mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
migrations
...
frankfurt
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0969ba97f1 | ||
|
|
b835338fe5 | ||
|
|
36cf718600 | ||
|
|
e7d7788bae | ||
|
|
1d989f7276 | ||
|
|
7d25cd4f1f | ||
|
|
0dca4007e4 | ||
|
|
08a6a08285 | ||
|
|
891ebcbe30 | ||
|
|
aa6b204513 | ||
|
|
06bc29bd5e | ||
|
|
6d08976b00 | ||
|
|
5764e0a7e6 | ||
|
|
7c44a43d4a | ||
|
|
661a101cb5 | ||
|
|
6f4dbc58f1 | ||
|
|
499da4f7f6 | ||
|
|
8da352fffe |
No files matched your search
Generated
+1769
-78
File diff suppressed because it is too large.
Load diff
+10
@@ -11,6 +11,8 @@ members = [
|
||||
"document/format",
|
||||
"document/graph-storage",
|
||||
"document/container",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -97,12 +99,16 @@ text-nodes = { path = "node-graph/nodes/text" }
|
||||
transform-nodes = { path = "node-graph/nodes/transform" }
|
||||
vector-nodes = { path = "node-graph/nodes/vector" }
|
||||
repeat-nodes = { path = "node-graph/nodes/repeat" }
|
||||
vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
||||
ollev = { git = "https://github.com/tagtraumen/ollev" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
peer-transport = { path = "document/peer-transport" }
|
||||
document-live = { path = "document/live" }
|
||||
raster-nodes = { path = "node-graph/nodes/raster" }
|
||||
graphene-std = { path = "node-graph/nodes/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
@@ -122,6 +128,7 @@ 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"] }
|
||||
@@ -170,6 +177,9 @@ web-sys = { version = "=0.3.98", features = [
|
||||
"Gpu",
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
"Lock",
|
||||
"LockManager",
|
||||
"LockOptions",
|
||||
] }
|
||||
winit = "0.31.0-beta.2"
|
||||
keyboard-types = "0.8"
|
||||
|
||||
@@ -18,6 +18,7 @@ accepted = [
|
||||
"NCSA", # Keep this list in sync with those in `/deny.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/deny.toml`
|
||||
]
|
||||
workarounds = ["ring"]
|
||||
ignore-build-dependencies = true
|
||||
|
||||
@@ -82,6 +82,7 @@ allow = [
|
||||
"NCSA", # Keep this list in sync with those in `/about.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/about.toml`
|
||||
]
|
||||
# The confidence threshold for detecting a license from license text.
|
||||
# The higher the value, the more closely the license text must be to the
|
||||
|
||||
+57
-2
@@ -16,6 +16,7 @@ use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::clock::InstantClock;
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::input::InputState;
|
||||
@@ -26,7 +27,7 @@ use crate::spawner::TokioSpawner;
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, Scheduling, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -54,6 +55,7 @@ pub(crate) struct App {
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
hide_ui: bool,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -102,6 +104,8 @@ impl App {
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
TokioSpawner::new(async_runtime.handle().clone()),
|
||||
Arc::new(InstantClock::new()),
|
||||
Scheduling::default(),
|
||||
editor_wake,
|
||||
runtime_wake,
|
||||
);
|
||||
@@ -112,7 +116,17 @@ impl App {
|
||||
loop {
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
// A frame starts after waiting out a deferred one or an idle wait, while a wake mid-frame continues the frame
|
||||
let next_frame = match node_runtime.until_next_frame() {
|
||||
Some(wait) => {
|
||||
thread::sleep(wait);
|
||||
true
|
||||
}
|
||||
None => start_render_receiver.recv_timeout(Duration::from_millis(10)).is_err(),
|
||||
};
|
||||
if next_frame {
|
||||
node_runtime.begin_frame();
|
||||
}
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
@@ -145,6 +159,7 @@ impl App {
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
hide_ui: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,6 +180,10 @@ impl App {
|
||||
}
|
||||
|
||||
fn resize(&mut self) {
|
||||
if self.hide_ui {
|
||||
self.handle_desktop_frontend_message(DesktopFrontendMessage::TmpToggleHideUI, &mut Vec::new());
|
||||
}
|
||||
|
||||
let Some(window) = &self.window else {
|
||||
tracing::error!("Resize failed due to missing window");
|
||||
return;
|
||||
@@ -290,6 +309,19 @@ impl App {
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
|
||||
|
||||
if self.hide_ui {
|
||||
if x != 0.0 && y != 0.0 {
|
||||
let message = DesktopWrapperMessage::TmpUpdateViewport {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
width: self.window_size.width as f64 / self.window_scale,
|
||||
height: self.window_size.height as f64 / self.window_scale,
|
||||
};
|
||||
self.dispatch_desktop_wrapper_message(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(render_state) = &mut self.render_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
@@ -308,6 +340,9 @@ impl App {
|
||||
self.input_state.set_direct_input(enabled);
|
||||
}
|
||||
DesktopFrontendMessage::UpdateUIScale { scale } => {
|
||||
if self.hide_ui {
|
||||
return;
|
||||
}
|
||||
self.ui_scale = scale;
|
||||
self.resize();
|
||||
}
|
||||
@@ -413,6 +448,22 @@ impl App {
|
||||
let message = DesktopWrapperMessage::LoadThirdPartyLicenses { text };
|
||||
responses.push(message);
|
||||
}
|
||||
|
||||
DesktopFrontendMessage::TmpToggleHideUI => {
|
||||
if self.hide_ui {
|
||||
self.hide_ui = false;
|
||||
} else {
|
||||
let message = DesktopWrapperMessage::TmpUpdateViewport {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
width: self.window_size.width as f64 / self.window_scale,
|
||||
height: self.window_size.height as f64 / self.window_scale,
|
||||
};
|
||||
self.dispatch_desktop_wrapper_message(message);
|
||||
self.render_state.as_mut().unwrap().unbind_ui_texture();
|
||||
self.hide_ui = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,6 +509,10 @@ impl App {
|
||||
}
|
||||
}
|
||||
AppEvent::UiUpdate(texture) => {
|
||||
if self.hide_ui {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(render_state) = self.render_state.as_mut() {
|
||||
render_state.bind_ui_texture(texture);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use crate::wrapper::Clock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The desktop's monotonic clock, measuring time since the app started it.
|
||||
pub(crate) struct InstantClock(Instant);
|
||||
|
||||
impl InstantClock {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for InstantClock {
|
||||
fn now(&self) -> Duration {
|
||||
self.0.elapsed()
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||
|
||||
mod app;
|
||||
mod cli;
|
||||
mod clock;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod gpu_context;
|
||||
|
||||
@@ -207,6 +207,11 @@ impl RenderState {
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
pub(crate) fn unbind_ui_texture(&mut self) {
|
||||
self.ui_texture = None;
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport_scale(&mut self, scale: [f32; 2]) {
|
||||
self.surface_outdated = true;
|
||||
self.viewport_scale = scale;
|
||||
|
||||
@@ -77,5 +77,10 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text: text };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
|
||||
DesktopWrapperMessage::TmpUpdateViewport { x, y, width, height } => {
|
||||
let message = ViewportMessage::TmpUpdateBounds { x, y, width, height };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerClipboardWrite { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
|
||||
}
|
||||
// The desktop app has no web origin to build the link from, so it points at the hosted editor.
|
||||
FrontendMessage::TriggerSessionLinkCopy { token } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
|
||||
content: format!("https://editor.graphite.rs/?session={token}"),
|
||||
});
|
||||
}
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
@@ -142,6 +148,10 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerDisplayThirdPartyLicensesDialog => {
|
||||
dispatcher.respond(DesktopFrontendMessage::LoadThirdPartyLicenses);
|
||||
}
|
||||
|
||||
FrontendMessage::TmpToggleHideUI => {
|
||||
dispatcher.respond(DesktopFrontendMessage::TmpToggleHideUI);
|
||||
}
|
||||
m => return Some(m),
|
||||
}
|
||||
None
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::Arc;
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
|
||||
pub use graphite_editor::task::{Spawn, Task};
|
||||
pub use graphite_editor::task::{Clock, Scheduling, Spawn, Task};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
@@ -35,12 +35,15 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn DocumentStore>,
|
||||
wgpu_context: WgpuContext,
|
||||
spawner: impl Spawn + Send + Sync + 'static,
|
||||
clock: Arc<dyn Clock>,
|
||||
scheduling: Scheduling,
|
||||
editor_wake: impl Fn() + Send + Sync + 'static,
|
||||
runtime_wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> (Self, NodeRuntime) {
|
||||
@@ -61,7 +64,13 @@ impl DesktopWrapper {
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_runtime(
|
||||
RuntimeBuilder::new()
|
||||
.with_wake(runtime_wake)
|
||||
.with_application_io(application_io)
|
||||
.with_clock(clock)
|
||||
.with_scheduling(scheduling),
|
||||
)
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
@@ -71,6 +71,8 @@ pub enum DesktopFrontendMessage {
|
||||
WindowShowAll,
|
||||
Restart,
|
||||
LoadThirdPartyLicenses,
|
||||
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
|
||||
pub enum DesktopWrapperMessage {
|
||||
@@ -87,6 +89,8 @@ pub enum DesktopWrapperMessage {
|
||||
ClipboardReadResult { content: Option<String> },
|
||||
PointerLockMove { x: f64, y: f64 },
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
|
||||
TmpUpdateViewport { x: f64, y: f64, width: f64, height: f64 },
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
|
||||
@@ -23,11 +23,14 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
|
||||
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
|
||||
zip = ["document-container/zip"]
|
||||
xz = ["document-container/xz"]
|
||||
default = ["conversion", "zip", "xz"]
|
||||
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
|
||||
network = ["dep:peer-transport"]
|
||||
default = ["conversion", "zip", "xz", "network"]
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-graph-storage = { workspace = true, default-features = false }
|
||||
peer-transport = { workspace = true, optional = true }
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
|
||||
@@ -50,4 +50,8 @@ pub enum Error {
|
||||
/// An export marked a resource for embedding but its bytes were absent from the byte store.
|
||||
#[error("embedded resource {0} missing from the byte store")]
|
||||
MissingResource(ResourceHash),
|
||||
/// A packet for the collaboration session failed to encode.
|
||||
#[cfg(feature = "network")]
|
||||
#[error("network error: {0}")]
|
||||
Network(#[from] peer_transport::PacketError),
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
|
||||
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
|
||||
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
|
||||
@@ -151,6 +151,8 @@ impl<L: Layout> Gdd<L> {
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
// An export is a copy taken out of the room; it does not reconnect on its own.
|
||||
shared: false,
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
@@ -158,6 +160,13 @@ impl<L: Layout> Gdd<L> {
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
|
||||
if !self.metadata.is_empty() {
|
||||
let mut facts = Vec::new();
|
||||
for fact in self.metadata.facts() {
|
||||
METADATA_CODEC.append(&mut facts, &fact)?;
|
||||
}
|
||||
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &facts)?;
|
||||
}
|
||||
|
||||
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ pub trait Layout {
|
||||
fn registry_basename(&self) -> &str;
|
||||
fn history_basename(&self) -> &str;
|
||||
fn hot_log_basename(&self) -> &str;
|
||||
/// What people state about the history beside it: users and their names, later labels and tags.
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
@@ -39,6 +41,9 @@ impl Layout for GddV1Layout {
|
||||
fn hot_log_basename(&self) -> &str {
|
||||
"hot-log"
|
||||
}
|
||||
fn metadata_basename(&self) -> &str {
|
||||
"metadata"
|
||||
}
|
||||
fn resources_dir(&self) -> &str {
|
||||
"resources"
|
||||
}
|
||||
|
||||
+108
-10
@@ -10,16 +10,17 @@
|
||||
// gated off wasm to avoid unused-import warnings.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
use graphene_resource::{ResourceHash, ResourceStorage};
|
||||
|
||||
pub mod codec;
|
||||
pub mod error;
|
||||
@@ -27,6 +28,8 @@ pub mod export;
|
||||
pub mod io;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
#[cfg(feature = "network")]
|
||||
pub mod network;
|
||||
pub mod persist;
|
||||
pub mod resource;
|
||||
pub mod session_state;
|
||||
@@ -52,6 +55,8 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
/// 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;
|
||||
/// Facts are appended one per line and folded on read, so the file is never rewritten.
|
||||
pub const METADATA_CODEC: Codec = Codec::JsonLines;
|
||||
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;
|
||||
@@ -65,8 +70,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
/// read.
|
||||
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
|
||||
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||
#[derive(Clone)]
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
|
||||
/// not carried over.
|
||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) working: AnyContainer,
|
||||
@@ -75,12 +80,74 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
/// and synchronous.
|
||||
pub(crate) manifest: Manifest,
|
||||
/// What people state about the history, such as user names. Kept in its own file, merged last-writer-wins
|
||||
/// with every copy met, never folded or undone.
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
/// Wall clock in Unix-epoch milliseconds as the editor last reported it, so retirements can record when
|
||||
/// they happened. `None` when nothing ticks, as in the CLI or tests.
|
||||
pub(crate) wall_clock_ms: Option<f64>,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
/// 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>>,
|
||||
/// Where resource bytes live. `None` means the working copy's own content-addressed store; the editor
|
||||
/// points this at its application-wide cache.
|
||||
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
/// What peers changed since the editor last took it, so it can reconcile its runtime mirror without a rebuild.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// When each closed interaction was first seen, by marker, so the retirement policy can age it. Not
|
||||
/// persisted: after a reopen everything pending is old enough.
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
/// When this peer last staged an op, so an interaction the editor left open can be closed once quiet.
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
/// Whether an op of this peer's own was staged since the last policy tick.
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
/// Whether the document should be in its room: set by sharing, cleared by disconnecting, persisted so
|
||||
/// a reopen reconnects.
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
|
||||
/// Whole-file rewrites deferred to the end of a poll, so a batch of remote packets costs one rewrite per
|
||||
/// file, not one per packet.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(crate) struct PendingPersist {
|
||||
pub(crate) history: bool,
|
||||
pub(crate) hot_log: bool,
|
||||
pub(crate) snapshot: bool,
|
||||
}
|
||||
|
||||
impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
session: self.session.clone(),
|
||||
working: self.working.clone(),
|
||||
layout: self.layout.clone(),
|
||||
manifest: self.manifest.clone(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
metadata: self.metadata.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
byte_store: self.byte_store.clone(),
|
||||
shared: self.shared,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
@@ -98,10 +165,10 @@ impl<L: Layout + Default> Gdd<L> {
|
||||
|
||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||
let layout = L::default();
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
||||
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +203,10 @@ impl<L: Layout> Gdd<L> {
|
||||
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
|
||||
false => SessionState::default(),
|
||||
};
|
||||
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
|
||||
true => HistoryMetadata::fold(io::iter::<MetadataFact>(&working, layout.metadata_basename(), METADATA_CODEC).await?),
|
||||
false => HistoryMetadata::default(),
|
||||
};
|
||||
|
||||
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
@@ -160,11 +231,12 @@ impl<L: Layout> Gdd<L> {
|
||||
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.last_hot_sequence);
|
||||
session.restore_clock_counter(session_state.clock_counter);
|
||||
// Before the hot log replays, so a retired op in it is dropped rather than staged again.
|
||||
session.absorb_retired_marks(&session_state.retired_marks);
|
||||
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -174,23 +246,36 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
shared: session_state.shared,
|
||||
metadata,
|
||||
wall_clock_ms: None,
|
||||
byte_store: None,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||
/// the manifest and writes each payload with its recorded codec.
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
user_id: user,
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
let session = Session::with_identity(peer, user);
|
||||
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -200,6 +285,19 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
metadata: HistoryMetadata::default(),
|
||||
wall_clock_ms: None,
|
||||
byte_store: None,
|
||||
shared: false,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
|
||||
//! then broadcasts staged hot ops, and retired deltas when hosting. `poll_peers` applies what peers
|
||||
//! send through the [`SyncTarget`] impl below, which persists it like local edits.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, Touched, UserId};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::{Gdd, PendingPersist};
|
||||
|
||||
/// What peers changed in the working registry since the editor last asked, so the editor can reconcile
|
||||
/// just the touched entities of its runtime mirror.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Takes what peers changed since the last call. Empty when nothing did.
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
/// Connect to this document's room as host or guest, and remember it is shared so a reopen reconnects.
|
||||
pub fn connect(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
|
||||
self.network = Some(Replica::connect(transport, self.session.peer(), user));
|
||||
self.shared = true;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Whether the document is meant to be in its room; see [`connect`](Self::connect).
|
||||
pub fn is_shared(&self) -> bool {
|
||||
self.shared
|
||||
}
|
||||
|
||||
/// Take the host role if none is present once the grace period ends. See [`Replica::decide_role`].
|
||||
pub fn decide_role(&mut self) -> Option<Role> {
|
||||
self.network.as_mut().and_then(Replica::decide_role)
|
||||
}
|
||||
|
||||
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::guest(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
/// Leaves the room. A host first retires every closed interaction, so finished work reaches history before
|
||||
/// the retirer leaves.
|
||||
pub fn leave(&mut self) {
|
||||
self.shared = false;
|
||||
if let Err(error) = self.persist_session_state() {
|
||||
log::error!("Persisting the session state before leaving failed: {error}");
|
||||
}
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
/// Drops the connection but keeps the document shared, for a transport that went down, so a reopen reconnects.
|
||||
pub fn disconnect(&mut self) {
|
||||
let closed = self.session.closed_interactions();
|
||||
if let Err(error) = self.retire_interactions(&closed) {
|
||||
log::error!("Retiring before leaving failed: {error}");
|
||||
}
|
||||
if let Some(mut replica) = self.network.take() {
|
||||
replica.leave();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.network.as_ref().map(Replica::role)
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.network.as_ref().is_none_or(Replica::is_synced)
|
||||
}
|
||||
|
||||
/// Announce this peer's display name to the room; a no-op when it has not changed or nobody is connected.
|
||||
pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.set_name(name)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send this peer's pointer position, `None` when it left the viewport.
|
||||
pub fn send_cursor(&mut self, position: Option<peer_transport::CursorPosition>) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_cursor(position)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The other peers in the room; empty when the document is not connected.
|
||||
pub fn peers(&self) -> Vec<peer_transport::RemotePeer> {
|
||||
self.network.as_ref().map(|replica| replica.peers().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.session.mark_runtime_current();
|
||||
}
|
||||
|
||||
pub fn poll_peers(&mut self) -> Vec<Event> {
|
||||
let Some(mut replica) = self.network.take() else { return Vec::new() };
|
||||
let events = replica.poll(self);
|
||||
self.network = Some(replica);
|
||||
events
|
||||
}
|
||||
|
||||
/// Answer an [`Event::ResourceRequested`].
|
||||
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_resource(to, hash, bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
fn peer(&self) -> PeerId {
|
||||
self.session.peer()
|
||||
}
|
||||
|
||||
fn document_id(&self) -> Option<u64> {
|
||||
Some(self.manifest.document_id)
|
||||
}
|
||||
|
||||
fn adopt_document_id(&mut self, document_id: u64) -> Result<(), TargetError> {
|
||||
self.update_manifest(|manifest| manifest.document_id = document_id)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.session.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
self.session.retired_registry().clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
self.session.hot_log().to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
self.session.known_revs()
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.session.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta> {
|
||||
let deltas = <Session as SyncTarget>::deltas_unknown_to(&mut self.session, known);
|
||||
// The published frontier moved; it persists with the session state.
|
||||
self.pending_persist.snapshot |= !deltas.is_empty();
|
||||
deltas
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
self.session.load(registry, history, head)?;
|
||||
self.remote_changes.rebuilt = true;
|
||||
self.pending_persist = PendingPersist {
|
||||
history: true,
|
||||
hot_log: true,
|
||||
snapshot: true,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// An op naming an entity not yet here is handed back for retry; only applied ops reach the hot frame log.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
// Recorded even if the apply fails: it may still have revived what it references.
|
||||
self.remote_changes.touched.record(&hot_op.op);
|
||||
if self.session.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
continue;
|
||||
}
|
||||
self.append_hot_frame(&hot_op)?;
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
|
||||
let incoming: HashSet<Rev> = deltas.iter().map(|delta| delta.id).collect();
|
||||
let length_before = self.session.history_len();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
SyncTarget::merge_remote(&mut self.session, deltas, retires, head)?;
|
||||
|
||||
// Whatever a peer sent is already shared, so it sits behind the published frontier and cannot be silently rewound.
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
|
||||
// A batch that only extended history, plus any merge delta joining it, is appended to the file; one that
|
||||
// sorted earlier deltas after it rewrites the file.
|
||||
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
|
||||
let appended = tail
|
||||
.iter()
|
||||
.all(|&rev| incoming.contains(&rev) || self.session.delta(rev).is_some_and(|delta| matches!(delta.kind, RegistryDelta::Merge { .. })));
|
||||
match appended {
|
||||
true => self.append_history_deltas(&tail)?,
|
||||
false => self.pending_persist.history = true,
|
||||
}
|
||||
self.pending_persist.hot_log |= !retires.is_empty();
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
|
||||
let length_before = self.session.history_len();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
let absorbed = SyncTarget::merge_divergent(&mut self.session, deltas, retires)?;
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
|
||||
// Appended when the tail is just the absorbed deltas and their merge; see `merge_remote`.
|
||||
let absorbed_ids: HashSet<Rev> = absorbed.iter().map(|delta| delta.id).collect();
|
||||
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
|
||||
match tail.iter().all(|rev| absorbed_ids.contains(rev)) {
|
||||
true => self.append_history_deltas(&tail)?,
|
||||
false => self.pending_persist.history = true,
|
||||
}
|
||||
self.pending_persist.hot_log |= !retires.is_empty();
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(absorbed)
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
SyncTarget::retired_marks(&self.session)
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
let touched = self.session.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.hot_log = true;
|
||||
// Also writes the session state, which carries the marks.
|
||||
self.pending_persist.snapshot = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn metadata(&self) -> HistoryMetadata {
|
||||
self.metadata.clone()
|
||||
}
|
||||
|
||||
fn absorb_metadata(&mut self, remote: &HistoryMetadata) -> Result<bool, TargetError> {
|
||||
let landed = self.metadata.merge(remote);
|
||||
if landed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
self.append_facts(&landed)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
|
||||
let touched = self.session.retract_hot_ops(ops);
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
|
||||
let touched = self.session.apply_head_move(moved)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
let pending = std::mem::take(&mut self.pending_persist);
|
||||
|
||||
if pending.history {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
if pending.hot_log {
|
||||
self.rewrite_hot_log()?;
|
||||
}
|
||||
if pending.snapshot {
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.unstored_resources().into_iter().collect()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
self.hold_resource(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+370
-58
@@ -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::{Delta, HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
@@ -35,6 +35,16 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Set the person using this device. A change re-registers the peer on its next staged batch, and the newer
|
||||
/// registration wins everywhere.
|
||||
pub fn set_user(&mut self, user: UserId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
return Ok(());
|
||||
}
|
||||
self.session.set_user(user);
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Edit the cached manifest and persist it. Always JSON, synchronous.
|
||||
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
|
||||
edit(&mut self.manifest);
|
||||
@@ -62,10 +72,7 @@ impl<L: Layout> Gdd<L> {
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
self.persist_staged(&hot_ops)?;
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
@@ -80,34 +87,41 @@ impl<L: Layout> Gdd<L> {
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
/// hot frame, is broadcast to any session, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(())
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
|
||||
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
|
||||
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
|
||||
/// are no pending hot ops.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
self.retire_inner(up_to, true)
|
||||
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops.into_iter().collect())?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Every staged hot op ends here: the frame that survives a crash, then the broadcast that reaches the room.
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
|
||||
@@ -139,24 +153,34 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
|
||||
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
|
||||
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
|
||||
/// retired `Rev`s. A no-op when nothing was staged.
|
||||
/// Persist freshly-staged hot ops and retire exactly them into durable history as one unit. Frames are
|
||||
/// appended first, so a crash before retirement still recovers the work. Returns the retired `Rev`s;
|
||||
/// on a peer that does not retire the ops stay hot.
|
||||
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
|
||||
|
||||
if hot_ops.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
self.retire_inner(last.timestamp, interaction_end)
|
||||
let ids: Vec<_> = hot_ops.iter().map(HotOp::id).collect();
|
||||
let revs = self.session.retire_hot_ops(&ids)?;
|
||||
// Marked before the history frames are written, so the boundary is on disk with them.
|
||||
if interaction_end && let Some(&last) = revs.last() {
|
||||
self.session.mark_interaction_end(last);
|
||||
}
|
||||
self.finish_retirement(&revs, &ids)?;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
|
||||
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
|
||||
/// preserves replay order without scanning the whole history.
|
||||
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
|
||||
pub(crate) fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for &rev in revs {
|
||||
let Some(delta) = self.session.delta(rev) else {
|
||||
@@ -171,7 +195,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
|
||||
/// 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
|
||||
/// 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> {
|
||||
if self.session.annotate_delta(rev, key, value) {
|
||||
@@ -184,7 +208,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in self.session.history() {
|
||||
self.manifest.codecs.history.append(&mut buffer, delta)?;
|
||||
@@ -193,7 +217,58 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
/// What people state about the history, such as user names.
|
||||
pub fn metadata(&self) -> &HistoryMetadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// Record a fact about a user at wall time `wall_ms`, persisted and told to the room. Returns whether it
|
||||
/// changed anything.
|
||||
pub fn record_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms.max(0.) as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.set_user_attribute(user, key, value, stamp) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.append_facts(&[fact])?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_metadata(&self.metadata)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Record a fact about a rev, such as a label or tag on the interaction it closes. Otherwise like
|
||||
/// [`record_user_attribute`](Self::record_user_attribute).
|
||||
pub fn record_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms.max(0.) as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.set_rev_attribute(rev, key, value, stamp) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.append_facts(&[fact])?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_metadata(&self.metadata)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Append facts to the metadata file, one line each; the file is never rewritten.
|
||||
pub(crate) fn append_facts(&mut self, facts: &[MetadataFact]) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for fact in facts {
|
||||
METADATA_CODEC.append(&mut buffer, fact)?;
|
||||
}
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
@@ -202,6 +277,7 @@ impl<L: Layout> Gdd<L> {
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
shared: self.shared,
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
@@ -213,7 +289,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
pub(crate) 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())?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -242,45 +318,281 @@ impl<L: Layout> Gdd<L> {
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
|
||||
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
|
||||
/// re-snapshot the registry. Synchronous.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
|
||||
self.retire_inner(up_to, false)
|
||||
/// How many closed interactions must be waiting before they retire. Retiring later fuses more of a gesture
|
||||
/// into one delta and leaves more for undo to rewind silently.
|
||||
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
|
||||
/// How long a closed interaction sits before it may retire, so every peer has seen all of it.
|
||||
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
|
||||
/// The longest anything waits: a quiet session still retires, and an interaction with a gap in its author's
|
||||
/// run retires with what arrived.
|
||||
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
|
||||
|
||||
/// Closes this peer's open interaction, if any, with a marker broadcast like any other hot op. The editor
|
||||
/// calls this at each undo-step boundary.
|
||||
pub fn end_interaction(&mut self) -> Result<(), Error> {
|
||||
let staged = self.session.end_interaction()?;
|
||||
self.persist_staged(&staged)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
|
||||
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
|
||||
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
let new_revs = self.session.retire(up_to)?;
|
||||
/// Undo this peer's latest interaction while it is still hot: its ops leave the hot log here, and on every
|
||||
/// peer the retraction reaches, and never retire. `None` means the step already retired and undo has to
|
||||
/// move the cursor. What the ops named lands in the remote changes, so the mirror picks up what others
|
||||
/// wrote there meanwhile.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(document_graph_storage::Retraction { ids, touched, ops }) = self.session.retract_interaction()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.own_last_staged_ms = None;
|
||||
#[cfg(feature = "network")]
|
||||
self.remote_changes.touched.extend(touched);
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = touched;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&ids)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = ids;
|
||||
Ok(Some(ops))
|
||||
}
|
||||
|
||||
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
|
||||
if interaction_end && let Some(&last) = new_revs.last() {
|
||||
self.session.mark_interaction_end(last);
|
||||
/// Undo this peer's latest retired step, the one [`Session::latest_own_interaction`] names, through
|
||||
/// [`drop_step`](Self::drop_step). `None` when this peer has no retired step of its own on the line.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.drop_step(rev)?;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
/// Drop a retired interaction out of the line, later steps minted again on its parent; see
|
||||
/// [`Session::drop_interaction`]. The retirer does it, records what it named in the remote changes and
|
||||
/// tells the room; anyone else asks the retirer and sees the head move come back through the poll.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.rewrite_history()?;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the head to an ancestor in a session, everything since staying as a branch; see
|
||||
/// [`Session::move_head_to`]. The retirer does it and tells the room; anyone else asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_move(rev)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Redo a step [`undo_retired_step`](Self::undo_retired_step) dropped, as a copy on top of the line.
|
||||
/// The retirer does it; anyone else asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
self.rewrite_history()?;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage ops a retraction took back as a fresh interaction, recording them as changes for the mirror:
|
||||
/// redoing a retracted step is a new edit to everyone, this peer included.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
#[cfg(feature = "network")]
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every interaction the policy says is due at `now_ms`, the wall clock in milliseconds that retirements
|
||||
/// also record: closed interactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS), once
|
||||
/// [`RETIRE_AFTER_INTERACTIONS`](Self::RETIRE_AFTER_INTERACTIONS) of them are waiting or the oldest has waited
|
||||
/// [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). Open interactions never retire. The editor calls this every
|
||||
/// frame with whether it is between steps; a peer that does not retire only closes its own quiet interaction.
|
||||
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
|
||||
// The editor passes the wall clock, which retirements record as when a step happened.
|
||||
self.wall_clock_ms = Some(now_ms);
|
||||
// An interaction the editor never closed, or one cut off by a reopen, closes once quiet, but only between
|
||||
// steps: a pause mid-gesture must not split what undo takes back as one.
|
||||
if self.own_staged_since_tick {
|
||||
self.own_staged_since_tick = false;
|
||||
self.own_last_staged_ms = Some(now_ms);
|
||||
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let closed = self.session.closed_interactions();
|
||||
let mut seen = std::mem::take(&mut self.interactions_seen);
|
||||
let mut due = Vec::new();
|
||||
let mut oldest_age: f64 = 0.0;
|
||||
for interaction in &closed {
|
||||
let Some(&marker) = interaction.ops.last() else { continue };
|
||||
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
|
||||
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
|
||||
due.push(interaction.clone());
|
||||
oldest_age = oldest_age.max(age);
|
||||
}
|
||||
}
|
||||
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
|
||||
self.interactions_seen = seen;
|
||||
|
||||
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
|
||||
self.retire_interactions(&due)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one, whoever authored it. The undo path calls
|
||||
/// this first so the interaction being undone is in history; a peer that does not retire only closes its own.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
let closed = self.session.closed_interactions();
|
||||
self.retire_interactions(&closed)
|
||||
}
|
||||
|
||||
/// Retire the given closed interactions, each as one undo step, in one history append and one
|
||||
/// broadcast. A no-op for a peer that leaves retirement to the session host.
|
||||
pub(crate) fn retire_interactions(&mut self, interactions: &[document_graph_storage::ClosedInteraction]) -> Result<Vec<Rev>, Error> {
|
||||
if !self.retires_locally() || interactions.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut revs = Vec::new();
|
||||
let mut retired_hot_ops = Vec::new();
|
||||
for interaction in interactions {
|
||||
revs.extend(self.session.retire_interaction(interaction)?);
|
||||
retired_hot_ops.extend(interaction.ops.iter().copied());
|
||||
}
|
||||
self.finish_retirement(&revs, &retired_hot_ops)?;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Working-copy checkpoint: retire every hot op stamped at or before `up_to`, whatever its author or
|
||||
/// interaction state. For callers that own the whole log; a session uses [`retire_interactions`](Self::retire_interactions).
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
|
||||
let revs = self.session.retire(up_to)?;
|
||||
self.finish_retirement(&revs, &retired_hot_ops)?;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// What every retirement ends with: the published frontier moves, the deltas reach the history file,
|
||||
/// the hot log and snapshot are rewritten, and the room hears about it.
|
||||
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
|
||||
// Stamped before the frames are written, so the time is on disk and in the broadcast.
|
||||
if let Some(wall_ms) = self.wall_clock_ms
|
||||
&& !new_revs.is_empty()
|
||||
{
|
||||
self.session.stamp_retired_at(new_revs, wall_ms as u64);
|
||||
}
|
||||
// These deltas are about to reach peers, so the published frontier moves with them: rewinding a commit
|
||||
// peers hold would silently diverge, so undo past it moves the shared head instead. Set before the
|
||||
// persists below so it survives a reopen.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = new_revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
|
||||
if !new_revs.is_empty() {
|
||||
self.append_history_deltas(&new_revs)?;
|
||||
self.append_history_deltas(new_revs)?;
|
||||
}
|
||||
|
||||
// Rewrite hot log with whatever survived retirement.
|
||||
let mut hot_buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
|
||||
}
|
||||
self.working
|
||||
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
|
||||
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
|
||||
Ok(new_revs)
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
replica.broadcast_retired(&deltas, retired_hot_ops)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = retired_hot_ops;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// Guests leave retirement to the host and keep their hot ops until its retired deltas arrive.
|
||||
fn retires_locally(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
{
|
||||
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
|
||||
}
|
||||
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -90,6 +91,35 @@ impl<L: Layout> Gdd<L> {
|
||||
{
|
||||
ResourceProxy(self.working.clone(), self.layout.clone())
|
||||
}
|
||||
|
||||
/// Point resource lookups at an external store, for an embedder keeping one cache for every open document.
|
||||
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
|
||||
self.byte_store = Some(byte_store);
|
||||
}
|
||||
|
||||
/// Whether this document's resource bytes are on hand, in whichever store backs it.
|
||||
pub(crate) fn holds_resource(&self, hash: &ResourceHash) -> bool {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => byte_store.contains(hash),
|
||||
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put resource bytes into whichever store backs this document.
|
||||
pub(crate) fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => {
|
||||
byte_store.store(bytes);
|
||||
Ok(())
|
||||
}
|
||||
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resources the registry or its history names whose bytes are not on hand.
|
||||
pub(crate) fn unstored_resources(&self) -> Vec<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
@@ -103,6 +133,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
||||
|
||||
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -34,9 +34,6 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
||||
#[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)]
|
||||
@@ -45,6 +42,12 @@ pub struct SessionState {
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default)]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Whether the document was in its room when last persisted, so a reopen reconnects.
|
||||
#[serde(default)]
|
||||
pub shared: bool,
|
||||
/// The retired hot op marks, so a late copy re-sent after a reopen is dropped rather than retired again.
|
||||
#[serde(default)]
|
||||
pub retired_marks: RetiredMarks,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// History metadata: persisted with the working copy and merged with every copy met.
|
||||
// Needs the network feature for a session and the runtime conversion for staging ops.
|
||||
#![cfg(all(feature = "conversion", feature = "network"))]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::from_runtime::DeclarationBytes;
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, TimeStamp, UserId, rev_attr, user_attr};
|
||||
use peer_transport::mock::MockNetwork;
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
|
||||
async fn document(peer: u64, user: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Let the room settle: greetings, the sync handshake and whatever was broadcast.
|
||||
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
|
||||
for _ in 0..16 {
|
||||
for peer in peers.iter_mut() {
|
||||
peer.poll_peers();
|
||||
}
|
||||
network.deliver_all();
|
||||
}
|
||||
for peer in peers.iter_mut() {
|
||||
peer.poll_peers();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_name_survives_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10).await;
|
||||
assert!(gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
assert!(
|
||||
!gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
|
||||
"the same name is no change"
|
||||
);
|
||||
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
assert!(gdd.record_rev_attribute(step, rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
|
||||
assert!(gdd.record_rev_attribute(step, "tag:v1", true.into(), NOW_MS).expect("record"));
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
|
||||
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_reach_the_room_with_the_sync_and_as_they_change() {
|
||||
futures::executor::block_on(async {
|
||||
let mut host = document(1, 10).await;
|
||||
let mut guest = document(2, 20).await;
|
||||
host.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
// A name given before joining travels with the joiner and reaches the host.
|
||||
guest.record_user_attribute(UserId(20), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
|
||||
let mut network = MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10));
|
||||
guest.join(guest_endpoint, UserId(20));
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
|
||||
// A rename while in the room goes round on its own.
|
||||
assert!(guest.record_user_attribute(UserId(20), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retirement_records_when_it_happened() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10).await;
|
||||
// The editor's per-frame tick is where the wall clock comes from.
|
||||
gdd.retire_due(NOW_MS, true).expect("tick");
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
gdd.stage_constructed_ops(
|
||||
vec![RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}],
|
||||
&DeclarationBytes::default(),
|
||||
&byte_store,
|
||||
)
|
||||
.expect("stage");
|
||||
let everything = TimeStamp {
|
||||
counter: u64::MAX,
|
||||
peer: PeerId(u64::MAX),
|
||||
};
|
||||
let revs = gdd.retire(everything).expect("retire");
|
||||
assert!(!revs.is_empty());
|
||||
for rev in revs {
|
||||
let delta = gdd.session().delta(rev).expect("retired delta");
|
||||
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
@@ -97,7 +97,7 @@ fn manifest_returns_what_create_in_wrote() {
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
@@ -112,7 +112,7 @@ fn update_manifest_changes_visible_after_reopen() {
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||
// produces one network in the registry.
|
||||
@@ -139,7 +139,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||
let early = HotOp {
|
||||
@@ -187,7 +187,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Retire one op so there is a real retired rev to mark as published.
|
||||
let op = HotOp {
|
||||
@@ -218,7 +218,7 @@ fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
@@ -246,7 +246,7 @@ fn export_zip_round_trips_via_deserialize() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -271,7 +271,7 @@ fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
@@ -294,7 +294,7 @@ fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -324,7 +324,7 @@ fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -353,7 +353,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -377,7 +377,7 @@ fn export_carries_resources() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -405,7 +405,7 @@ fn embed_all_resources_materializes_link_only_resource() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||
// byte store; the working copy never holds them.
|
||||
@@ -470,7 +470,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||
let payload = b"embedded bytes in the cache";
|
||||
@@ -511,7 +511,7 @@ fn export_round_trips_unretired_hot_ops() {
|
||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -564,7 +564,7 @@ fn open_in_rejects_future_format_version() {
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
@@ -585,7 +585,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
@@ -627,7 +627,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -680,7 +680,7 @@ fn declarations_round_trip_through_byte_store() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
@@ -708,7 +708,7 @@ fn an_export_without_history_drops_tombstones() {
|
||||
use document_graph_storage::{Network, NetworkId, RegistryDelta};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let id = NetworkId(7);
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
attributes: Default::default(),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
@@ -80,28 +80,24 @@ fn a_reopen_continues_the_hot_op_sequence() {
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set(1)]).unwrap();
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = stage(&mut gdd, set(2));
|
||||
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let last = reopened.session().last_hot_sequence();
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Needs the runtime conversion for `stage_constructed_ops` and the network feature for a session.
|
||||
#![cfg(all(feature = "conversion", feature = "network"))]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::from_runtime::DeclarationBytes;
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, UserId};
|
||||
use peer_transport::mock::MockNetwork;
|
||||
|
||||
/// Every staging path has to reach the room. Pins a regression where the recorded-batch path persisted its hot frames
|
||||
/// but never sent them.
|
||||
#[test]
|
||||
fn staging_a_constructed_batch_reaches_the_room() {
|
||||
futures::executor::block_on(async {
|
||||
let mut host = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
|
||||
let mut network = MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(1));
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
|
||||
// Greet the guest so the host can send to it, and get the hello out of the way.
|
||||
host.poll_peers();
|
||||
network.deliver_all();
|
||||
assert_eq!(network.pending(), 0);
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
let staged = host
|
||||
.stage_constructed_ops(
|
||||
vec![RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}],
|
||||
&DeclarationBytes::default(),
|
||||
&byte_store,
|
||||
)
|
||||
.expect("stage");
|
||||
|
||||
assert!(!staged.is_empty(), "the staged hot ops come back for the caller");
|
||||
assert!(network.pending() > 0, "a staged batch must be broadcast to the room");
|
||||
});
|
||||
}
|
||||
@@ -211,6 +211,8 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
/// Changes nothing and only carries its hot op's attributes, such as the end of an interaction staged after its last
|
||||
/// write. Retirement drops it.
|
||||
Meta,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
|
||||
@@ -2,8 +2,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId,
|
||||
NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -16,7 +16,7 @@ pub struct Document {
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
|
||||
pub(crate) hot_timestamps: HashSet<TimeStamp>,
|
||||
/// Which hot ops are retired into history, so a late copy is dropped.
|
||||
/// Which hot ops are done with (retired, or taken back by their author), so a late copy is dropped.
|
||||
pub(crate) retired: RetiredMarks,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
@@ -112,12 +112,36 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
|
||||
/// Record newly retired hot ops, dropping any the hot log still holds. Returns what the dropped ops named.
|
||||
pub(crate) fn mark_retired(&mut self, retired: impl IntoIterator<Item = HotOpId>) -> crate::Touched {
|
||||
self.retired.extend(retired);
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns what the dropped ops named.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> crate::Touched {
|
||||
self.retired.absorb(remote);
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
|
||||
/// Take back hot ops for good, re-deriving the working registry without them, since a commuting op
|
||||
/// cannot be undone in place. Returns what the ops named and the ops themselves.
|
||||
pub(crate) fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> (crate::Touched, Vec<HotOp>) {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let taken: Vec<HotOp> = self.hot_log.extract_if(.., |hot_op| wanted.contains(&hot_op.id())).collect();
|
||||
taken.iter().for_each(|hot_op| _ = self.hot_timestamps.remove(&hot_op.timestamp));
|
||||
self.retired.extend(ids.iter().copied());
|
||||
|
||||
let mut touched = crate::Touched::default();
|
||||
for hot_op in &taken {
|
||||
touched.record(&hot_op.op);
|
||||
}
|
||||
if !taken.is_empty() {
|
||||
self.rebuild_working();
|
||||
}
|
||||
(touched, taken)
|
||||
}
|
||||
|
||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
||||
pub(crate) fn resync_hot_timestamps(&mut self) {
|
||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
@@ -133,17 +157,17 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop retired hot ops and re-derive working without them: their effect returns with their deltas.
|
||||
fn drop_retired_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
/// Drop retired hot ops and re-derive working without them: a retired op's effect returns with its delta.
|
||||
fn drop_retired_hot_ops(&mut self) -> crate::Touched {
|
||||
let retired = &self.retired;
|
||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
if dropped {
|
||||
let dropped: Vec<HotOp> = self.hot_log.extract_if(.., |hot_op| retired.covers(hot_op.id())).collect();
|
||||
let mut touched = crate::Touched::default();
|
||||
if !dropped.is_empty() {
|
||||
dropped.iter().for_each(|hot_op| touched.record(&hot_op.op));
|
||||
self.resync_hot_timestamps();
|
||||
self.rebuild_working();
|
||||
}
|
||||
dropped
|
||||
touched
|
||||
}
|
||||
|
||||
/// Apply a retired commit and record it in history.
|
||||
|
||||
@@ -37,6 +37,11 @@ impl History {
|
||||
history
|
||||
}
|
||||
|
||||
/// Where `rev` sits in the file order, if it is here.
|
||||
pub(crate) fn position(&self, rev: Rev) -> Option<usize> {
|
||||
self.index.get(&rev).copied()
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
self.index.get(&rev).map(|&position| &self.deltas[position])
|
||||
}
|
||||
@@ -50,6 +55,15 @@ impl History {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
/// Whether the deltas from `from` on already sit in canonical order, as a single-parent chain off the delta
|
||||
/// before them, as a retirement appends: each link is the sort's only candidate at its step.
|
||||
pub(crate) fn extends_canonically(&self, from: usize) -> bool {
|
||||
(from..self.deltas.len()).all(|position| {
|
||||
let delta = &self.deltas[position];
|
||||
delta.parent == position.checked_sub(1).map(|previous| self.deltas[previous].id) && !matches!(delta.kind, RegistryDelta::Merge { .. })
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -90,22 +104,17 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
/// The delta at `position` in topological order.
|
||||
pub(crate) fn at(&self, position: usize) -> Option<&Delta> {
|
||||
self.deltas.get(position)
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
///
|
||||
/// Deterministic: peers that absorb the same delta set end up with byte-identical history, whatever the
|
||||
/// arrival order.
|
||||
pub(crate) fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
@@ -159,6 +168,37 @@ impl History {
|
||||
seen
|
||||
}
|
||||
|
||||
pub(crate) 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(crate) fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
|
||||
let mut samples = vec![tip];
|
||||
let mut current = tip;
|
||||
let mut distance = 0_usize;
|
||||
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
|
||||
current = parent;
|
||||
distance += 1;
|
||||
if distance.is_power_of_two() {
|
||||
samples.push(current);
|
||||
}
|
||||
}
|
||||
// Always the root: copies of one document share it however far they diverged, so the answering peer
|
||||
// can tell a divergent copy from a stranger and merge rather than replace.
|
||||
if samples.last() != Some(¤t) {
|
||||
samples.push(current);
|
||||
}
|
||||
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> {
|
||||
@@ -179,6 +219,13 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record when a retired delta entered history (outside its `Rev`). Returns whether the delta was found.
|
||||
pub(crate) fn set_retired_at(&mut self, rev: Rev, wall_ms: u64) -> bool {
|
||||
let Some(&position) = self.index.get(&rev) else { return false };
|
||||
self.deltas[position].retired_at_ms = wall_ms;
|
||||
true
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! What people say about a document's history, kept beside it rather than in it: user names, step labels
|
||||
//! and tags. None of it is folded into the document, so moving the head never changes it and stating it
|
||||
//! never rewrites a delta. Each [`MetadataFact`] carries a wall-clock stamp and the newer of two about the
|
||||
//! same thing wins, so the record merges the same in any order and any number of times. On disk the facts
|
||||
//! are appended one per line and folded on read, so nothing is ever rewritten.
|
||||
|
||||
use crate::ids::{PeerId, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct WallStamp {
|
||||
pub ms: u64,
|
||||
pub peer: PeerId,
|
||||
}
|
||||
|
||||
/// What a fact is about.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Subject {
|
||||
User(UserId),
|
||||
Rev(Rev),
|
||||
}
|
||||
|
||||
/// One statement: an attribute of a user or of a rev, with its stamp. The unit of the file and of a merge.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MetadataFact {
|
||||
pub subject: Subject,
|
||||
pub key: String,
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// One stated value with its stamp, as the folded record holds it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Fact {
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// Everything on record about one user.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UserRecord {
|
||||
pub user: UserId,
|
||||
pub attributes: BTreeMap<String, Fact>,
|
||||
}
|
||||
|
||||
/// Everything on record about one rev, which stands for the interaction it closes.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RevRecord {
|
||||
pub rev: Rev,
|
||||
pub attributes: BTreeMap<String, Fact>,
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a user.
|
||||
pub mod user_attr {
|
||||
/// The display name the user chose. Absent or empty means unnamed.
|
||||
pub const NAME: &str = "name";
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a rev.
|
||||
pub mod rev_attr {
|
||||
/// The name a person gave the interaction the rev closes. Absent or empty means unnamed.
|
||||
pub const LABEL: &str = "label";
|
||||
/// A tag on the rev, one key per tag name after this prefix; `true` while it stands, `false` once removed.
|
||||
pub const TAG_PREFIX: &str = "tag:";
|
||||
}
|
||||
|
||||
/// The folded record. Users and revs are kept sorted so two copies holding the same facts serialize alike.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HistoryMetadata {
|
||||
#[serde(default)]
|
||||
pub users: Vec<UserRecord>,
|
||||
#[serde(default)]
|
||||
pub revs: Vec<RevRecord>,
|
||||
}
|
||||
|
||||
impl HistoryMetadata {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.users.is_empty() && self.revs.is_empty()
|
||||
}
|
||||
|
||||
/// The record folded from facts in file order: each fact lands unless a newer one about the same thing stands.
|
||||
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
|
||||
let mut record = Self::default();
|
||||
for fact in facts {
|
||||
record.absorb(fact);
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
/// Every fact the record holds, users first then revs, for writing it out whole.
|
||||
pub fn facts(&self) -> Vec<MetadataFact> {
|
||||
let users = self.users.iter().flat_map(|record| {
|
||||
record.attributes.iter().map(|(key, fact)| MetadataFact {
|
||||
subject: Subject::User(record.user),
|
||||
key: key.clone(),
|
||||
value: fact.value.clone(),
|
||||
stamp: fact.stamp,
|
||||
})
|
||||
});
|
||||
let revs = self.revs.iter().flat_map(|record| {
|
||||
record.attributes.iter().map(|(key, fact)| MetadataFact {
|
||||
subject: Subject::Rev(record.rev),
|
||||
key: key.clone(),
|
||||
value: fact.value.clone(),
|
||||
stamp: fact.stamp,
|
||||
})
|
||||
});
|
||||
users.chain(revs).collect()
|
||||
}
|
||||
|
||||
pub fn user(&self, user: UserId) -> Option<&UserRecord> {
|
||||
self.users.binary_search_by_key(&user, |record| record.user).ok().map(|index| &self.users[index])
|
||||
}
|
||||
|
||||
pub(crate) fn user_attribute(&self, user: UserId, key: &str) -> Option<&Fact> {
|
||||
self.user(user)?.attributes.get(key)
|
||||
}
|
||||
|
||||
/// The user's display name, if one is on record and not empty.
|
||||
pub fn user_name(&self, user: UserId) -> Option<&str> {
|
||||
self.user_attribute(user, user_attr::NAME)?.value.as_str().filter(|name| !name.is_empty())
|
||||
}
|
||||
|
||||
pub fn rev(&self, rev: Rev) -> Option<&RevRecord> {
|
||||
self.revs.binary_search_by_key(&rev, |record| record.rev).ok().map(|index| &self.revs[index])
|
||||
}
|
||||
|
||||
pub(crate) fn rev_attribute(&self, rev: Rev, key: &str) -> Option<&Fact> {
|
||||
self.rev(rev)?.attributes.get(key)
|
||||
}
|
||||
|
||||
/// The name a person gave the interaction `rev` closes, if any and not empty.
|
||||
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
|
||||
self.rev_attribute(rev, rev_attr::LABEL)?.value.as_str().filter(|label| !label.is_empty())
|
||||
}
|
||||
|
||||
/// The tags standing on `rev`, in name order.
|
||||
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
|
||||
let Some(record) = self.rev(rev) else { return Vec::new() };
|
||||
record
|
||||
.attributes
|
||||
.iter()
|
||||
.filter(|(_, fact)| fact.value == serde_json::Value::Bool(true))
|
||||
.filter_map(|(key, _)| key.strip_prefix(rev_attr::TAG_PREFIX))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// State a fact about a user. A no-op when the same value already stands; otherwise stamped after the fact it
|
||||
/// replaces, so a clock behind a peer's still wins. Returns the fact as stated, for appending and broadcasting.
|
||||
pub fn set_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
|
||||
self.state(Subject::User(user), key, value, stamp)
|
||||
}
|
||||
|
||||
/// State a fact about a rev; see [`set_user_attribute`](Self::set_user_attribute).
|
||||
pub fn set_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
|
||||
self.state(Subject::Rev(rev), key, value, stamp)
|
||||
}
|
||||
|
||||
fn state(&mut self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
|
||||
let attributes = self.attributes_mut(subject);
|
||||
if let Some(existing) = attributes.get(key) {
|
||||
if existing.value == value {
|
||||
return None;
|
||||
}
|
||||
if stamp <= existing.stamp {
|
||||
stamp.ms = existing.stamp.ms + 1;
|
||||
}
|
||||
}
|
||||
attributes.insert(key.to_string(), Fact { value: value.clone(), stamp });
|
||||
Some(MetadataFact {
|
||||
subject,
|
||||
key: key.to_string(),
|
||||
value,
|
||||
stamp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Take on a fact stated elsewhere unless an equal or newer stamp stands for the same thing. Returns whether
|
||||
/// it landed.
|
||||
pub(crate) fn absorb(&mut self, fact: MetadataFact) -> bool {
|
||||
let attributes = self.attributes_mut(fact.subject);
|
||||
if attributes.get(&fact.key).is_some_and(|mine| fact.stamp <= mine.stamp) {
|
||||
return false;
|
||||
}
|
||||
attributes.insert(fact.key, Fact { value: fact.value, stamp: fact.stamp });
|
||||
true
|
||||
}
|
||||
|
||||
/// Take on another copy's record: for every key, the newer stamp wins. Returns the facts that landed, for
|
||||
/// appending to the file.
|
||||
pub fn merge(&mut self, other: &Self) -> Vec<MetadataFact> {
|
||||
other.facts().into_iter().filter(|fact| self.absorb(fact.clone())).collect()
|
||||
}
|
||||
|
||||
fn attributes_mut(&mut self, subject: Subject) -> &mut BTreeMap<String, Fact> {
|
||||
match subject {
|
||||
Subject::User(user) => {
|
||||
let index = match self.users.binary_search_by_key(&user, |record| record.user) {
|
||||
Ok(index) => index,
|
||||
Err(index) => {
|
||||
self.users.insert(index, UserRecord { user, attributes: BTreeMap::new() });
|
||||
index
|
||||
}
|
||||
};
|
||||
&mut self.users[index].attributes
|
||||
}
|
||||
Subject::Rev(rev) => {
|
||||
let index = match self.revs.binary_search_by_key(&rev, |record| record.rev) {
|
||||
Ok(index) => index,
|
||||
Err(index) => {
|
||||
self.revs.insert(index, RevRecord { rev, attributes: BTreeMap::new() });
|
||||
index
|
||||
}
|
||||
};
|
||||
&mut self.revs[index].attributes
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stamp(ms: u64, peer: u64) -> WallStamp {
|
||||
WallStamp { ms, peer: PeerId(peer) }
|
||||
}
|
||||
|
||||
fn rev(n: u128) -> Rev {
|
||||
Rev::new(n).expect("non-zero")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newer_fact_wins_whatever_order_the_copies_meet_in() {
|
||||
let mut a = HistoryMetadata::default();
|
||||
let mut b = HistoryMetadata::default();
|
||||
assert!(a.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(10, 1)).is_some());
|
||||
assert!(b.set_user_attribute(UserId(1), user_attr::NAME, "Ada L.".into(), stamp(20, 2)).is_some());
|
||||
|
||||
let mut ab = a.clone();
|
||||
assert_eq!(ab.merge(&b).len(), 1);
|
||||
let mut ba = b.clone();
|
||||
assert!(ba.merge(&a).is_empty());
|
||||
assert_eq!(ab, ba);
|
||||
assert_eq!(ab.user_name(UserId(1)), Some("Ada L."));
|
||||
assert!(ab.merge(&b).is_empty(), "merging again changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_behind_a_peers_still_gets_its_say() {
|
||||
let mut record = HistoryMetadata::default();
|
||||
record.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(100, 2));
|
||||
let stated = record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(5, 1)).expect("a change");
|
||||
assert_eq!(stated.stamp.ms, 101);
|
||||
assert_eq!(record.user_name(UserId(1)), Some("Countess"));
|
||||
assert!(
|
||||
record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(500, 1)).is_none(),
|
||||
"the same value is no change"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fold_of_the_facts_is_the_record_and_back() {
|
||||
let mut record = HistoryMetadata::default();
|
||||
record.set_user_attribute(UserId(9), user_attr::NAME, "".into(), stamp(1, 1));
|
||||
record.set_user_attribute(UserId(3), user_attr::NAME, "Bea".into(), stamp(1, 1));
|
||||
record.set_rev_attribute(rev(7), rev_attr::LABEL, "Fixed the eye".into(), stamp(2, 1));
|
||||
record.set_rev_attribute(rev(7), "tag:v1", true.into(), stamp(3, 1));
|
||||
record.set_rev_attribute(rev(7), "tag:draft", false.into(), stamp(4, 1));
|
||||
assert_eq!(record.user_name(UserId(9)), None);
|
||||
assert_eq!(record.users.iter().map(|record| record.user).collect::<Vec<_>>(), vec![UserId(3), UserId(9)]);
|
||||
assert_eq!(record.rev_label(rev(7)), Some("Fixed the eye"));
|
||||
assert_eq!(record.rev_tags(rev(7)), vec!["v1"]);
|
||||
|
||||
let facts = record.facts();
|
||||
assert_eq!(facts.len(), 5);
|
||||
assert_eq!(HistoryMetadata::fold(facts), record);
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,14 @@ pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
pub mod history;
|
||||
mod history_metadata;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
pub mod touched;
|
||||
pub mod value;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -24,12 +26,14 @@ pub use attributes::*;
|
||||
pub use crdt::*;
|
||||
pub use document::*;
|
||||
pub use history::History;
|
||||
pub use history_metadata::{Fact, HistoryMetadata, MetadataFact, RevRecord, Subject, UserRecord, WallStamp, rev_attr, user_attr};
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
pub use touched::Touched;
|
||||
pub use value::{Value, ValueError, from_value, to_value};
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -40,11 +44,13 @@ pub use from_runtime::{
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use to_runtime::Declarations;
|
||||
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use crate::{Attributes, Implementation, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -66,6 +66,31 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry as `to_runtime` renders it: a removed network that a live node still runs counts as present, so a
|
||||
/// diff against the runtime does not take it for an addition.
|
||||
pub(crate) fn as_rendered(&self) -> Registry {
|
||||
let mut rendered = self.clone();
|
||||
for node in self.node_instances.values() {
|
||||
if let Implementation::Network(id) = node.implementation
|
||||
&& let Some(mark) = rendered.removed_networks.remove(&id)
|
||||
{
|
||||
rendered.networks.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Whether both registries removed the same entities at the same times. The marks decide how future
|
||||
/// ops land, so registries agreeing on values but not on marks will diverge.
|
||||
pub fn removal_marks_equal(&self, other: &Self) -> bool {
|
||||
fn same<K: std::hash::Hash + Eq, T>(a: &HashMap<K, Tombstone<T>>, b: &HashMap<K, Tombstone<T>>) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.all(|(id, mark)| b.get(id).is_some_and(|other| other.timestamp == mark.timestamp && other.placeholder == mark.placeholder))
|
||||
}
|
||||
same(&self.removed_nodes, &other.removed_nodes) && same(&self.removed_networks, &other.removed_networks) && same(&self.removed_resources, &other.removed_resources)
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{
|
||||
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value,
|
||||
to_value,
|
||||
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId,
|
||||
Value, to_value,
|
||||
};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -19,6 +19,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 {
|
||||
@@ -40,6 +43,7 @@ impl Session {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,11 +55,22 @@ impl Session {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// Change the person behind this peer. The next staged batch registers the peer again, and the newer
|
||||
/// registration wins everywhere.
|
||||
pub fn set_user(&mut self, user: UserId) {
|
||||
self.document.user = user;
|
||||
}
|
||||
|
||||
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.
|
||||
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
|
||||
}
|
||||
@@ -82,11 +97,28 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
let rendered;
|
||||
let base = match &self.runtime_base {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
rendered = self.document.working_registry.as_rendered();
|
||||
&rendered
|
||||
}
|
||||
};
|
||||
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. Lenient, as the
|
||||
// diff is against what the runtime held: a peer's concurrent write may have reshaped what it names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
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.as_rendered());
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -147,11 +179,11 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
|
||||
}
|
||||
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
/// [`stage_ops`](Self::stage_ops), each op carrying its hot op's attributes. A batch is staged whole or not at all.
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -177,7 +209,7 @@ impl Session {
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -191,9 +223,22 @@ impl Session {
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
self.advance_runtime_base(&staged);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// A local batch is an edit the runtime already shows, so the base a whole-document stage diffs against moves
|
||||
/// with it; otherwise that stage would restate the batch, which fails on what the batch added.
|
||||
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
|
||||
let Some(base) = self.runtime_base.take() else { return };
|
||||
let working = std::mem::replace(&mut self.document.working_registry, base);
|
||||
for hot_op in staged {
|
||||
// Lenient, like replaying an op already seen: the base held what the runtime held when the batch was made.
|
||||
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
|
||||
}
|
||||
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
|
||||
}
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
@@ -206,7 +251,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops paired with their authored stamp (`None` to mint one), which retirement keeps
|
||||
/// so LWW resolves as it did live.
|
||||
/// so LWW resolves as it did live; 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::Retired;
|
||||
let ops = ops.into_iter();
|
||||
@@ -267,6 +312,7 @@ impl Session {
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,14 +334,231 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Drop hot ops another peer has retired, without retiring them locally. The working registry is rebuilt
|
||||
/// without them, so until their deltas arrive it shows the snapshot plus what is still hot.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.mark_retired(retired.iter().copied())
|
||||
}
|
||||
|
||||
/// Take back this peer's latest interaction (its ops since the previous marker) while it is still hot, so an
|
||||
/// accidental gesture and its undo leave no step in history. `None` when nothing is hot or the interaction
|
||||
/// already retired somewhere this peer knows of, which makes it an undo of a retired step.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Retraction>, CrdtError> {
|
||||
let peer = self.document.peer;
|
||||
let mut own: Vec<&HotOp> = self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp.peer == peer).collect();
|
||||
own.sort_by_key(|hot_op| hot_op.sequence);
|
||||
// The latest interaction: everything after the previous marker, through a trailing marker if any.
|
||||
let closed_before = match own.last() {
|
||||
Some(last) if last.ends_interaction() => own.len() - 1,
|
||||
Some(_) => own.len(),
|
||||
None => return Ok(None),
|
||||
};
|
||||
let start = own[..closed_before].iter().rposition(|hot_op| hot_op.ends_interaction()).map_or(0, |position| position + 1);
|
||||
if own[start..].iter().all(|hot_op| matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let ids: Vec<HotOpId> = own[start..].iter().map(|hot_op| hot_op.id()).collect();
|
||||
if ids.iter().any(|&id| self.document.retired.covers(id)) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
Ok(Some(Retraction { ids, touched, ops }))
|
||||
}
|
||||
|
||||
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
|
||||
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.retract_hot_ops(ids).0
|
||||
}
|
||||
|
||||
/// The last delta of this person's latest retired interaction on the line, if any: what an undo of a
|
||||
/// retired step in a session names. Any peer of the same user counts; see [`is_mine`](Self::is_mine).
|
||||
pub fn latest_own_interaction(&self) -> Option<Rev> {
|
||||
let mut current = self.document.head?;
|
||||
loop {
|
||||
let delta = self.document.history.get(current)?;
|
||||
if delta.is_interaction_end() && self.is_mine(delta.author) {
|
||||
return Some(current);
|
||||
}
|
||||
current = delta.parent?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo a retired interaction in a session by dropping it out of the shared line: the head moves to its parent
|
||||
/// and the later steps are minted again there with the same author, stamp and kind, so every follower holds
|
||||
/// identical revs; the originals stay as an abandoned branch. Returns the move to broadcast and what the
|
||||
/// dropped ops named. Only the retirer does this; a guest asks it to.
|
||||
pub fn drop_interaction(&mut self, undone: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
let base = self.interaction_start_parent(undone, false).ok_or(CrdtError::NotUndoable(undone))?;
|
||||
|
||||
// The line from the head down to the interaction's parent, newest first.
|
||||
let mut walked = Vec::new();
|
||||
let mut current = from;
|
||||
while current != Some(base) {
|
||||
let rev = current.ok_or(CrdtError::NotFoundInHistory(undone))?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
|
||||
return Err(CrdtError::NotUndoable(undone));
|
||||
}
|
||||
current = delta.parent;
|
||||
walked.push(delta);
|
||||
}
|
||||
let position = walked.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
|
||||
|
||||
// Fold from history at the new head.
|
||||
self.document.head = Some(base);
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
|
||||
let mut touched = Touched::default();
|
||||
walked[position..].iter().for_each(|delta| touched.record(&delta.kind));
|
||||
let mut copies = Vec::new();
|
||||
for original in walked[..position].iter().rev() {
|
||||
let revs = self.commit_ops_authored_at([(original.kind.clone(), Some(original.timestamp))], true)?;
|
||||
// A copy keeps what was said about the original: its interaction end, and when it was retired.
|
||||
if let Some(&rev) = revs.last() {
|
||||
self.carry_attributes(original, rev);
|
||||
}
|
||||
copies.extend(revs.iter().filter_map(|&rev| self.document.history.get(rev).cloned()));
|
||||
}
|
||||
// Two branches now, so restore the canonical file order every peer computes alike.
|
||||
self.document.history.canonical_sort();
|
||||
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
head: self.document.head,
|
||||
copies,
|
||||
},
|
||||
touched,
|
||||
))
|
||||
}
|
||||
|
||||
/// Move the shared head back to an ancestor in a session. The line down to `target` stays as an abandoned
|
||||
/// branch, nothing is minted, and the snapshot refolds at the target as in [`drop_interaction`](Self::drop_interaction).
|
||||
/// Returns the move to broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to.
|
||||
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
if from == Some(target) {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let mut touched = Touched::default();
|
||||
let mut current = from;
|
||||
while current != Some(target) {
|
||||
let rev = current.ok_or(CrdtError::NotFoundInHistory(target))?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?;
|
||||
touched.record(&delta.kind);
|
||||
current = delta.parent;
|
||||
}
|
||||
self.document.head = Some(target);
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
head: Some(target),
|
||||
copies: Vec::new(),
|
||||
},
|
||||
touched,
|
||||
))
|
||||
}
|
||||
|
||||
/// Follow another peer's cursor move: refold the snapshot to where the copies start, take the copies on,
|
||||
/// and put the head where the mover put it. Returns what the walked-over ops named. The move only
|
||||
/// applies from the head it started at; anywhere else this peer has diverged and needs a resync.
|
||||
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
|
||||
if self.document.head != moved.from {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
expected: moved.from,
|
||||
found: self.document.head,
|
||||
});
|
||||
}
|
||||
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
|
||||
|
||||
let mut touched = Touched::default();
|
||||
let mut current = self.document.head;
|
||||
while current != base {
|
||||
let rev = current.ok_or(CrdtError::NothingToUndo)?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?;
|
||||
touched.record(&delta.kind);
|
||||
current = delta.parent;
|
||||
}
|
||||
// Fold from history at the new base, as `drop_interaction` does.
|
||||
self.document.head = base;
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
|
||||
for copy in &moved.copies {
|
||||
if let Some(parent) = copy.parent
|
||||
&& !self.document.history.contains(parent)
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
self.document.apply_op_with(RegistryTarget::Retired, copy.kind.clone(), copy.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.history.push(copy.clone());
|
||||
self.document.head = Some(copy.id);
|
||||
}
|
||||
if self.document.head != moved.head {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
expected: moved.head,
|
||||
found: self.document.head,
|
||||
});
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// Redo a dropped interaction in a session: mint its ops again on top of the line, as one interaction.
|
||||
/// Its writes carry their original stamps, so a field someone wrote since keeps the newer value.
|
||||
/// Returns the new revs, for an ordinary retirement-style broadcast.
|
||||
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
|
||||
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
|
||||
let mut originals = Vec::new();
|
||||
let mut current = Some(dropped);
|
||||
while current != Some(base) {
|
||||
let rev = current.ok_or(CrdtError::NothingToRedo)?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
current = delta.parent;
|
||||
originals.push(delta);
|
||||
}
|
||||
originals.reverse();
|
||||
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
|
||||
// The copies keep the originals' attributes and retirement times.
|
||||
if revs.len() == originals.len() {
|
||||
for (original, &rev) in originals.iter().zip(&revs) {
|
||||
self.carry_attributes(original, rev);
|
||||
}
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
|
||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
||||
&self.document.retired
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
|
||||
self.document.absorb_retired_marks(remote);
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
let touched = self.document.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.runtime_base = None;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -304,38 +567,6 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
@@ -350,6 +581,173 @@ impl Session {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// Take a retirer's deltas on and put the head where the retirer's is, minting nothing: a guest follows the
|
||||
/// host's line rather than merging with it. A batch not extending this head (the host moved the line) refolds
|
||||
/// the snapshot, leaving the old tip as an abandoned branch. `head` defaults to the batch's last delta.
|
||||
pub fn follow(&mut self, incoming: Vec<Delta>, head: Option<Rev>) -> Result<MergeOutcome, CrdtError> {
|
||||
let before = self.document.head;
|
||||
let length_before = self.document.history.len();
|
||||
let named = head.is_some();
|
||||
let head = head.or_else(|| incoming.last().map(|delta| delta.id)).or(before);
|
||||
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = delta.all_parents().find(|&parent| !self.document.history.contains(parent)) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
// A batch bringing nothing new whose end this head already descends from is a late copy of a line followed
|
||||
// past; only a named head or a head move takes the line back. One ending ahead, like a restored step, still moves it.
|
||||
let stale = |head: Rev| !named && before.is_some_and(|before| self.document.history.is_ancestor(head, before));
|
||||
if self.document.history.len() == length_before && (head == before || head.is_some_and(stale)) {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
// The new head extends this one when walking its parents back over the batch reaches this head.
|
||||
let mut chain = Vec::new();
|
||||
let mut current = head;
|
||||
let extends = loop {
|
||||
if current == before {
|
||||
break true;
|
||||
}
|
||||
let Some(rev) = current else { break false };
|
||||
let Some(delta) = self.document.history.get(rev) else { break false };
|
||||
if self.document.history.position(rev).is_some_and(|position| position < length_before) {
|
||||
break false;
|
||||
}
|
||||
// A merge joins a line this chain does not walk, possibly a branch this peer abandoned, so the
|
||||
// snapshot has to be folded from the new head's whole ancestry.
|
||||
if delta.all_parents().count() > 1 {
|
||||
break false;
|
||||
}
|
||||
chain.push(delta.clone());
|
||||
current = delta.parent;
|
||||
};
|
||||
|
||||
if extends {
|
||||
for delta in chain.iter().rev() {
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
}
|
||||
self.document.head = head;
|
||||
} else {
|
||||
self.document.head = head;
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok(head.map_or(MergeOutcome::NoOp, MergeOutcome::FastForward))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let head_before = self.document.head;
|
||||
|
||||
// Working is snapshot plus hot tail, so each delta lands on both (cloning would promote hot ops). Every
|
||||
// field, presence included, is last-writer-wins, so the batch's order decides nothing.
|
||||
let mut absorbed_ids = HashSet::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
absorbed_ids.insert(delta.id);
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
if absorbed_ids.is_empty() {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
// A batch chaining off the last delta, as a retirement's does, is already in canonical order. The
|
||||
// order matters to the history file and `Rev` determinism only, not to the registries.
|
||||
let extends = self.document.history.extends_canonically(length_before);
|
||||
if !extends {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
|
||||
let history = &self.document.history;
|
||||
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
|
||||
let parents: Vec<Rev> = if extends && self.document.head == last_before {
|
||||
// The chain hangs off `head`, so `head` is its ancestor and the chain's end is the one tip.
|
||||
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
|
||||
} else {
|
||||
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
|
||||
candidates.extend(self.document.head);
|
||||
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
|
||||
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
|
||||
};
|
||||
|
||||
let outcome = match parents.as_slice() {
|
||||
[tip] => MergeOutcome::FastForward(*tip),
|
||||
_ => {
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(parents, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
|
||||
self.document.history.push(merge);
|
||||
MergeOutcome::Merged(merge_rev)
|
||||
}
|
||||
};
|
||||
self.document.head = outcome.head();
|
||||
// The line moved, so what was undone is either on it now or left behind. A peer holds what came from it, so the
|
||||
// line up to here is published and a silent undo leaves it be.
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
|
||||
// A merge may join a branch this peer abandoned, whose effects applying the batch did not bring into
|
||||
// the snapshot, and so may a batch sorted in ahead of the tail. Either way, refold from the new head.
|
||||
let mut refold = !extends || matches!(outcome, MergeOutcome::Merged(_));
|
||||
if !refold && let MergeOutcome::FastForward(tip) = outcome {
|
||||
refold = !self.fold_in_skipped(tip, head_before, &absorbed_ids)?;
|
||||
}
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Fold in the deltas between `from` and the new `tip` that the batch did not bring: steps undone here that the
|
||||
/// incoming line builds on. Walks first parents, so O(the batch plus those steps). `false` when the walk meets a
|
||||
/// merge or misses `from`, for the caller to refold instead.
|
||||
fn fold_in_skipped(&mut self, tip: Rev, from: Option<Rev>, absorbed: &HashSet<Rev>) -> Result<bool, CrdtError> {
|
||||
let mut skipped = Vec::new();
|
||||
let mut current = Some(tip);
|
||||
while current != from {
|
||||
let Some(delta) = current.and_then(|rev| self.document.history.get(rev)) else { return Ok(false) };
|
||||
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
|
||||
return Ok(false);
|
||||
}
|
||||
if !absorbed.contains(&delta.id) {
|
||||
skipped.push(delta.clone());
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
for delta in skipped.into_iter().rev() {
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.apply_op_idempotent(delta.kind, delta.timestamp)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
|
||||
/// re-registration possibly before the marker; empty when nothing is open.
|
||||
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
|
||||
@@ -366,7 +764,7 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
@@ -404,6 +802,16 @@ impl Session {
|
||||
closed
|
||||
}
|
||||
|
||||
/// Retire one closed interaction coarsened, marking its last delta as the interaction's end. Every op is
|
||||
/// retired, the ones coarsening drops included. Returns the new revs.
|
||||
pub fn retire_interaction(&mut self, interaction: &ClosedInteraction) -> Result<Vec<Rev>, CrdtError> {
|
||||
let revs = self.retire_hot_ops_with(&interaction.ops, true)?;
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
@@ -411,14 +819,20 @@ impl Session {
|
||||
|
||||
/// Promote the given hot ops into retired deltas in hot-log order, each keeping its authored stamp.
|
||||
///
|
||||
/// One retired delta per hot op, except a `Meta` op, which commits nothing.
|
||||
/// One retired delta per hot op, except a `Meta` op, which commits nothing. [`retire_interaction`](Self::retire_interaction)
|
||||
/// coarsens a closed interaction instead.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
self.retire_hot_ops_with(ids, false)
|
||||
}
|
||||
|
||||
fn retire_hot_ops_with(&mut self, ids: &[HotOpId], coarsened: bool) -> 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.retired.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
let drained = if coarsened { coarsen(drained) } else { drained };
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta))
|
||||
@@ -426,7 +840,9 @@ impl Session {
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author.
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author and whether or not its
|
||||
/// interaction is closed. For callers that own the whole log, tests mostly; a session retires by
|
||||
/// [`retire_interaction`](Self::retire_interaction).
|
||||
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)
|
||||
@@ -438,6 +854,25 @@ impl Session {
|
||||
self.document.history.mark_interaction_end(rev, timestamp);
|
||||
}
|
||||
|
||||
/// Record when these retired deltas entered history, in wall-clock milliseconds as the retirer saw them.
|
||||
/// Outside their revs, and never used for ordering.
|
||||
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
|
||||
for &rev in revs {
|
||||
self.document.history.set_retired_at(rev, wall_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy every attribute of the delta it stands for, each with the stamp it had, and when the
|
||||
/// original was retired.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
self.document.history.set_retired_at(copy, wall_ms);
|
||||
}
|
||||
for (key, value) in original.attributes.live() {
|
||||
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -483,6 +918,8 @@ impl Session {
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
// 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) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
@@ -503,6 +940,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);
|
||||
@@ -545,6 +983,33 @@ 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.
|
||||
pub fn known_revs(&self) -> Vec<Rev> {
|
||||
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Retired deltas on `head`'s ancestry that are not reachable from `known`, in replay order. An abandoned
|
||||
/// branch stays local: it is this peer's to redo, and a peer that merged it would bring the undone step
|
||||
/// back. Merging thus joins heads, never every tip.
|
||||
///
|
||||
/// What a peer receives it holds, so the head counts as published from then on and a silent undo leaves it be.
|
||||
pub fn deltas_unknown_to(&mut self, known: impl IntoIterator<Item = Rev>) -> Vec<Delta> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let deltas: Vec<Delta> = self
|
||||
.document
|
||||
.history
|
||||
.deltas_unknown_to(known)
|
||||
.into_iter()
|
||||
.filter(|delta| reachable.contains(&delta.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
if let Some(head) = self.document.head.filter(|_| !deltas.is_empty()) {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -682,6 +1147,23 @@ 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)]
|
||||
@@ -696,6 +1178,7 @@ pub struct HotOp {
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Whether the op closes its author's interaction.
|
||||
pub fn ends_interaction(&self) -> bool {
|
||||
self.attributes.get_or(crate::attr::delta::INTERACTION_END, false)
|
||||
}
|
||||
@@ -743,8 +1226,8 @@ pub struct HotOpId {
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops are retired: each author's gap-free prefix, plus runs past it while ops are in flight. Persisted, so
|
||||
/// a late copy of a retired op is dropped.
|
||||
/// Which hot ops are done with, retired or taken back by their author: each author's gap-free prefix, plus runs past it
|
||||
/// while ops are in flight. Replicated and persisted, so a late copy of a retired op is dropped wherever it lands.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RetiredMarks {
|
||||
pub retired_up_to: HashMap<PeerId, HotSequence>,
|
||||
@@ -765,7 +1248,7 @@ fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
}
|
||||
|
||||
impl RetiredMarks {
|
||||
/// Whether history already holds this hot op.
|
||||
/// Whether this hot op is done with.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
|| self
|
||||
@@ -834,6 +1317,10 @@ pub enum CrdtError {
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
NothingToRedo,
|
||||
#[error("Interaction {0} cannot be dropped: it is the base or spans a merge")]
|
||||
NotUndoable(Rev),
|
||||
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
|
||||
CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
|
||||
#[error("Node {0} already exists")]
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
@@ -841,3 +1328,106 @@ pub enum CrdtError {
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
|
||||
/// Which field of the registry a write lands on, for coarsening.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum FieldKey {
|
||||
NodeInput(NodeId, u32),
|
||||
NodeInputAttribute(NodeId, u32, String),
|
||||
NodeAttribute(NodeId, String),
|
||||
NodeImplementation(NodeId),
|
||||
NodeInputs(NodeId),
|
||||
NetworkExport(NetworkId, u32),
|
||||
NetworkAttribute(NetworkId, String),
|
||||
ResourceHash(ResourceId),
|
||||
Source(ResourceId, crate::SourceKey),
|
||||
DocumentAttribute(String),
|
||||
}
|
||||
|
||||
/// The field a write lands on, `None` for an op that is not a plain field write.
|
||||
fn field_of(op: &RegistryDelta) -> Option<FieldKey> {
|
||||
Some(match op {
|
||||
RegistryDelta::ChangeNodeInput { id, index, .. } => FieldKey::NodeInput(*id, *index),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => FieldKey::NodeInputAttribute(*id, *index, delta.key.clone()),
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => FieldKey::NodeAttribute(*id, delta.key.clone()),
|
||||
RegistryDelta::SetNodeImplementation { id, .. } => FieldKey::NodeImplementation(*id),
|
||||
RegistryDelta::SetNodeInputs { id, .. } => FieldKey::NodeInputs(*id),
|
||||
RegistryDelta::SetNetworkExport { id, index, .. } => FieldKey::NetworkExport(*id, *index),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => FieldKey::NetworkAttribute(*id, delta.key.clone()),
|
||||
RegistryDelta::SetResourceHash { id, .. } => FieldKey::ResourceHash(*id),
|
||||
RegistryDelta::AddSource { id, key, .. } | RegistryDelta::RemoveSource { id, key } => FieldKey::Source(*id, *key),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => FieldKey::DocumentAttribute(delta.key.clone()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What a write refers to beyond its own field: a node an input is wired to, or a network an
|
||||
/// implementation points at. A reference is evidence the target exists at the write's stamp, so a write
|
||||
/// that carries one only drops when the write superseding it carries the same.
|
||||
fn references_of(op: &RegistryDelta) -> Vec<u64> {
|
||||
let of_input = |input: &crate::NodeInput| match input {
|
||||
crate::NodeInput::Node { id, .. } => Some(id.0),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => of_input(new_input).into_iter().collect(),
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => inputs.iter().filter_map(|slot| of_input(&slot.input)).collect(),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => export.as_ref().and_then(of_input).into_iter().collect(),
|
||||
RegistryDelta::SetNodeImplementation {
|
||||
implementation: Implementation::Network(network),
|
||||
..
|
||||
} => vec![network.0],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarsens one interaction's ops: a field write that a later write in it supersedes has no effect on the fold
|
||||
/// and is dropped, unless it refers to something the later write does not. A whole-list input write
|
||||
/// supersedes every earlier input write on its node. Structural ops stay.
|
||||
fn coarsen(mut ops: Vec<HotOp>) -> Vec<HotOp> {
|
||||
// Newest by stamp, which is the author's order. The hot log holds arrival order, and a re-announcement
|
||||
// after a lapsed link delivers later ops first, so log order would retire a value the registry never showed.
|
||||
ops.sort_by_key(|hot_op| hot_op.timestamp);
|
||||
let mut keep = vec![true; ops.len()];
|
||||
let mut latest: HashMap<FieldKey, usize> = HashMap::new();
|
||||
for (index, hot_op) in ops.iter().enumerate() {
|
||||
let Some(field) = field_of(&hot_op.op) else { continue };
|
||||
let references = references_of(&hot_op.op);
|
||||
let supersedes = |earlier: &HotOp| references_of(&earlier.op).iter().all(|reference| references.contains(reference));
|
||||
|
||||
if let FieldKey::NodeInputs(id) = field {
|
||||
latest.retain(|key, &mut earlier| {
|
||||
let same_node = matches!(key, FieldKey::NodeInput(node, _) | FieldKey::NodeInputAttribute(node, _, _) | FieldKey::NodeInputs(node) if *node == id);
|
||||
let superseded = same_node && supersedes(&ops[earlier]);
|
||||
keep[earlier] &= !superseded;
|
||||
!superseded
|
||||
});
|
||||
} else if let Some(&earlier) = latest.get(&field)
|
||||
&& supersedes(&ops[earlier])
|
||||
{
|
||||
keep[earlier] = false;
|
||||
}
|
||||
latest.insert(field, index);
|
||||
}
|
||||
ops.into_iter().zip(keep).filter_map(|(hot_op, keep)| keep.then_some(hot_op)).collect()
|
||||
}
|
||||
|
||||
/// What [`Session::retract_interaction`] took back.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Retraction {
|
||||
/// The ids to send, so every peer drops the same ops.
|
||||
pub ids: Vec<HotOpId>,
|
||||
/// What the ops named, for a mirror to bring back into line.
|
||||
pub touched: Touched,
|
||||
/// The ops themselves, marker aside, for a redo to stage afresh.
|
||||
pub ops: Vec<RegistryDelta>,
|
||||
}
|
||||
|
||||
/// A shared cursor move, as [`Session::drop_interaction`] produces it and [`Session::apply_head_move`]
|
||||
/// follows it: the head it started from, the head it ends at, and the steps minted again in between.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HeadMove {
|
||||
pub from: Option<Rev>,
|
||||
pub head: Option<Rev>,
|
||||
pub copies: Vec<Delta>,
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, ResourceId, Session, UserId, Value};
|
||||
|
||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -9,13 +9,19 @@ fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
pub(super) fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `hot_op` flagged as the end of its author's interaction, as a peer's `end_interaction` stages it.
|
||||
fn closing(mut hot_op: crate::HotOp) -> crate::HotOp {
|
||||
hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN);
|
||||
hot_op
|
||||
}
|
||||
|
||||
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
@@ -43,6 +49,234 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// Only closed interactions retire: an author's ops past its last marker stay hot however old, while a
|
||||
/// later interaction from someone else retires around them.
|
||||
#[test]
|
||||
fn only_closed_interactions_retire_and_an_open_one_stays_hot() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open");
|
||||
|
||||
// The guest opens an interaction and leaves it open, stamped earlier than everything the host does.
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
|
||||
|
||||
host.stage_ops([set_attribute("host", 1)]).expect("host op");
|
||||
let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open");
|
||||
assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction());
|
||||
assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}");
|
||||
assert_eq!(closed[0].author, PeerId(1));
|
||||
assert!(closed[0].contiguous);
|
||||
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
|
||||
|
||||
let revs = host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert_eq!(revs.len(), 2, "the marker commits no delta");
|
||||
assert!(
|
||||
host.history().any(|delta| delta.id == revs[1] && delta.is_interaction_end()),
|
||||
"the interaction retires as one undo step"
|
||||
);
|
||||
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
|
||||
assert!(host.hot_log().iter().all(|hot_op| hot_op.timestamp.peer == PeerId(2)));
|
||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
||||
|
||||
// The guest closes: its interaction retires after the host's although it is stamped before it.
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].author, PeerId(2));
|
||||
host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// An interaction with a gap in its author's run is listed as not contiguous, so the retirer can wait for
|
||||
/// the re-announcement, and closes normally once the gap fills.
|
||||
#[test]
|
||||
fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight");
|
||||
host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 2);
|
||||
assert!(!closed[0].contiguous);
|
||||
assert!(!closed[1].contiguous, "the gap is behind the later interaction too");
|
||||
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
|
||||
let closed = host.closed_interactions();
|
||||
assert!(closed.iter().all(|interaction| interaction.contiguous));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
/// Retracting a hot interaction removes its ops for good and re-derives what they touched from the snapshot
|
||||
/// and the other hot ops, so a concurrent write to the same entity survives. The ops never retire, and a late copy is dropped.
|
||||
#[test]
|
||||
fn a_retracted_interaction_leaves_no_trace_and_keeps_what_others_wrote() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(3)).expect("base");
|
||||
host.document.working_registry = host.document.retired_snapshot.clone();
|
||||
|
||||
// A guest's write to the network and the host's own gesture on the same network, interleaved.
|
||||
let guest_write = crate::HotOp {
|
||||
op: RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(3),
|
||||
delta: AttributeDelta {
|
||||
key: "guest".into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
},
|
||||
timestamp: crate::TimeStamp { counter: 40, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.stage_ops([RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(3),
|
||||
delta: AttributeDelta {
|
||||
key: "host".into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
}])
|
||||
.expect("host op");
|
||||
host.replay_hot_op(guest_write.clone()).expect("guest op");
|
||||
host.stage_ops([add_network(9)]).expect("host op");
|
||||
let own: Vec<crate::HotOpId> = host.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(1)).map(crate::HotOp::id).collect();
|
||||
|
||||
let crate::Retraction { ids, touched, ops } = host.retract_interaction().expect("retract").expect("the host's interaction is hot");
|
||||
assert_eq!(ops.len(), 3, "RegisterPeer and the two writes come back for a redo, the marker does not");
|
||||
assert_eq!(ids, own, "the whole open interaction is taken back");
|
||||
assert!(touched.networks.contains(&NetworkId(3)) && touched.networks.contains(&NetworkId(9)));
|
||||
assert_eq!(host.hot_log().len(), 1, "only the guest's op stays");
|
||||
assert!(!host.registry().networks.contains_key(&NetworkId(9)));
|
||||
let network = &host.registry().networks[&NetworkId(3)];
|
||||
assert!(!network.attributes.contains_key("host"), "the host's write is gone");
|
||||
assert!(network.attributes.contains_key("guest"), "the guest's concurrent write survives");
|
||||
assert!(host.retract_interaction().expect("nothing left").is_none());
|
||||
|
||||
// A late copy of a retracted op is dropped, and nothing of it ever retires.
|
||||
let late = crate::HotOp {
|
||||
op: add_network(9),
|
||||
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
|
||||
sequence: own[1].sequence,
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(late.clone()).expect("dropped, not an error");
|
||||
assert_eq!(host.hot_log().len(), 1);
|
||||
assert!(host.closed_interactions().is_empty());
|
||||
|
||||
// Another peer learns of the retraction from the marks alone.
|
||||
let mut guest = Session::with_peer(PeerId(2));
|
||||
guest.commit_op_for_test(add_network(3)).expect("base");
|
||||
guest.document.working_registry = guest.document.retired_snapshot.clone();
|
||||
guest.replay_hot_op(late).expect("the host's op reached the guest");
|
||||
assert!(guest.registry().networks.contains_key(&NetworkId(9)));
|
||||
let touched = guest.absorb_retired_marks(host.retired_marks());
|
||||
assert!(touched.networks.contains(&NetworkId(9)));
|
||||
assert!(!guest.registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(guest.hot_log().is_empty());
|
||||
}
|
||||
|
||||
/// An author's ops can reach the retirer out of order through a re-announcement after a lapsed link.
|
||||
/// Coarsening keeps the newest write by stamp, not log position, so the retired delta matches every working registry.
|
||||
#[test]
|
||||
fn an_interaction_that_arrived_out_of_order_retires_to_its_newest_write() {
|
||||
let mut author = Session::with_peer(PeerId(2));
|
||||
author.stage_ops(vec![set_attribute("name", 1), set_attribute("name", 2)]).expect("stage");
|
||||
author.end_interaction().expect("close");
|
||||
let ops = author.hot_log().to_vec();
|
||||
|
||||
let mut in_order = Session::with_peer(PeerId(1));
|
||||
let mut reversed = Session::with_peer(PeerId(1));
|
||||
for hot_op in &ops {
|
||||
in_order.replay_hot_op(hot_op.clone()).expect("replay");
|
||||
}
|
||||
for hot_op in ops.iter().rev() {
|
||||
reversed.replay_hot_op(hot_op.clone()).expect("replay");
|
||||
}
|
||||
for host in [&mut in_order, &mut reversed] {
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert!(host.registry().value_equal(host.retired_registry()), "the retired value is the one the working registry showed");
|
||||
}
|
||||
assert_eq!(reversed.retired_registry(), in_order.retired_registry(), "arrival order decides nothing");
|
||||
}
|
||||
|
||||
/// An interaction retires coarsened: of the writes to one field only the newest becomes a delta, a
|
||||
/// whole-list input write supersedes the slot writes before it, a write wiring an input to a node stays
|
||||
/// while what supersedes it wires elsewhere, and the fold is the one every op would have produced.
|
||||
#[test]
|
||||
fn an_interaction_retires_to_one_delta_per_field() {
|
||||
let attribute = |value: u32| set_attribute("name", value);
|
||||
let wire = |target: u64| RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: crate::NodeInput::Node { id: NodeId(target), index: 0 },
|
||||
};
|
||||
let value = |value: u32| RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 1,
|
||||
new_input: crate::NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(value)),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(3)).expect("network");
|
||||
host.document.working_registry = host.document.retired_snapshot.clone();
|
||||
let node = |id: u64| RegistryDelta::AddNode {
|
||||
id: NodeId(id),
|
||||
node: crate::Node::new(NetworkId(3), crate::Implementation::ProtoNode(ResourceId::from(7)), 2),
|
||||
};
|
||||
let ops = vec![node(1), node(2), node(4), attribute(1), value(1), attribute(2), wire(2), value(2), wire(4), attribute(3), value(3)];
|
||||
let mut raw = host.clone();
|
||||
raw.stage_ops(ops.clone()).expect("stage");
|
||||
host.stage_ops(ops).expect("stage");
|
||||
host.end_interaction().expect("close");
|
||||
raw.end_interaction().expect("close");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
let coarsened = host.retire_interaction(&closed[0]).expect("retire");
|
||||
let raw_ids: Vec<crate::HotOpId> = raw.hot_log().iter().map(crate::HotOp::id).collect();
|
||||
let uncoarsened = raw.retire_hot_ops(&raw_ids).expect("retire raw");
|
||||
|
||||
assert_eq!(uncoarsened.len(), 12, "RegisterPeer, three additions and eight writes");
|
||||
assert_eq!(
|
||||
coarsened.len(),
|
||||
8,
|
||||
"RegisterPeer, three additions, the newest attribute, the newest value, and both wires: {coarsened:?}"
|
||||
);
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.retired_registry().value_equal(raw.retired_registry()), "the fold is unchanged");
|
||||
assert!(host.registry().value_equal(host.retired_registry()), "the working registry, built from every op, agrees");
|
||||
assert_eq!(host.retired_registry(), raw.retired_registry(), "stamps included: the survivor keeps its own");
|
||||
let kinds: Vec<&RegistryDelta> = host.history().map(|delta| &delta.kind).collect();
|
||||
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeDocumentAttribute { .. })).count() == 1);
|
||||
assert!(
|
||||
kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 0, .. })).count() == 2,
|
||||
"the wire to node 2 stays as evidence node 2 exists"
|
||||
);
|
||||
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 1, .. })).count() == 1);
|
||||
assert!(host.history().last().is_some_and(|delta| delta.is_interaction_end()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_peer_registration_wins_in_any_order() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
@@ -78,6 +312,26 @@ fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
assert!(session.hot_log().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retraction_settles_its_sequences_so_later_interactions_stay_contiguous() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.stage_ops([set_attribute("a", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
let up_to = session.hot_log().last().unwrap().timestamp;
|
||||
session.retire(up_to).unwrap();
|
||||
session.stage_ops([set_attribute("b", 1)]).unwrap();
|
||||
session.retract_interaction().unwrap();
|
||||
|
||||
session.stage_ops([set_attribute("c", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
let closed = session.closed_interactions();
|
||||
assert!(closed[0].contiguous, "the retracted sequences are not a gap");
|
||||
session.retire_interaction(&closed[0]).unwrap();
|
||||
let marks = session.retired_marks();
|
||||
assert!(marks.retired_runs.is_empty(), "retired and retracted together leave one prefix");
|
||||
assert_eq!(marks.retired_up_to[&PeerId(1)], session.last_hot_sequence());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
let op = crate::HotOp {
|
||||
@@ -180,68 +434,7 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
assert!(next.timestamp > own.timestamp, "a later stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closed_interactions_are_listed_and_the_marker_commits_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open");
|
||||
|
||||
// The guest's open interaction is stamped before everything the host does.
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
|
||||
|
||||
host.stage_ops([set_attribute("host", 1)]).expect("host op");
|
||||
let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open");
|
||||
assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction());
|
||||
assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}");
|
||||
assert_eq!(closed[0].author, PeerId(1));
|
||||
assert!(closed[0].contiguous);
|
||||
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
|
||||
|
||||
let revs = host.retire_hot_ops(&closed[0].ops).expect("retire");
|
||||
assert_eq!(revs.len(), 2, "the marker commits no delta");
|
||||
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
|
||||
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].author, PeerId(2));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight");
|
||||
host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 2);
|
||||
assert!(!closed[0].contiguous);
|
||||
assert!(!closed[1].contiguous, "the gap is behind the later interaction too");
|
||||
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
|
||||
let closed = host.closed_interactions();
|
||||
assert!(closed.iter().all(|interaction| interaction.contiguous));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
/// The end of an interaction can ride on its last write: a flagged write closes it as a `Meta` op does.
|
||||
#[test]
|
||||
fn a_flagged_write_closes_its_interaction() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
@@ -259,8 +452,3 @@ fn a_flagged_write_closes_its_interaction() {
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].ops.len(), 2, "both writes, and no marker of its own");
|
||||
}
|
||||
|
||||
fn closing(mut hot_op: crate::HotOp) -> crate::HotOp {
|
||||
hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN);
|
||||
hot_op
|
||||
}
|
||||
@@ -161,7 +161,7 @@ fn history_is_causal_and_deterministic() {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: crate::AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -170,73 +170,6 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
|
||||
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
|
||||
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
#[test]
|
||||
fn resurrection_reaches_across_a_merge() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
})
|
||||
.expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
|
||||
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("resurrection must find the AddNetwork on the merged-in branch");
|
||||
}
|
||||
|
||||
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
|
||||
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
|
||||
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
|
||||
@@ -951,7 +884,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone.
|
||||
fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
@@ -965,7 +898,7 @@ fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
}
|
||||
|
||||
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
pub(super) fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
let delta = crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(value)),
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::{NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
|
||||
|
||||
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A root network holding a proto node and a group, with another proto node and a nested group inside
|
||||
/// the group, so projection is exercised two networks deep.
|
||||
fn nested_network() -> NodeNetwork {
|
||||
let inner = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
|
||||
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let group = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
|
||||
(
|
||||
RuntimeNodeId(21),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
|
||||
implementation: DocumentNodeImplementation::Network(inner),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
|
||||
(
|
||||
RuntimeNodeId(2),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
|
||||
implementation: DocumentNodeImplementation::Network(group),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn find_node<'a>(network: &'a NodeNetwork, path: &[RuntimeNodeId], id: RuntimeNodeId) -> &'a DocumentNode {
|
||||
let nested = network.nested_network(path).expect("the path should resolve");
|
||||
nested.nodes.get(&id).expect("the node should exist")
|
||||
}
|
||||
|
||||
/// A node projected alone must match the whole-document conversion, metadata included, since a mirror
|
||||
/// patched from projections has to match one rebuilt whole.
|
||||
#[test]
|
||||
fn projecting_a_node_matches_the_whole_conversion() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
for &id in registry.node_instances.keys() {
|
||||
let projected = projection.node(id).expect("every stored node projects");
|
||||
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
|
||||
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
|
||||
|
||||
assert_eq!(
|
||||
&projected.node,
|
||||
find_node(&whole, &path, local_id),
|
||||
"node {id} projected differently than the whole conversion converts it"
|
||||
);
|
||||
|
||||
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
|
||||
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
|
||||
|
||||
// The nested entries are exactly the whole conversion's entries under this node.
|
||||
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
|
||||
let expected_nested: BTreeSet<_> = node_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.storage_id)
|
||||
.collect();
|
||||
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
|
||||
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
|
||||
|
||||
let expected_networks: BTreeSet<_> = network_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.network_id)
|
||||
.collect();
|
||||
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
|
||||
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_network_entry_projects_its_dense_exports_and_path() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
|
||||
let root = projection.network_entry(ROOT_NETWORK).expect("root");
|
||||
assert!(root.network_path.is_empty());
|
||||
assert_eq!(root.exports, whole.exports);
|
||||
|
||||
for &network_id in registry.networks.keys() {
|
||||
let entry = projection.network_entry(network_id).expect("every stored network projects");
|
||||
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
|
||||
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
|
||||
assert_eq!(entry.scope_injections, nested.scope_injections);
|
||||
if let Some(owner) = projection.owner(network_id) {
|
||||
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
|
||||
assert_eq!(
|
||||
entry.network_path,
|
||||
[owner_path.as_slice(), &[owner_local]].concat(),
|
||||
"a network's path ends in the node implementing it"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A network no node implements is not in the runtime, so nothing inside it has an address.
|
||||
#[test]
|
||||
fn an_unreachable_network_has_no_address() {
|
||||
let mut registry = Registry::default();
|
||||
registry.networks.insert(crate::NetworkId(5), crate::Network::default());
|
||||
let mut node = Node::dummy();
|
||||
node.network = crate::NetworkId(5);
|
||||
registry.node_instances.insert(NodeId(9), node);
|
||||
|
||||
let declarations = crate::Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
assert_eq!(projection.network_path(crate::NetworkId(5)), None);
|
||||
assert_eq!(projection.node_address(NodeId(9)), None);
|
||||
assert!(matches!(projection.node(NodeId(9)), Err(crate::to_runtime::ConversionError::NetworkNotFound(_))));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -112,6 +112,129 @@ fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// One node in runtime form together with the metadata for it and everything nested under it, as
|
||||
/// [`RuntimeProjection::node`] produces it. Entry paths are absolute, as in a whole-document conversion.
|
||||
pub struct ProjectedNode {
|
||||
/// The runtime path of the network the node sits in.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
pub node: DocumentNode,
|
||||
/// The node's own entry first, then one per nested node.
|
||||
pub node_entries: Vec<NodeMetadataEntry>,
|
||||
/// One per network the node's implementation nests, outermost first.
|
||||
pub network_entries: Vec<NetworkMetadataEntry>,
|
||||
}
|
||||
|
||||
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
|
||||
pub struct ProjectedNetwork {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
/// Dense, the way the runtime holds them: a storage slot holding nothing is skipped.
|
||||
pub exports: Vec<GraphCraftNodeInput>,
|
||||
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
|
||||
pub metadata: NetworkMetadataEntry,
|
||||
}
|
||||
|
||||
/// Converts single registry entities to runtime form, for keeping a runtime mirror in step without
|
||||
/// rebuilding it. Owners are gathered once at construction so each address lookup is a probe.
|
||||
pub struct RuntimeProjection<'a> {
|
||||
context: ConversionContext<'a>,
|
||||
/// The node whose implementation each nested network is.
|
||||
owners: FxHashMap<NetworkId, NodeId>,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
|
||||
let owners = self
|
||||
.node_instances
|
||||
.iter()
|
||||
.filter_map(|(&id, node)| match node.implementation {
|
||||
Implementation::Network(network) => Some((network, id)),
|
||||
Implementation::ProtoNode(_) => None,
|
||||
})
|
||||
.collect();
|
||||
RuntimeProjection {
|
||||
context: ConversionContext::new(self, declarations),
|
||||
owners,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeProjection<'_> {
|
||||
/// The node implementing `network`, or `None` for the root and for a network no node implements.
|
||||
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
|
||||
self.owners.get(&network).copied()
|
||||
}
|
||||
|
||||
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
|
||||
/// `None` for a network the root does not reach, which the runtime does not hold.
|
||||
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
|
||||
let mut chain = Vec::new();
|
||||
let mut current = network;
|
||||
while current != ROOT_NETWORK {
|
||||
let owner = self.owner(current)?;
|
||||
let node = self.context.registry.node_instances.get(&owner)?;
|
||||
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
|
||||
if chain.contains(&owner) {
|
||||
return None;
|
||||
}
|
||||
chain.push(owner);
|
||||
current = node.network;
|
||||
}
|
||||
Some(chain.into_iter().rev().map(|owner| runtime_node_id(owner, &self.context.registry.node_instances[&owner])).collect())
|
||||
}
|
||||
|
||||
/// Where the node sits in the runtime: the path of its network, and its id within that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
|
||||
}
|
||||
|
||||
/// The node and everything nested under it, converted the way a whole-document conversion converts
|
||||
/// them, so a mirror patched with the result matches a rebuild.
|
||||
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
|
||||
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
|
||||
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
|
||||
let local_id = runtime_node_id(id, node);
|
||||
|
||||
if let Implementation::Network(nested) = node.implementation {
|
||||
detect_network_cycle(&self.context, nested)?;
|
||||
}
|
||||
|
||||
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
|
||||
let mut network_entries = Some(Vec::new());
|
||||
Ok(ProjectedNode {
|
||||
node: convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?,
|
||||
network_path,
|
||||
local_id,
|
||||
node_entries: node_entries.expect("seeded above"),
|
||||
network_entries: network_entries.expect("seeded above"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The network's exports, scope injections and metadata, without its nodes.
|
||||
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
|
||||
let registry = self.context.registry;
|
||||
// A network removed concurrently with a write into it renders as it was, so its nodes keep their place.
|
||||
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
|
||||
let empty_attrs = crate::Attributes::new();
|
||||
let exports = network
|
||||
.exports
|
||||
.iter()
|
||||
.filter_map(|slot| slot.target.as_ref())
|
||||
.map(|input| convert_input(registry, id, input, &empty_attrs))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ProjectedNetwork {
|
||||
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
|
||||
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
|
||||
exports,
|
||||
network_path,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Which entities a run of ops named, so a runtime mirror of the registry can be brought back into line
|
||||
//! without a full rebuild.
|
||||
//!
|
||||
//! Over-approximate on purpose: an op is recorded whether or not it changed anything, and the mirror
|
||||
//! settles the outcome by comparing each entity's stored and mirrored forms. That is cheaper than having
|
||||
//! every apply arm report its outcome, and stays correct when an op revives an entity it only references.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::{NetworkId, NodeId, NodeInput, RegistryDelta};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Touched {
|
||||
pub nodes: BTreeSet<NodeId>,
|
||||
pub networks: BTreeSet<NetworkId>,
|
||||
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
|
||||
pub resources: bool,
|
||||
}
|
||||
|
||||
impl Touched {
|
||||
/// Records every entity `op` names: its target, and any node it references, since applying it can
|
||||
/// revive a referenced node that was concurrently removed.
|
||||
pub fn record(&mut self, op: &RegistryDelta) {
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. }
|
||||
| RegistryDelta::SetNodeImplementation { id, .. }
|
||||
| RegistryDelta::ChangeNodeAttribute { id, .. }
|
||||
| RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs([new_input]);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
self.networks.insert(*id);
|
||||
self.reference_inputs(export.iter());
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
self.networks.insert(*id);
|
||||
}
|
||||
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
|
||||
self.resources = true;
|
||||
}
|
||||
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: Touched) {
|
||||
self.nodes.extend(other.nodes);
|
||||
self.networks.extend(other.networks);
|
||||
self.resources |= other.resources;
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
|
||||
}
|
||||
|
||||
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
|
||||
for input in inputs {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{AttributeDelta, Network, Node};
|
||||
|
||||
#[test]
|
||||
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
|
||||
assert!(touched.networks.is_empty());
|
||||
assert!(!touched.resources);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_touches_the_network_and_the_node_it_targets() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(3),
|
||||
index: 0,
|
||||
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
|
||||
});
|
||||
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta { key: "key".into(), value: None },
|
||||
});
|
||||
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
|
||||
assert!(touched.is_empty());
|
||||
|
||||
touched.record(&RegistryDelta::SetResourceHash {
|
||||
id: crate::ResourceId::new(),
|
||||
hash: None,
|
||||
});
|
||||
assert!(touched.resources);
|
||||
assert!(touched.nodes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_add_touches_the_node_and_what_its_inputs_reference() {
|
||||
let mut node = Node::dummy();
|
||||
node.inputs.push(crate::InputSlot {
|
||||
input: NodeInput::Node { id: NodeId(9), index: 0 },
|
||||
timestamp: crate::TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
});
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
|
||||
touched.record(&RegistryDelta::AddNetwork {
|
||||
id: NetworkId(5),
|
||||
network: Network::default(),
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(5)]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "document-live"
|
||||
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-format = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,124 @@
|
||||
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
|
||||
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
|
||||
//! async runtime: the caller spawns the transport driver and decides how to render.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout, ResourceProxy};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
#[error(transparent)]
|
||||
Format(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
Conversion(#[from] ConversionError),
|
||||
}
|
||||
|
||||
pub struct LiveDocument {
|
||||
gdd: GddV1,
|
||||
token: SessionToken,
|
||||
}
|
||||
|
||||
impl LiveDocument {
|
||||
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
|
||||
/// future for as long as the session lives.
|
||||
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let gdd = Self::empty_document(peer).await?;
|
||||
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
|
||||
}
|
||||
|
||||
/// Host a session on an already opened document.
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.share(room, user);
|
||||
Self { gdd, token }
|
||||
}
|
||||
|
||||
/// Join the session under `token`; the document fills in once the host's sync arrives.
|
||||
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let mut gdd = Self::empty_document(peer).await?;
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.join(room, user);
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, UserId(peer.0), peer.0, version.clone(), version)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.gdd.role()
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
/// Synced and holding every resource the document references, so `network` can be built and run.
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
/// Resources the document references whose bytes no peer has sent yet; `is_ready` waits on them.
|
||||
pub fn missing_resources(&self) -> Vec<ResourceHash> {
|
||||
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
|
||||
pub async fn poll(&mut self) -> Vec<Event> {
|
||||
let events = self.gdd.poll_peers();
|
||||
for event in &events {
|
||||
let Event::ResourceRequested { from, hash } = event else { continue };
|
||||
match self.gdd.read_resource(hash).await {
|
||||
Ok(bytes) => {
|
||||
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
|
||||
log::warn!("Failed to send resource {hash}: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub fn document(&self) -> &GddV1 {
|
||||
&self.gdd
|
||||
}
|
||||
|
||||
pub fn document_mut(&mut self) -> &mut GddV1 {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
/// Byte store for resources received from peers, for an executor to load from.
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
|
||||
self.gdd.resource_proxy()
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "peer-transport"
|
||||
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
matchbox_socket = "0.14.0"
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_bytes = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
uuid = "1"
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,19 @@
|
||||
pub mod mock;
|
||||
mod packet;
|
||||
mod replica;
|
||||
mod room;
|
||||
mod target;
|
||||
mod token;
|
||||
mod transport;
|
||||
|
||||
pub use packet::{CursorPosition, CursorSpace, PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
|
||||
pub use room::{Incoming, Room};
|
||||
pub use target::{SyncTarget, TargetError};
|
||||
pub use token::{InvalidSessionToken, SessionToken};
|
||||
pub use transport::{Transport, TransportEvent, TransportPeerId};
|
||||
|
||||
pub use matchbox_socket::MessageLoopFuture;
|
||||
|
||||
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
|
||||
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
|
||||
@@ -0,0 +1,172 @@
|
||||
//! In-process transport for deterministic simulation. Packets wait in per-pair queues until `step` delivers
|
||||
//! one, so the seed drives interleavings while each pair stays ordered like a reliable channel.
|
||||
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
connected: Vec<TransportPeerId>,
|
||||
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
|
||||
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
|
||||
next_peer: u128,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.connected.retain(|&other| other != id);
|
||||
self.in_flight.retain(|&(from, to), _| from != id && to != id);
|
||||
for &other in &self.connected.clone() {
|
||||
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
|
||||
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockNetwork {
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl MockNetwork {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self {
|
||||
shared: Arc::new(Mutex::new(Shared::default())),
|
||||
rng: SplitMix64(seed),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, not yet connected peer.
|
||||
pub fn endpoint(&mut self) -> MockEndpoint {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
shared.next_peer += 1;
|
||||
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
|
||||
shared.inboxes.insert(id, VecDeque::new());
|
||||
MockEndpoint {
|
||||
id,
|
||||
shared: self.shared.clone(),
|
||||
known_peers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, id: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
if shared.connected.contains(&id) {
|
||||
return;
|
||||
}
|
||||
for &other in &shared.connected.clone() {
|
||||
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
|
||||
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
|
||||
}
|
||||
shared.connected.push(id);
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.shared.lock().unwrap().disconnect(id);
|
||||
}
|
||||
|
||||
pub fn pending(&self) -> usize {
|
||||
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
|
||||
}
|
||||
|
||||
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
|
||||
pub fn step(&mut self) -> bool {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
|
||||
if queues.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (from, to) = queues[self.rng.below(queues.len())];
|
||||
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn deliver_all(&mut self) {
|
||||
while self.step() {}
|
||||
}
|
||||
|
||||
/// Deliver everything in flight to one peer only, so a test can put a packet in one peer's hands and not another's.
|
||||
pub fn deliver_to(&mut self, to: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
|
||||
|
||||
for key in queues {
|
||||
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
|
||||
for packet in packets {
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn random_below(&mut self, bound: usize) -> usize {
|
||||
self.rng.below(bound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Like a real socket, an endpoint knows only the peers whose connect events it has polled, so it can't send to
|
||||
/// a peer before greeting it.
|
||||
pub struct MockEndpoint {
|
||||
id: TransportPeerId,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
known_peers: Vec<TransportPeerId>,
|
||||
}
|
||||
|
||||
impl MockEndpoint {
|
||||
pub fn id(&self) -> TransportPeerId {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for MockEndpoint {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
if self.known_peers.contains(&to) {
|
||||
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
for to in self.known_peers.clone() {
|
||||
if Some(to) != excluded {
|
||||
self.send(to, packet)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
|
||||
for event in &events {
|
||||
match event {
|
||||
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
|
||||
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.shared.lock().unwrap().disconnect(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
(self.next() % bound as u64) as usize
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The host is the single peer that retires hot ops.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Role {
|
||||
Host,
|
||||
Guest,
|
||||
/// Not yet greeted by a host. See [`Replica::connect`](crate::Replica::connect).
|
||||
Undecided,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts `seq`,
|
||||
/// so `epoch` names the incarnation and counters from different epochs are never compared.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerSeq {
|
||||
pub peer: PeerId,
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
/// MessagePack-encoded on the wire.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum SyncPacket {
|
||||
/// Sent first on every connection. `epoch` and `seq` anchor the receiver's counter for this sender,
|
||||
/// since earlier broadcasts were never sent to it.
|
||||
Hello {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
role: Role,
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
},
|
||||
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
|
||||
SyncRequest {
|
||||
known_revs: Vec<Rev>,
|
||||
},
|
||||
Sync(Box<SyncPayload>),
|
||||
Broadcast(Broadcast),
|
||||
/// Undo (`restore: false`) or redo (`restore: true`) one of the guest's retired interactions, named by its last
|
||||
/// delta. The host answers the room with a `HeadMove` or new deltas.
|
||||
UndoRequest {
|
||||
rev: Rev,
|
||||
restore: bool,
|
||||
},
|
||||
/// Move the shared head back to its ancestor `rev`, leaving the line since as a branch. The host answers the
|
||||
/// room with a `HeadMove` without copies.
|
||||
MoveRequest {
|
||||
rev: Rev,
|
||||
},
|
||||
ResourceRequest(Vec<ResourceHash>),
|
||||
Resource {
|
||||
hash: ResourceHash,
|
||||
#[serde(with = "serde_bytes")]
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// The sender's display name, sent after the hello and on change; the newest wins. Presence is not history,
|
||||
/// so it stays outside the causal broadcast.
|
||||
Profile {
|
||||
name: String,
|
||||
},
|
||||
/// The sender's pointer, `None` when it left the viewport. Sent at most once a frame; the link identifies the sender.
|
||||
Cursor {
|
||||
position: Option<CursorPosition>,
|
||||
},
|
||||
/// A peer's record of the history's users and their names. Outside the causal order, since it merges in any order.
|
||||
Metadata(HistoryMetadata),
|
||||
}
|
||||
|
||||
/// The host's answer to a `SyncRequest`. `registry` is sent only when the host recognized none of the requester's
|
||||
/// revs; otherwise `deltas` extend its history. `seen` is the host's delivery vector at snapshot time, adopted so
|
||||
/// later broadcasts line up.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SyncPayload {
|
||||
pub registry: Option<Registry>,
|
||||
pub deltas: Vec<Delta>,
|
||||
pub head: Option<Rev>,
|
||||
pub hot_log: Vec<HotOp>,
|
||||
pub known_revs: Vec<Rev>,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
/// Which hot ops are retired or taken back, so the requester drops any it holds rather than re-entering it as
|
||||
/// live work.
|
||||
pub retired: RetiredMarks,
|
||||
/// Adopted by a peer that started empty, so opening its own copy later reconnects to the same room.
|
||||
#[serde(default)]
|
||||
pub document_id: Option<u64>,
|
||||
/// So a joiner can name every author.
|
||||
#[serde(default)]
|
||||
pub metadata: HistoryMetadata,
|
||||
}
|
||||
|
||||
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen` is the
|
||||
/// sender's delivery vector; a receiver holds the packet until it has delivered everything in `seen`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Broadcast {
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
pub body: BroadcastBody,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
HotOps(Vec<HotOp>),
|
||||
/// `deltas` are in causal order. `retires` names the hot ops they replace, empty for a plain history transfer.
|
||||
Deltas {
|
||||
deltas: Vec<Delta>,
|
||||
retires: Vec<HotOpId>,
|
||||
},
|
||||
/// Hot ops their author took back: they leave every hot log and never retire.
|
||||
Retract(Vec<HotOpId>),
|
||||
/// Everything a peer knows is retired, re-announced with hot ops on a membership change so a peer that joined
|
||||
/// during a retirement or retraction still hears of it.
|
||||
RetiredMarks(RetiredMarks),
|
||||
/// The host dropped a retired interaction out of the line: every peer walks back and follows the head.
|
||||
HeadMove(HeadMove),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PacketError {
|
||||
#[error("failed to encode packet: {0}")]
|
||||
Encode(#[from] rmp_serde::encode::Error),
|
||||
#[error("failed to decode packet: {0}")]
|
||||
Decode(#[from] rmp_serde::decode::Error),
|
||||
}
|
||||
|
||||
impl SyncPacket {
|
||||
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
|
||||
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
|
||||
Ok(rmp_serde::from_slice(bytes)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// A peer's pointer, with its space so it is drawn only where it means something.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CursorPosition {
|
||||
pub position: [f64; 2],
|
||||
pub space: CursorSpace,
|
||||
/// Icon name of the peer's tool, shown beside the pointer; `None` from a viewer with no tools.
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum CursorSpace {
|
||||
/// Document coordinates over the canvas.
|
||||
Document,
|
||||
/// Node-graph coordinates in the network at this node-id path from the document network.
|
||||
Graph { network: Vec<u64> },
|
||||
}
|
||||
@@ -0,0 +1,968 @@
|
||||
use crate::packet::{Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::target::{SyncTarget, TargetError};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub enum Event {
|
||||
PeerJoined {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
},
|
||||
PeerLeft {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// This peer's own role changed: it took over from a departed host, stepped aside unsynced, or yielded to a lower id.
|
||||
RoleChanged {
|
||||
role: Role,
|
||||
},
|
||||
/// A peer's display name arrived or changed.
|
||||
ProfileChanged {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// A peer's pointer moved, or left the viewport.
|
||||
CursorMoved {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// Something on record about the history's users changed, from a peer or a sync.
|
||||
MetadataChanged,
|
||||
/// The guest has applied the host's state.
|
||||
Synced,
|
||||
/// Remote ops changed the target.
|
||||
Changed,
|
||||
ResourceReceived {
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// The target couldn't serve this synchronously; answer with `send_resource`.
|
||||
ResourceRequested {
|
||||
from: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReplicaError {
|
||||
#[error(transparent)]
|
||||
Packet(#[from] PacketError),
|
||||
#[error(transparent)]
|
||||
Target(#[from] TargetError),
|
||||
}
|
||||
|
||||
/// A peer in the room as its last hello described it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RemotePeer {
|
||||
pub peer: PeerId,
|
||||
pub user: UserId,
|
||||
pub role: Role,
|
||||
/// Empty until its profile arrives.
|
||||
pub name: String,
|
||||
/// In document space; `None` when not over the viewport.
|
||||
pub cursor: Option<CursorPosition>,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts have been delivered here.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PeerProgress {
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
/// Broadcasts arriving before the host's `Sync` are held back, since they target state the guest doesn't have yet.
|
||||
enum SyncState {
|
||||
Synced,
|
||||
AwaitingSync { pending: Vec<(PeerId, Broadcast)> },
|
||||
}
|
||||
|
||||
/// Protocol state for one peer in a room. Owns no document; `poll` applies into a `SyncTarget`.
|
||||
///
|
||||
/// Broadcasts are delivered in causal order: each carries the sender's sequence number and delivery
|
||||
/// vector, and is held until everything the sender had delivered has been delivered here too.
|
||||
pub struct Replica {
|
||||
transport: Box<dyn Transport>,
|
||||
role: Role,
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
/// Sent with every hello and on change.
|
||||
name: String,
|
||||
peers: HashMap<TransportPeerId, RemotePeer>,
|
||||
/// The role each link was last greeted with, so a link greeted before a role change is greeted again.
|
||||
greeted: HashMap<TransportPeerId, Role>,
|
||||
sync: SyncState,
|
||||
/// Drawn fresh so a reconnect or a reload never reuses one. See [`PeerSeq`].
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
delivered: HashMap<PeerId, PeerProgress>,
|
||||
held: Vec<(PeerId, Broadcast)>,
|
||||
/// Hot ops whose referents had not arrived, retried as later ops fill the gaps. A missing entity is
|
||||
/// indistinguishable from a concurrently removed one, so the op waits rather than applying against state it does not fit.
|
||||
deferred: Vec<HotOp>,
|
||||
/// Asked for and not yet received, so a standing request is not resent every poll.
|
||||
requested_resources: HashSet<ResourceHash>,
|
||||
/// Requests that arrived before the bytes did, answered once they turn up.
|
||||
owed_resources: HashMap<ResourceHash, HashSet<TransportPeerId>>,
|
||||
/// Whether the target's resource references may have moved since last examined.
|
||||
resources_stale: bool,
|
||||
/// The unanswered sync request's link, so it is asked again only if that peer stops hosting first.
|
||||
sync_requested_from: Option<TransportPeerId>,
|
||||
/// The host whose line this peer holds: the one it last synced from, or itself. Any other host calls for a
|
||||
/// sync from it, since what it retired may never have been broadcast here. See [`Self::follow_current_host`].
|
||||
synced_from: Option<PeerId>,
|
||||
}
|
||||
|
||||
impl Replica {
|
||||
pub fn host(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Host, peer, user, SyncState::Synced)
|
||||
}
|
||||
|
||||
/// Join through a link, expecting a host. The role stays undecided until that host greets, so a link into a room
|
||||
/// whose host is gone elects like anyone else rather than waiting for a greeting that never comes.
|
||||
pub fn guest(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::connect(transport, peer, user)
|
||||
}
|
||||
|
||||
/// Connect to the document's room in whichever role it calls for: a host's hello makes this peer a guest, and
|
||||
/// [`decide_role`](Self::decide_role) makes it the host if none greets in time.
|
||||
pub fn connect(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Undecided, peer, user, SyncState::AwaitingSync { pending: Vec::new() })
|
||||
}
|
||||
|
||||
/// For a peer still undecided after the grace period: become the host unless an undecided peer with a lower id
|
||||
/// will. A room with guests is never seized; they elect among themselves when their host leaves. Returns the role taken.
|
||||
pub fn decide_role(&mut self) -> Option<Role> {
|
||||
if self.role != Role::Undecided {
|
||||
return None;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.role != Role::Undecided) {
|
||||
return None;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.peer < self.peer) {
|
||||
return None;
|
||||
}
|
||||
log::debug!("Join handshake: no host greeted, becoming the host");
|
||||
self.become_host();
|
||||
Some(Role::Host)
|
||||
}
|
||||
|
||||
/// An unsynced peer asks the known host for a sync, again only if that peer stops hosting or leaves first.
|
||||
fn ensure_sync_requested(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.is_synced() || self.sync_requested_from.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
log::debug!("Join handshake: sync request sent to the host");
|
||||
self.sync_requested_from = Some(host);
|
||||
self.transport.send(host, &SyncPacket::SyncRequest { known_revs: target.known_revs() })
|
||||
}
|
||||
|
||||
/// A synced guest whose host is not the one it synced from syncs from it, since what that host retired may never
|
||||
/// have been broadcast here. The sync merges onto what is held.
|
||||
fn follow_current_host(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.role != Role::Guest || !self.is_synced() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(host) = self.peers.values().find(|remote| remote.role == Role::Host).map(|remote| remote.peer) else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.synced_from == Some(host) {
|
||||
return Ok(());
|
||||
}
|
||||
log::debug!("Syncing from {host:?}, a host this peer has not synced from");
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = None;
|
||||
self.ensure_sync_requested(target)
|
||||
}
|
||||
|
||||
/// Ask the host for its line again, naming what is held so it sends only the rest. Broadcasts arriving meanwhile
|
||||
/// are buffered as on a first sync.
|
||||
fn request_resync(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.role == Role::Host || !self.is_synced() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
log::info!("A retired step arrived whose parent is missing here; syncing from the host again");
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = Some(host);
|
||||
self.transport.send(host, &SyncPacket::SyncRequest { known_revs: target.known_revs() })
|
||||
}
|
||||
|
||||
/// Take the host role and tell the room. Broadcasts buffered for a sync that now never comes are kept for
|
||||
/// delivery, or the sender's later ones would wait on them forever.
|
||||
fn become_host(&mut self) {
|
||||
self.role = Role::Host;
|
||||
self.synced_from = Some(self.peer);
|
||||
if let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) {
|
||||
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
|
||||
self.held.extend(worth_holding);
|
||||
}
|
||||
self.announce_role();
|
||||
}
|
||||
|
||||
/// Greet every peer again with the current role; a known peer takes it as a role change only.
|
||||
fn announce_role(&mut self) {
|
||||
let peers: Vec<TransportPeerId> = self.peers.keys().copied().collect();
|
||||
for transport_peer in peers {
|
||||
if let Err(error) = self.send_hello(transport_peer) {
|
||||
log::error!("Announcing the {:?} role: {error}", self.role);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In a room left without a host, the synced guest with the lowest id takes the role; every peer applies the
|
||||
/// same rule to the same membership, so they agree. An unsynced guest has nothing to serve, so it steps aside as
|
||||
/// undecided, which re-runs the rule on the rest through its greeting and has it sync from whoever takes over.
|
||||
fn settle_without_host(&mut self, events: &mut Vec<Event>) {
|
||||
if self.role != Role::Guest || self.peers.values().any(|remote| remote.role == Role::Host) {
|
||||
return;
|
||||
}
|
||||
if !self.is_synced() {
|
||||
log::info!("The host went before syncing this peer; waiting for whoever takes over");
|
||||
self.role = Role::Undecided;
|
||||
self.sync_requested_from = None;
|
||||
self.announce_role();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
return;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.role == Role::Guest && remote.peer < self.peer) {
|
||||
return;
|
||||
}
|
||||
log::info!("The host went; taking the host role over as the lowest synced peer");
|
||||
self.become_host();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
|
||||
fn new(transport: Box<dyn Transport>, role: Role, peer: PeerId, user: UserId, sync: SyncState) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
role,
|
||||
peer,
|
||||
user,
|
||||
name: String::new(),
|
||||
peers: HashMap::new(),
|
||||
greeted: HashMap::new(),
|
||||
sync,
|
||||
epoch: core_types::uuid::generate_uuid(),
|
||||
seq: 0,
|
||||
delivered: HashMap::new(),
|
||||
held: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
requested_resources: HashSet::new(),
|
||||
owed_resources: HashMap::new(),
|
||||
resources_stale: false,
|
||||
sync_requested_from: None,
|
||||
synced_from: (role == Role::Host).then_some(peer),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Role {
|
||||
self.role
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
matches!(self.sync, SyncState::Synced)
|
||||
}
|
||||
|
||||
/// The display name this peer announces, sent to the room on change and with every hello.
|
||||
pub fn set_name(&mut self, name: &str) -> Result<(), PacketError> {
|
||||
if self.name == name {
|
||||
return Ok(());
|
||||
}
|
||||
self.name = name.to_string();
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Profile { name: self.name.clone() })
|
||||
}
|
||||
|
||||
/// Tell the room this peer's history metadata after it changed here.
|
||||
pub fn send_metadata(&mut self, metadata: &HistoryMetadata) -> Result<(), PacketError> {
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Metadata(metadata.clone()))
|
||||
}
|
||||
|
||||
/// Tell the room where this peer's pointer is, `None` once it left the viewport. The caller coalesces to at
|
||||
/// most one call per frame.
|
||||
pub fn send_cursor(&mut self, position: Option<CursorPosition>) -> Result<(), PacketError> {
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Cursor { position })
|
||||
}
|
||||
|
||||
/// The other peers in the room, in no particular order.
|
||||
pub fn peers(&self) -> impl Iterator<Item = &RemotePeer> + '_ {
|
||||
self.peers.values()
|
||||
}
|
||||
|
||||
/// Broadcasts waiting on causal dependencies. Non-zero in an idle room means a stuck delivery.
|
||||
pub fn held_broadcasts(&self) -> usize {
|
||||
self.held.len()
|
||||
}
|
||||
|
||||
/// One line per held broadcast saying what it waits on, for inspecting a stuck room.
|
||||
#[doc(hidden)]
|
||||
pub fn describe_held(&self) -> Vec<String> {
|
||||
self.held
|
||||
.iter()
|
||||
.map(|(sender, broadcast)| {
|
||||
let progress = self.delivered.get(sender).map(|progress| (progress.epoch, progress.seq));
|
||||
let unmet: Vec<String> = broadcast
|
||||
.seen
|
||||
.iter()
|
||||
.filter(|mark| mark.peer != *sender && !self.has_delivered(**mark))
|
||||
.map(|mark| format!("{:?}@{}:{} (here {:?})", mark.peer, mark.epoch, mark.seq, self.delivered.get(&mark.peer).map(|p| (p.epoch, p.seq))))
|
||||
.collect();
|
||||
format!("from {sender:?} epoch {} seq {} (delivered {progress:?}) unmet {unmet:?}", broadcast.epoch, broadcast.seq)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ops held back for a referent that had not arrived. Non-zero in an idle room means one never did.
|
||||
pub fn deferred_ops(&self) -> usize {
|
||||
self.deferred.len()
|
||||
}
|
||||
|
||||
/// Resources asked for whose bytes have not come back yet.
|
||||
pub fn pending_resource_requests(&self) -> impl Iterator<Item = ResourceHash> + '_ {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// A local edit can name a resource whose bytes are not here, such as a pasted node's font.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Ask the host to undo (`restore == false`) or redo (`restore == true`) this peer's retired interaction.
|
||||
/// A host undoes its own directly with [`broadcast_head_move`](Self::broadcast_head_move).
|
||||
pub fn request_undo(&mut self, rev: Rev, restore: bool) -> Result<(), PacketError> {
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.transport.send(host, &SyncPacket::UndoRequest { rev, restore })
|
||||
}
|
||||
|
||||
/// Ask the host to move the shared head to `rev`, an ancestor of it. A host moves its own directly with
|
||||
/// [`broadcast_head_move`](Self::broadcast_head_move).
|
||||
pub fn request_move(&mut self, rev: Rev) -> Result<(), PacketError> {
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.transport.send(host, &SyncPacket::MoveRequest { rev })
|
||||
}
|
||||
|
||||
/// Host only: tell the room the head moved, with the steps minted again under it.
|
||||
pub fn broadcast_head_move(&mut self, moved: HeadMove) -> Result<(), PacketError> {
|
||||
debug_assert_eq!(self.role, Role::Host);
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::HeadMove(moved))
|
||||
}
|
||||
|
||||
/// Take back this peer's own hot ops, already gone from the local log, so every other peer drops them too.
|
||||
pub fn broadcast_retraction(&mut self, ops: &[HotOpId]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::Retract(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Host only.
|
||||
pub fn broadcast_retired(&mut self, deltas: &[Delta], retires: &[HotOpId]) -> Result<(), PacketError> {
|
||||
debug_assert_eq!(self.role, Role::Host);
|
||||
// An interaction of nothing but its marker retires with no delta, and the marker still has to go.
|
||||
if deltas.is_empty() && retires.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// References are read from history as well as the registry, so retiring can re-reference a hash the registry overwrote.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: deltas.to_vec(),
|
||||
retires: retires.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn broadcast(&mut self, body: BroadcastBody) -> Result<(), PacketError> {
|
||||
self.seq += 1;
|
||||
let broadcast = Broadcast {
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
seen: self.seen_vector(),
|
||||
body,
|
||||
};
|
||||
self.transport.broadcast(&SyncPacket::Broadcast(broadcast))
|
||||
}
|
||||
|
||||
/// Everything delivered here, including this peer's own broadcasts.
|
||||
fn seen_vector(&self) -> Vec<PeerSeq> {
|
||||
let delivered = self.delivered.iter().map(|(&peer, progress)| PeerSeq {
|
||||
peer,
|
||||
epoch: progress.epoch,
|
||||
seq: progress.seq,
|
||||
});
|
||||
delivered
|
||||
.chain([PeerSeq {
|
||||
peer: self.peer,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
}])
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.transport.close();
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, target: &mut dyn SyncTarget) -> Vec<Event> {
|
||||
let mut events = Vec::new();
|
||||
let transport_events = self.transport.poll();
|
||||
|
||||
// Greet every new peer before handling the batch. The transport adds them to its send set up front, so a
|
||||
// broadcast made meanwhile would reach them before a hello whose seq already covers it, and be skipped.
|
||||
for transport_event in &transport_events {
|
||||
if let TransportEvent::PeerConnected(transport_peer) = transport_event
|
||||
&& let Err(error) = self.send_hello(*transport_peer)
|
||||
{
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
for transport_event in transport_events {
|
||||
let result = match transport_event {
|
||||
TransportEvent::PeerConnected(_) => Ok(()),
|
||||
TransportEvent::PeerDisconnected(transport_peer) => {
|
||||
self.greeted.remove(&transport_peer);
|
||||
if self.sync_requested_from == Some(transport_peer) {
|
||||
self.sync_requested_from = None;
|
||||
}
|
||||
let departed = self.peers.remove(&transport_peer);
|
||||
log::debug!("Link {transport_peer:?} closed: {:?}", departed.as_ref().map(|remote| (remote.peer, remote.role)));
|
||||
if let Some(remote) = &departed {
|
||||
events.push(Event::PeerLeft { peer: remote.peer });
|
||||
}
|
||||
// The departed peer may have owed bytes, so let the rest be asked.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
|
||||
match departed {
|
||||
Some(remote) => {
|
||||
let closed = self.close_epoch(remote.peer, target, &mut events);
|
||||
// Any departure can settle the election, since a guest that deferred to a lower id is the
|
||||
// candidate once that id is gone. A sync asked of the departed peer goes to whoever hosts.
|
||||
self.settle_without_host(&mut events);
|
||||
closed.and_then(|()| self.ensure_sync_requested(&*target).map_err(ReplicaError::from))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events),
|
||||
TransportEvent::Malformed(transport_peer, error) => {
|
||||
log::warn!("Dropping malformed packet from {transport_peer}: {error}");
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = result {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// A role decision can release broadcasts buffered for a sync that never comes, with no packet arriving.
|
||||
if !self.held.is_empty()
|
||||
&& let Err(error) = self.deliver_held(target, &mut events)
|
||||
{
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
self.retry_deferred(target, &mut events);
|
||||
|
||||
if let Err(error) = target.flush() {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.request_missing_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.serve_owed_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
/// Re-announce every hot op held here that history does not cover, whoever wrote it, since this peer may hold
|
||||
/// the only copy of another's op. Covered ops are no-ops on every receiver.
|
||||
fn reannounce_hot_ops(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
let retired = target.retired_marks();
|
||||
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
|
||||
|
||||
self.broadcast_hot_ops(&unretired)?;
|
||||
// A retraction in flight when a peer joined never reached it and nothing re-sends it, so the marks go round too.
|
||||
if retired.retired_up_to.is_empty() && retired.retired_runs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.broadcast(BroadcastBody::RetiredMarks(retired))
|
||||
}
|
||||
|
||||
/// Retry ops held back for a missing referent, every poll, since any later op can supply it.
|
||||
fn retry_deferred(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) {
|
||||
if self.deferred.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let pending = std::mem::take(&mut self.deferred);
|
||||
let waiting = pending.len();
|
||||
match target.apply_remote_hot_ops(pending) {
|
||||
Ok(deferred) => {
|
||||
// Nothing else in the poll notices that one applied, changing the target and maybe naming a new resource.
|
||||
if deferred.len() < waiting {
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
self.deferred = deferred;
|
||||
}
|
||||
Err(error) => log::error!("Retrying deferred hot ops: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the room for referenced bytes not held here, after every batch since any delivered op can reference
|
||||
/// a new resource. Hashes with a standing request are skipped.
|
||||
fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if !self.resources_stale {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = false;
|
||||
|
||||
let missing = target.missing_resources();
|
||||
// A resource that turned up some other way leaves its request behind, which would suppress a later ask.
|
||||
self.requested_resources.retain(|hash| missing.contains(hash));
|
||||
|
||||
// Sorted so `HashSet` order does not reach the wire and make a seeded run unreproducible.
|
||||
let mut unasked: Vec<ResourceHash> = missing.into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect();
|
||||
unasked.sort_unstable();
|
||||
if unasked.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.requested_resources.extend(unasked.iter().copied());
|
||||
self.transport.broadcast(&SyncPacket::ResourceRequest(unasked))
|
||||
}
|
||||
|
||||
/// Answer requests that arrived before their bytes did. Runs every poll, since bytes can turn up locally and a
|
||||
/// requester never asks twice.
|
||||
fn serve_owed_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.owed_resources.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Both loops run sorted so hash order does not decide send order and make a seeded run unreproducible.
|
||||
let mut ready: Vec<(ResourceHash, Vec<u8>)> = self.owed_resources.keys().filter_map(|&hash| target.resource_bytes(hash).map(|bytes| (hash, bytes))).collect();
|
||||
ready.sort_unstable_by_key(|(hash, _)| *hash);
|
||||
|
||||
for (hash, bytes) in ready {
|
||||
let mut recipients: Vec<TransportPeerId> = self.owed_resources.remove(&hash).unwrap_or_default().into_iter().collect();
|
||||
recipients.sort_unstable();
|
||||
|
||||
for to in recipients {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes: bytes.clone() })?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> {
|
||||
let hello = SyncPacket::Hello {
|
||||
peer: self.peer,
|
||||
user: self.user,
|
||||
role: self.role,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
};
|
||||
log::debug!("Join handshake: hello sent to {transport_peer:?} as {:?}", self.role);
|
||||
self.transport.send(transport_peer, &hello)?;
|
||||
self.greeted.insert(transport_peer, self.role);
|
||||
if !self.name.is_empty() {
|
||||
self.transport.send(transport_peer, &SyncPacket::Profile { name: self.name.clone() })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_packet(&mut self, from: TransportPeerId, packet: SyncPacket, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
match packet {
|
||||
SyncPacket::Hello { peer, user, role, epoch, seq } => {
|
||||
log::debug!("Join handshake: hello from {peer:?} ({role:?}), synced {}", self.is_synced());
|
||||
// A re-greeting over the same link and epoch announces a role; re-anchoring would strand its held broadcasts.
|
||||
let known = self.peers.contains_key(&from) && self.delivered.get(&peer).is_some_and(|progress| progress.epoch == epoch);
|
||||
// A re-greeting keeps the presence the link already announced.
|
||||
let presence = self.peers.remove(&from);
|
||||
self.peers.insert(
|
||||
from,
|
||||
RemotePeer {
|
||||
peer,
|
||||
user,
|
||||
role,
|
||||
name: presence.as_ref().map(|remote| remote.name.clone()).unwrap_or_default(),
|
||||
cursor: presence.and_then(|remote| remote.cursor),
|
||||
},
|
||||
);
|
||||
if !known {
|
||||
self.anchor_delivered(peer, epoch, seq);
|
||||
|
||||
// Can unblock broadcasts held against an earlier link's counter.
|
||||
self.deliver_held(target, events)?;
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
events.push(Event::PeerJoined { peer, user });
|
||||
// A fresh peer may hold bytes nobody else here could serve.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
}
|
||||
|
||||
if role == Role::Host && self.role == Role::Undecided {
|
||||
self.role = Role::Guest;
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
// Two hosts meet briefly when elections ran on differing memberships; the lower id keeps the role.
|
||||
if role == Role::Host && self.role == Role::Host && peer < self.peer {
|
||||
log::info!("Yielding the host role to {peer:?}, which has the lower id");
|
||||
self.role = Role::Guest;
|
||||
// Sync from it below, handing over what this peer retired alone, and tell the room so nobody
|
||||
// keeps asking this peer for what only a host answers.
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = None;
|
||||
self.announce_role();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
self.follow_current_host(&*target)?;
|
||||
// A link greeted with an earlier role before it became a known peer hears the current one, or a
|
||||
// guest joining as the host changes would never learn who hosts.
|
||||
if self.greeted.get(&from) != Some(&self.role) {
|
||||
self.send_hello(from)?;
|
||||
}
|
||||
// The peer asked for a sync stopped hosting before answering.
|
||||
if self.sync_requested_from == Some(from) && role != Role::Host {
|
||||
self.sync_requested_from = None;
|
||||
}
|
||||
self.ensure_sync_requested(&*target)?;
|
||||
// A host yielding or a guest stepping aside can leave the room hostless or make this peer the lowest candidate.
|
||||
if role != Role::Host {
|
||||
self.settle_without_host(events);
|
||||
}
|
||||
}
|
||||
SyncPacket::UndoRequest { rev, restore } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
// Best effort: a request naming a step no longer on this host's line is reported and dropped.
|
||||
let outcome: Result<(), TargetError> = if restore {
|
||||
target.restore_interaction(rev).and_then(|deltas| self.broadcast_retired(&deltas, &[]).map_err(TargetError::from))
|
||||
} else {
|
||||
target.drop_interaction(rev).and_then(|moved| self.broadcast_head_move(moved).map_err(TargetError::from))
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => events.push(Event::Changed),
|
||||
Err(error) => log::error!("Undo request for {rev:?} failed: {error}"),
|
||||
}
|
||||
}
|
||||
SyncPacket::MoveRequest { rev } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
let outcome = target.move_head_to(rev).and_then(|moved| self.broadcast_head_move(moved).map_err(TargetError::from));
|
||||
match outcome {
|
||||
Ok(()) => events.push(Event::Changed),
|
||||
Err(error) => log::error!("Move request to {rev:?} failed: {error}"),
|
||||
}
|
||||
}
|
||||
SyncPacket::SyncRequest { known_revs } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
let shares_history = known_revs.iter().any(|&rev| target.contains_rev(rev));
|
||||
log::debug!("Join handshake: sync request from {from:?}, shares history {shares_history}");
|
||||
let sync = SyncPayload {
|
||||
registry: (!shares_history).then(|| target.retired_registry()),
|
||||
deltas: target.deltas_unknown_to(&known_revs),
|
||||
head: target.head(),
|
||||
hot_log: target.hot_log(),
|
||||
known_revs: target.known_revs(),
|
||||
seen: self.seen_vector(),
|
||||
retired: target.retired_marks(),
|
||||
document_id: target.document_id(),
|
||||
metadata: target.metadata(),
|
||||
};
|
||||
log::debug!("Join handshake: sync answered with {} deltas and {} hot ops", sync.deltas.len(), sync.hot_log.len());
|
||||
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
|
||||
}
|
||||
SyncPacket::Sync(sync) => {
|
||||
log::debug!("Join handshake: sync received with {} deltas, full registry {}", sync.deltas.len(), sync.registry.is_some());
|
||||
self.sync_requested_from = None;
|
||||
let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.synced_from = self.peers.get(&from).map(|remote| remote.peer);
|
||||
// A full registry replaces a fresh copy's session, so its unretired ops, possibly the only copy of
|
||||
// what never reached the host, are replayed on top. A copy with retired history is never replaced,
|
||||
// or a host over an empty document would wipe it; its line merges and what the host lacks goes back.
|
||||
let full = sync.registry.is_some() && target.known_revs().is_empty();
|
||||
let held = if full { target.hot_log() } else { Vec::new() };
|
||||
|
||||
match (full, sync.registry) {
|
||||
(true, Some(registry)) => target.load(registry, sync.deltas, sync.head)?,
|
||||
_ => target.merge_remote(sync.deltas, &[], sync.head)?,
|
||||
}
|
||||
// A copy that joined by link takes the room's document id, or its own link would name an empty room.
|
||||
if let Some(document_id) = sync.document_id
|
||||
&& target.document_id() != Some(document_id)
|
||||
{
|
||||
target.adopt_document_id(document_id)?;
|
||||
}
|
||||
target.absorb_retired_marks(&sync.retired)?;
|
||||
if target.absorb_metadata(&sync.metadata)? {
|
||||
events.push(Event::MetadataChanged);
|
||||
}
|
||||
// Metadata recorded here while apart reaches the room too.
|
||||
let own = target.metadata();
|
||||
if !own.is_empty() {
|
||||
self.transport.broadcast_except(None, &SyncPacket::Metadata(own))?;
|
||||
}
|
||||
|
||||
self.deferred.extend(target.apply_remote_hot_ops(held)?);
|
||||
self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?);
|
||||
self.resources_stale = true;
|
||||
|
||||
// This peer may hold the only copy of an op that never reached the host.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
|
||||
// Broadcasts the host delivered before answering are in the snapshot.
|
||||
for mark in sync.seen {
|
||||
self.observe_delivered(mark);
|
||||
}
|
||||
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
|
||||
self.held.extend(worth_holding);
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
let host_is_missing = target.deltas_unknown_to(&sync.known_revs);
|
||||
if !host_is_missing.is_empty() {
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: host_is_missing,
|
||||
retires: Vec::new(),
|
||||
})?;
|
||||
}
|
||||
// The answering host may have yielded meanwhile.
|
||||
self.follow_current_host(&*target)?;
|
||||
|
||||
// Unlike retired work, hot ops exist only in flight, so a drop loses them. Re-announce our own.
|
||||
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
|
||||
self.broadcast_hot_ops(&own_hot_ops)?;
|
||||
|
||||
events.push(Event::Synced);
|
||||
}
|
||||
SyncPacket::Broadcast(broadcast) => {
|
||||
// Senders greet before broadcasting over a per-pair ordered channel, so this means the transport reordered.
|
||||
let Some(remote) = self.peers.get(&from) else {
|
||||
log::error!("Dropping a broadcast from a peer that never said hello");
|
||||
return Ok(());
|
||||
};
|
||||
let sender = remote.peer;
|
||||
match &mut self.sync {
|
||||
SyncState::AwaitingSync { pending } => pending.push((sender, broadcast)),
|
||||
SyncState::Synced => {
|
||||
if self.worth_holding(sender, &broadcast) {
|
||||
self.held.push((sender, broadcast));
|
||||
self.deliver_held(target, events)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::Profile { name } => {
|
||||
// Presence from a link that has not said hello belongs to nobody yet.
|
||||
if let Some(remote) = self.peers.get_mut(&from)
|
||||
&& remote.name != name
|
||||
{
|
||||
remote.name = name;
|
||||
events.push(Event::ProfileChanged { peer: remote.peer });
|
||||
}
|
||||
}
|
||||
SyncPacket::Cursor { position } => {
|
||||
if let Some(remote) = self.peers.get_mut(&from)
|
||||
&& remote.cursor != position
|
||||
{
|
||||
remote.cursor = position;
|
||||
events.push(Event::CursorMoved { peer: remote.peer });
|
||||
}
|
||||
}
|
||||
SyncPacket::Metadata(remote) => {
|
||||
if target.absorb_metadata(&remote)? {
|
||||
events.push(Event::MetadataChanged);
|
||||
}
|
||||
}
|
||||
SyncPacket::ResourceRequest(hashes) => {
|
||||
for hash in hashes {
|
||||
match target.resource_bytes(hash) {
|
||||
Some(bytes) => self.transport.send(from, &SyncPacket::Resource { hash, bytes })?,
|
||||
None => {
|
||||
self.owed_resources.entry(hash).or_default().insert(from);
|
||||
events.push(Event::ResourceRequested { from, hash });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::Resource { hash, bytes } => {
|
||||
if ResourceHash::from(bytes.as_slice()) != hash {
|
||||
log::warn!("Resource from {from} does not match its hash; dropping");
|
||||
return Ok(());
|
||||
}
|
||||
target.store_resource(hash, &bytes)?;
|
||||
self.requested_resources.remove(&hash);
|
||||
events.push(Event::ResourceReceived { hash, bytes });
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that a peer's broadcasts up to `mark` need not be waited for. Monotonic, since a hello and a host's
|
||||
/// `seen` vector can carry the same fact in either order.
|
||||
fn observe_delivered(&mut self, mark: PeerSeq) {
|
||||
if mark.peer == self.peer {
|
||||
return;
|
||||
}
|
||||
match self.delivered.get_mut(&mark.peer) {
|
||||
Some(progress) if progress.epoch == mark.epoch => progress.seq = progress.seq.max(mark.seq),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
self.delivered.insert(mark.peer, PeerProgress { epoch: mark.epoch, seq: mark.seq });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set where a peer's broadcasts resume on a new link. Replaces rather than raises, since nothing before its
|
||||
/// hello was sent here.
|
||||
fn anchor_delivered(&mut self, peer: PeerId, epoch: u64, seq: u64) {
|
||||
if peer == self.peer {
|
||||
return;
|
||||
}
|
||||
self.delivered.insert(peer, PeerProgress { epoch, seq });
|
||||
}
|
||||
|
||||
/// Settle up after a peer leaves: its held broadcasts can never fill their gaps, and anything waiting on it is free.
|
||||
fn close_epoch(&mut self, peer: PeerId, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
// Applying its buffered broadcasts would mint orphans no departure is left to clean up, and dropping
|
||||
// them breaks no dependency since none applied yet.
|
||||
if let SyncState::AwaitingSync { pending } = &mut self.sync {
|
||||
pending.retain(|(sender, _)| *sender != peer);
|
||||
}
|
||||
self.held.retain(|(sender, _)| *sender != peer);
|
||||
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
// The departed peer's unretired work reached only some peers, and it cannot re-announce it itself.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a link to this peer is open, so more of its broadcasts may turn up.
|
||||
fn is_connected(&self, peer: PeerId) -> bool {
|
||||
self.peers.values().any(|remote| remote.peer == peer)
|
||||
}
|
||||
|
||||
/// Deliver every held broadcast whose causal dependencies are met, repeating since each can unblock others.
|
||||
fn deliver_held(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
while let Some(index) = self.held.iter().position(|(sender, broadcast)| self.is_deliverable(*sender, broadcast)) {
|
||||
let (sender, broadcast) = self.held.remove(index);
|
||||
self.delivered.insert(
|
||||
sender,
|
||||
PeerProgress {
|
||||
epoch: broadcast.epoch,
|
||||
seq: broadcast.seq,
|
||||
},
|
||||
);
|
||||
|
||||
// Best effort: a failure is reported rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
|
||||
// A retired step whose parent never arrived here cannot apply. A guest resyncs from the host; a host
|
||||
// lets it go, since the sender's whole line arrives when the sender syncs from it.
|
||||
BroadcastBody::Deltas { deltas, .. }
|
||||
if deltas
|
||||
.iter()
|
||||
.any(|delta| delta.all_parents().any(|parent| !target.contains_rev(parent) && !deltas.iter().any(|held| held.id == parent))) =>
|
||||
{
|
||||
if self.role == Role::Host {
|
||||
log::info!("A retired step arrived whose parent is missing here; its author's line comes with its sync");
|
||||
Ok(())
|
||||
} else {
|
||||
self.request_resync(&*target).map_err(TargetError::from)
|
||||
}
|
||||
}
|
||||
// The host joins a diverged line with a merge delta, and the room follows to the joined head.
|
||||
BroadcastBody::Deltas { deltas, retires } if self.role == Role::Host => target.merge_divergent(deltas, &retires).and_then(|minted| {
|
||||
if minted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.broadcast(BroadcastBody::Deltas { deltas: minted, retires: Vec::new() }).map_err(TargetError::from)
|
||||
}),
|
||||
BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires, None),
|
||||
BroadcastBody::Retract(ops) => {
|
||||
// A copy still waiting on a referent is taken back with the rest.
|
||||
self.deferred.retain(|hot_op| !ops.contains(&hot_op.id()));
|
||||
target.retract_hot_ops(&ops)
|
||||
}
|
||||
BroadcastBody::RetiredMarks(marks) => {
|
||||
self.deferred.retain(|hot_op| !marks.covers(hot_op.id()));
|
||||
target.absorb_retired_marks(&marks)
|
||||
}
|
||||
BroadcastBody::HeadMove(moved) => target.apply_head_move(&moved),
|
||||
};
|
||||
if let Err(error) = applied {
|
||||
log::error!("Applying a delivered broadcast: {error}");
|
||||
}
|
||||
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_deliverable(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
let Some(progress) = self.delivered.get(&sender) else { return false };
|
||||
if progress.epoch != broadcast.epoch || broadcast.seq != progress.seq + 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
broadcast.seen.iter().all(|&mark| mark.peer == sender || self.has_delivered(mark))
|
||||
}
|
||||
|
||||
/// Whether a broadcast can still come up for delivery; a stale epoch or delivered seq never will.
|
||||
fn worth_holding(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
self.delivered.get(&sender).is_none_or(|progress| progress.epoch == broadcast.epoch && broadcast.seq > progress.seq)
|
||||
}
|
||||
|
||||
/// Whether a broadcast's dependency is met. One that never can be counts as met rather than stalling its sender.
|
||||
fn has_delivered(&self, mark: PeerSeq) -> bool {
|
||||
if mark.peer == self.peer {
|
||||
return mark.epoch != self.epoch || mark.seq <= self.seq;
|
||||
}
|
||||
match self.delivered.get(&mark.peer) {
|
||||
Some(progress) if progress.epoch != mark.epoch => true,
|
||||
Some(progress) if progress.seq >= mark.seq => true,
|
||||
// A peer with no open link sends nothing more, including one whose hello never arrived.
|
||||
_ => !self.is_connected(mark.peer),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use futures::StreamExt;
|
||||
use futures::channel::mpsc::UnboundedSender;
|
||||
use matchbox_socket::{MessageLoopFuture, Packet, PeerState, WebRtcSocket};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll, Waker};
|
||||
|
||||
const CHANNEL: usize = 0;
|
||||
/// Largest SCTP message every browser accepts.
|
||||
const CHUNK_BYTES: usize = 16 * 1024;
|
||||
const FRAME_FINAL: u8 = 1;
|
||||
const FRAME_MORE: u8 = 0;
|
||||
|
||||
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
|
||||
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
|
||||
// An empty packet still gets one frame, since chunking it would yield none.
|
||||
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
|
||||
|
||||
chunks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, chunk)| {
|
||||
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
|
||||
std::iter::once(flag).chain(chunk.iter().copied()).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Per-peer reassembly of framed packets. The channel is ordered per peer, so a packet ends at the first [`FRAME_FINAL`].
|
||||
#[derive(Default)]
|
||||
struct Reassembler {
|
||||
partial: HashMap<TransportPeerId, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Reassembler {
|
||||
/// The packet's bytes once its final chunk lands.
|
||||
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
|
||||
let (&flag, chunk) = frame.split_first()?;
|
||||
let buffer = self.partial.entry(peer).or_default();
|
||||
buffer.extend_from_slice(chunk);
|
||||
|
||||
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
|
||||
}
|
||||
|
||||
/// Drop a peer's half-received packet, which nothing will complete.
|
||||
fn forget(&mut self, peer: TransportPeerId) {
|
||||
self.partial.remove(&peer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Packets that arrived and wait to be polled, and whoever is waiting for them.
|
||||
#[derive(Debug, Default)]
|
||||
struct Inbox {
|
||||
packets: VecDeque<(TransportPeerId, Packet)>,
|
||||
waker: Option<Waker>,
|
||||
/// Set once the socket loop ended: nothing more will arrive.
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
fn lock(inbox: &Mutex<Inbox>) -> std::sync::MutexGuard<'_, Inbox> {
|
||||
inbox.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
/// A handle onto a room's inbox that resolves when a packet is waiting, so the room is polled as packets arrive
|
||||
/// rather than once per frame, which a hidden browser tab gets only about once a second.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Incoming {
|
||||
inbox: Arc<Mutex<Inbox>>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Resolves to `true` once a packet is waiting, `false` once the room's loop has ended and nothing more can arrive.
|
||||
pub async fn wait(&self) -> bool {
|
||||
std::future::poll_fn(|cx| self.poll_ready(cx)).await
|
||||
}
|
||||
|
||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<bool> {
|
||||
let mut inbox = lock(&self.inbox);
|
||||
if !inbox.packets.is_empty() {
|
||||
return Poll::Ready(true);
|
||||
}
|
||||
if inbox.closed {
|
||||
return Poll::Ready(false);
|
||||
}
|
||||
inbox.waker = Some(cx.waker().clone());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
/// One matchbox room over WebRTC, with packets split into `[flag][bytes]` chunks and reassembled per peer.
|
||||
/// The returned future must be polled continuously by the caller.
|
||||
pub struct Room {
|
||||
socket: WebRtcSocket,
|
||||
outgoing: UnboundedSender<(TransportPeerId, Packet)>,
|
||||
inbox: Arc<Mutex<Inbox>>,
|
||||
incoming: Reassembler,
|
||||
}
|
||||
|
||||
impl Room {
|
||||
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
|
||||
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
|
||||
let (mut socket, driver) = WebRtcSocket::new_reliable(signaling_url);
|
||||
let (outgoing, mut received) = socket.take_channel(CHANNEL).expect("a reliable socket has its one channel").split();
|
||||
let inbox = Arc::new(Mutex::new(Inbox::default()));
|
||||
|
||||
// Arrivals move into the inbox and wake its waiter. The forwarder ends when the socket loop returns and
|
||||
// drops its senders; the loop's result stays the driver's.
|
||||
let forwarder = {
|
||||
let inbox = Arc::clone(&inbox);
|
||||
async move {
|
||||
while let Some(arrived) = received.next().await {
|
||||
let mut inbox = lock(&inbox);
|
||||
inbox.packets.push_back(arrived);
|
||||
if let Some(waker) = inbox.waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
let mut inbox = lock(&inbox);
|
||||
inbox.closed = true;
|
||||
if let Some(waker) = inbox.waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
};
|
||||
let driver: MessageLoopFuture = Box::pin(async move {
|
||||
let (result, ()) = futures::join!(driver, forwarder);
|
||||
result
|
||||
});
|
||||
|
||||
(
|
||||
Self {
|
||||
socket,
|
||||
outgoing,
|
||||
inbox,
|
||||
incoming: Reassembler::default(),
|
||||
},
|
||||
driver,
|
||||
)
|
||||
}
|
||||
|
||||
/// A handle that resolves whenever a packet waits in this room.
|
||||
pub fn incoming(&self) -> Incoming {
|
||||
Incoming { inbox: Arc::clone(&self.inbox) }
|
||||
}
|
||||
|
||||
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
|
||||
for frame in frames(bytes) {
|
||||
for &peer in peers {
|
||||
// Fails only once the socket loop has ended, which the loop's future reports.
|
||||
if self.outgoing.unbounded_send((peer, frame.clone())).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Room {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
self.send_chunks(&bytes, &[to]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
|
||||
self.send_chunks(&bytes, &peers);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
events.push(match state {
|
||||
PeerState::Connected => TransportEvent::PeerConnected(peer),
|
||||
PeerState::Disconnected => {
|
||||
self.incoming.forget(peer);
|
||||
TransportEvent::PeerDisconnected(peer)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let received: Vec<_> = lock(&self.inbox).packets.drain(..).collect();
|
||||
for (peer, frame) in received {
|
||||
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
|
||||
|
||||
events.push(match SyncPacket::decode(&bytes) {
|
||||
Ok(packet) => TransportEvent::Packet(peer, packet),
|
||||
Err(error) => TransportEvent::Malformed(peer, error),
|
||||
});
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::FutureExt;
|
||||
|
||||
fn peer(byte: u128) -> TransportPeerId {
|
||||
TransportPeerId(uuid::Uuid::from_u128(byte))
|
||||
}
|
||||
|
||||
/// The inbox handle resolves on an arrival and once more when the loop ends, and is pending otherwise.
|
||||
#[test]
|
||||
fn the_inbox_wakes_on_arrival_and_reports_the_end() {
|
||||
let inbox = Arc::new(Mutex::new(Inbox::default()));
|
||||
let incoming = Incoming { inbox: Arc::clone(&inbox) };
|
||||
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
|
||||
|
||||
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
|
||||
|
||||
lock(&inbox).packets.clear();
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "drained: pending again");
|
||||
|
||||
lock(&inbox).closed = true;
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(false), "the end of the loop resolves the wait for good");
|
||||
}
|
||||
|
||||
/// Push every frame at a reassembler and collect the packets that come out.
|
||||
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
|
||||
}
|
||||
|
||||
/// A packet within one chunk travels as a single final frame.
|
||||
#[test]
|
||||
fn a_small_packet_is_one_frame() {
|
||||
let bytes = b"hello".to_vec();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), 1);
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&bytes), vec![bytes]);
|
||||
}
|
||||
|
||||
/// Chunking an empty packet yields no chunks, so it needs a frame of its own or it leaves no trace on the wire.
|
||||
#[test]
|
||||
fn an_empty_packet_still_produces_one_frame() {
|
||||
let framed = frames(&[]);
|
||||
|
||||
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
|
||||
}
|
||||
|
||||
/// Either side of the SCTP limit: exactly one chunk stays one frame, one byte more splits, and both rebuild exactly.
|
||||
#[test]
|
||||
fn packets_around_the_chunk_boundary_round_trip() {
|
||||
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
|
||||
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
|
||||
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
|
||||
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
|
||||
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
|
||||
|
||||
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet is spliced into the other.
|
||||
#[test]
|
||||
fn interleaved_peers_reassemble_separately() {
|
||||
let (first, second) = (peer(1), peer(2));
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
|
||||
let short = b"short".to_vec();
|
||||
|
||||
let long_frames = frames(&long);
|
||||
let short_frames = frames(&short);
|
||||
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
|
||||
|
||||
// The short packet arrives whole between the long packet's two chunks.
|
||||
assert_eq!(incoming.accept(first, &long_frames[0]), None);
|
||||
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
|
||||
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
|
||||
}
|
||||
|
||||
/// A peer dropping mid-packet leaves a partial buffer that must not prefix the next packet under that id.
|
||||
#[test]
|
||||
fn forgetting_a_peer_discards_its_partial_packet() {
|
||||
let sender = peer(1);
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
|
||||
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
|
||||
|
||||
incoming.forget(sender);
|
||||
|
||||
let fresh = b"fresh".to_vec();
|
||||
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
|
||||
}
|
||||
|
||||
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
|
||||
#[test]
|
||||
fn an_empty_frame_is_ignored() {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
assert_eq!(incoming.accept(peer(1), &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub type TargetError = Box<dyn std::error::Error>;
|
||||
|
||||
/// The document state a `Replica` reads from and applies remote changes to.
|
||||
pub trait SyncTarget {
|
||||
fn peer(&self) -> PeerId;
|
||||
/// The session token is derived from it. See [`SessionToken::for_document`](crate::SessionToken::for_document).
|
||||
fn document_id(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
/// Take on the host's document id after a sync, so this copy is the same document.
|
||||
fn adopt_document_id(&mut self, _document_id: u64) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
fn head(&self) -> Option<Rev>;
|
||||
fn retired_registry(&self) -> Registry;
|
||||
fn hot_log(&self) -> Vec<HotOp>;
|
||||
fn known_revs(&self) -> Vec<Rev>;
|
||||
fn contains_rev(&self, rev: Rev) -> bool;
|
||||
/// What a peer holding `known` lacks. Handing it out publishes it. See [`Session::deltas_unknown_to`].
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta>;
|
||||
|
||||
/// Which hot ops are retired or taken back. See [`Session::retired_marks`].
|
||||
fn retired_marks(&self) -> RetiredMarks;
|
||||
/// Take on a peer's marks, dropping what they cover from the hot log.
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError>;
|
||||
|
||||
/// The history's users and their names, merged last-writer-wins. Empty for a target that keeps none.
|
||||
fn metadata(&self) -> HistoryMetadata {
|
||||
HistoryMetadata::default()
|
||||
}
|
||||
/// Take on a peer's metadata. Returns whether any of it was news.
|
||||
fn absorb_metadata(&mut self, _remote: &HistoryMetadata) -> Result<bool, TargetError> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Replace all state with the given retired state.
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
|
||||
/// Must be idempotent on structural ops, since the sync may already reflect a buffered op. Returns the ops
|
||||
/// whose referents have not arrived, for the caller to retry.
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
|
||||
/// Take the host's deltas on and follow to `head`, or to the batch's last delta when `None`. See [`Session::follow`].
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError>;
|
||||
/// Host only: take a peer's deltas on, joining a diverged line with a merge delta rather than following it.
|
||||
/// Returns the absorbed deltas and the merge, for the host to broadcast so every guest follows.
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError>;
|
||||
/// A peer took back hot ops of its own: drop them and re-derive what they touched.
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError>;
|
||||
/// Host only: drop a retired interaction out of the shared line. See [`Session::drop_interaction`].
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>;
|
||||
/// Host only: mint a dropped interaction again on top of the line. See [`Session::restore_interaction`].
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
|
||||
/// Host only: move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`].
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let _ = rev;
|
||||
Err("this target cannot move its head".into())
|
||||
}
|
||||
/// Follow the host's cursor move. See [`Session::apply_head_move`].
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError>;
|
||||
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll)
|
||||
/// so a target that rewrites whole files does it once per batch.
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Referenced resources whose bytes are not available locally.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
HashSet::new()
|
||||
}
|
||||
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
let _ = hash;
|
||||
None
|
||||
}
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let _ = (hash, bytes);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for Session {
|
||||
fn peer(&self) -> PeerId {
|
||||
Session::peer(self)
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
Session::retired_registry(self).clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
Session::hot_log(self).to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
Session::known_revs(self)
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta> {
|
||||
Session::deltas_unknown_to(self, known.iter().copied())
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
// A spent sequence must not come round again, or a new op of this peer's would be taken as retired.
|
||||
let spent = self.last_hot_sequence();
|
||||
*self = Session::load(self.peer(), self.user(), registry, history, head, Vec::new(), self.next_node_counter());
|
||||
self.restore_hot_sequence(spent);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// Every op gets its turn even if one fails, since its broadcast is already consumed. A failure usually
|
||||
// means a referent has not arrived, so the op is handed back to retry.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
if self.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
|
||||
self.follow(deltas, head)?;
|
||||
self.discard_hot_ops(retires);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
|
||||
let mut absorbed: Vec<Delta> = deltas.iter().filter(|delta| !self.contains_rev(delta.id)).cloned().collect();
|
||||
let outcome = self.merge(deltas)?;
|
||||
self.discard_hot_ops(retires);
|
||||
if let document_graph_storage::MergeOutcome::Merged(rev) = outcome {
|
||||
absorbed.extend(self.delta(rev).cloned());
|
||||
}
|
||||
Ok(absorbed)
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
Session::retired_marks(self).clone()
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
Session::absorb_retired_marks(self, remote);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
|
||||
Session::retract_hot_ops(self, ops);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, _) = Session::drop_interaction(self, rev)?;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
|
||||
let revs = Session::restore_interaction(self, rev)?;
|
||||
Ok(revs.into_iter().filter_map(|rev| self.delta(rev).cloned()).collect())
|
||||
}
|
||||
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
|
||||
Session::apply_head_move(self, moved)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
Ok(Session::move_head_to(self, rev)?.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
|
||||
const PREFIX: &str = "graphite-";
|
||||
|
||||
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SessionToken(pub [u8; 16]);
|
||||
|
||||
impl SessionToken {
|
||||
pub fn signaling_url(&self, signaling_server: &str) -> String {
|
||||
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionToken {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid session token")]
|
||||
pub struct InvalidSessionToken;
|
||||
|
||||
impl FromStr for SessionToken {
|
||||
type Err = InvalidSessionToken;
|
||||
|
||||
/// Parses the bare token or a share link carrying it as the `session` query parameter, so a pasted link works
|
||||
/// wherever a token does.
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.trim();
|
||||
let s = match s.split_once("session=") {
|
||||
Some((_, rest)) => rest.split(['&', '#', ' ']).next().unwrap_or(""),
|
||||
None => s,
|
||||
};
|
||||
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
|
||||
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_string() {
|
||||
let token = SessionToken([7; 16]);
|
||||
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_the_token_out_of_a_share_link() {
|
||||
let token = SessionToken([7; 16]);
|
||||
let link = format!(" https://editor.graphite.rs/?session={token}#top ");
|
||||
assert_eq!(link.parse::<SessionToken>().unwrap(), token);
|
||||
assert_eq!(format!("http://localhost:8080/?debug=1&session={token}").parse::<SessionToken>().unwrap(), token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_length_or_missing_prefix() {
|
||||
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
|
||||
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionToken {
|
||||
/// The token every copy of a document shares, so a copy edited apart reconnects by opening the file. Document
|
||||
/// ids are random, so the room is as unguessable as the id; the mixing only spreads it over the token's width.
|
||||
pub fn for_document(document_id: u64) -> Self {
|
||||
fn mix(mut value: u64) -> u64 {
|
||||
value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..8].copy_from_slice(&mix(document_id).to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&mix(document_id ^ 0x5A5A_5A5A_5A5A_5A5A).to_le_bytes());
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod derived_token_tests {
|
||||
use super::SessionToken;
|
||||
|
||||
#[test]
|
||||
fn a_document_id_derives_one_token() {
|
||||
assert_eq!(SessionToken::for_document(7), SessionToken::for_document(7));
|
||||
assert_ne!(SessionToken::for_document(7), SessionToken::for_document(8));
|
||||
let text = SessionToken::for_document(7).to_string();
|
||||
assert_eq!(text.parse::<SessionToken>().expect("round trip"), SessionToken::for_document(7));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
|
||||
pub use matchbox_socket::PeerId as TransportPeerId;
|
||||
|
||||
pub enum TransportEvent {
|
||||
PeerConnected(TransportPeerId),
|
||||
PeerDisconnected(TransportPeerId),
|
||||
Packet(TransportPeerId, SyncPacket),
|
||||
Malformed(TransportPeerId, PacketError),
|
||||
}
|
||||
|
||||
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
|
||||
/// sender, which is what lets the `Replica` skip acknowledgement and retransmission.
|
||||
pub trait Transport: Send + Sync {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn poll(&mut self) -> Vec<TransportEvent>;
|
||||
fn close(&mut self);
|
||||
|
||||
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
self.broadcast_except(None, packet)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,6 +25,7 @@ graph-craft = { workspace = true }
|
||||
document-format = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
|
||||
+47
-10
@@ -2,14 +2,15 @@ use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use crate::task::{Scheduling, Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphene_std::runtime::Clock;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type ReadyEditorBuilder = EditorBuilder<Wake, Environment, Arc<dyn ResourceStorage>, Arc<dyn DocumentStore>>;
|
||||
pub type ReadyRuntimeBuilder = RuntimeBuilder<Wake, PlatformApplicationIo>;
|
||||
pub type ReadyRuntimeBuilder = RuntimeBuilder<Wake, PlatformApplicationIo, Arc<dyn Clock>>;
|
||||
|
||||
pub struct Builder<E = (), R = (), S = (), N = ()> {
|
||||
editor: E,
|
||||
@@ -96,6 +97,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
@@ -107,7 +110,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
@@ -181,14 +185,21 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
pub struct RuntimeBuilder<W = (), A = (), C = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
clock: C,
|
||||
scheduling: Scheduling,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self { wake: (), application_io: () }
|
||||
Self {
|
||||
wake: (),
|
||||
application_io: (),
|
||||
clock: (),
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,18 +209,44 @@ impl Default for RuntimeBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A> RuntimeBuilder<(), A> {
|
||||
impl<A, C> RuntimeBuilder<(), A, C> {
|
||||
/// Called from any thread when a graph task has completed, to run the runtime again as soon as possible.
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder<Wake, A> {
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder<Wake, A, C> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
impl<W, C> RuntimeBuilder<W, (), C> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo, C> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A> RuntimeBuilder<W, A, ()> {
|
||||
/// The host's clock, which frames and the nodes' own budgets are measured with.
|
||||
pub fn with_clock(self, clock: Arc<dyn Clock>) -> RuntimeBuilder<W, A, Arc<dyn Clock>> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io: self.application_io,
|
||||
clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A, C> RuntimeBuilder<W, A, C> {
|
||||
/// How the runtime schedules the evaluations finished tasks ask for, by default within a 16 ms frame budget.
|
||||
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
|
||||
Self { scheduling, ..self }
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub const VIEWPORT_SCROLL_RATE: f64 = 0.6;
|
||||
|
||||
pub const VIEWPORT_ROTATE_SNAP_INTERVAL: f64 = 15.;
|
||||
|
||||
pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.95;
|
||||
pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.999;
|
||||
|
||||
pub const DRAG_BEYOND_VIEWPORT_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
|
||||
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
|
||||
|
||||
@@ -290,6 +290,7 @@ impl Dispatcher {
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
current_tool_icon: self.message_handlers.tool_message_handler.active_tool_icon(),
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -304,6 +305,8 @@ impl Dispatcher {
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
|
||||
@@ -16,4 +16,5 @@ pub enum AppWindowMessage {
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
@@ -63,6 +63,19 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowRestart);
|
||||
}
|
||||
AppWindowMessage::TmpToggleHideUI => {
|
||||
responses.add(FrontendMessage::TmpToggleHideUI);
|
||||
responses.add(WorkspaceMessage::ToggleFocusDocument);
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DeferMessage::AfterGraphRun {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
}
|
||||
.into(),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
advertise_actions!(AppWindowMessageDiscriminant;
|
||||
@@ -73,6 +86,7 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
Drag,
|
||||
Hide,
|
||||
HideOthers,
|
||||
TmpToggleHideUI,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -140,6 +140,10 @@ pub enum FrontendMessage {
|
||||
url: String,
|
||||
},
|
||||
TriggerClipboardRead,
|
||||
/// Copy a link to join the live session behind `token`, built from the page's own origin.
|
||||
TriggerSessionLinkCopy {
|
||||
token: String,
|
||||
},
|
||||
TriggerClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
@@ -190,6 +194,15 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "box")]
|
||||
box_selection: Option<BoxSelection>,
|
||||
},
|
||||
UpdateDocumentCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateContextMenuInformation {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
@@ -382,4 +395,6 @@ pub enum FrontendMessage {
|
||||
WindowShowAll,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowRestart,
|
||||
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
@@ -12,6 +12,18 @@ pub struct DocumentInfo {
|
||||
#[serde(default)]
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
/// The document's live session, `None` when it is not shared.
|
||||
#[serde(default)]
|
||||
pub session: Option<SessionStatus>,
|
||||
}
|
||||
|
||||
/// Whether a shared document is in its room right now.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SessionStatus {
|
||||
Connected,
|
||||
/// Shared, but the transport is down or the document is not mounted yet; it reconnects on mount.
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
|
||||
@@ -59,6 +59,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyDown(F11); disabled=is_mac, action_dispatch=AppWindowMessage::Fullscreen),
|
||||
entry!(KeyDown(KeyF); modifiers=[Command, Control], disabled=!is_mac, action_dispatch=AppWindowMessage::Fullscreen),
|
||||
entry!(KeyDown(KeyQ); modifiers=[Command], disabled=cfg!(not(target_os = "macos")), action_dispatch=AppWindowMessage::Close),
|
||||
entry!(KeyDown(F11); modifiers=[Alt], action_dispatch=AppWindowMessage::TmpToggleHideUI),
|
||||
//
|
||||
// ClipboardMessage
|
||||
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=ClipboardMessage::Cut),
|
||||
|
||||
@@ -5,13 +5,45 @@ use crate::messages::prelude::*;
|
||||
#[impl_message(Message, InputPreprocessor)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InputPreprocessorMessage {
|
||||
DoubleClick { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
PointerDown { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerMove { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerUp { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerShake { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
CurrentTime { timestamp: u64 },
|
||||
WheelScroll { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
DoubleClick {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
KeyDown {
|
||||
key: Key,
|
||||
key_repeat: bool,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
KeyUp {
|
||||
key: Key,
|
||||
key_repeat: bool,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
PointerDown {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
PointerMove {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
/// The pointer moved over GUI covering the canvas, such as the node graph: only the position is recorded, for presence.
|
||||
PointerHover {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
},
|
||||
PointerUp {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
PointerShake {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
CurrentTime {
|
||||
timestamp: u64,
|
||||
},
|
||||
WheelScroll {
|
||||
editor_mouse_state: EditorPointerState,
|
||||
modifier_keys: ModifierKeys,
|
||||
},
|
||||
}
|
||||
@@ -109,6 +109,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
|
||||
self.translate_mouse_event(pointer_state, true, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerHover { editor_mouse_state } => {
|
||||
self.mouse.position = editor_mouse_state.to_pointer_state(viewport).position;
|
||||
}
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
|
||||
@@ -72,6 +72,8 @@ define_layout_target!(
|
||||
NodeGraphControlBar,
|
||||
/// The body of the Inspector containing many collapsable sections.
|
||||
Inspector,
|
||||
/// The body of the Session panel: the active document's live session state, join link, peers and sharing actions.
|
||||
SessionPanel,
|
||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||
StatusBarHints,
|
||||
/// The version information shown in the status bar at the bottom right of the window.
|
||||
|
||||
@@ -24,6 +24,8 @@ pub struct MenuBarMessageHandler {
|
||||
pub show_storage_preferences: bool,
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub session_panel_open: bool,
|
||||
pub history_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
pub focus_document: bool,
|
||||
@@ -687,6 +689,16 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Session")
|
||||
.label("Session")
|
||||
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("History")
|
||||
.label("History")
|
||||
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::{Declarations, Registry, Value};
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
|
||||
@@ -35,6 +35,20 @@ pub struct DocumentHistory {
|
||||
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
|
||||
/// part of the distance between the two.
|
||||
needs_whole_document_stage: bool,
|
||||
/// For each step on the legacy redo stack, how storage undid it, so redo takes the matching way back rather than
|
||||
/// diffing a snapshot that predates what peers wrote since.
|
||||
retracted_undos: Vec<UndoNote>,
|
||||
}
|
||||
|
||||
/// How storage undid a step, paired with the legacy redo entry pushed for it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum UndoNote {
|
||||
/// The step was still hot and its ops were taken back; redo stages them again.
|
||||
Retracted(Vec<document_graph_storage::RegistryDelta>),
|
||||
/// The step had retired in a session and was dropped out of the shared line; redo puts it back on top.
|
||||
Dropped(document_graph_storage::Rev),
|
||||
/// The storage cursor moved back over it; redo moves it forward.
|
||||
Cursor,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
@@ -77,6 +91,7 @@ impl DocumentHistory {
|
||||
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
|
||||
pub fn clear_redo(&mut self) {
|
||||
self.legacy_redo_stack.clear();
|
||||
self.retracted_undos.clear();
|
||||
}
|
||||
|
||||
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
|
||||
@@ -99,6 +114,11 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
/// The decoded proto-node declarations the working copy's registry states reference.
|
||||
pub fn declarations(&self) -> &Declarations {
|
||||
&self.declarations
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
|
||||
@@ -118,9 +138,123 @@ impl DocumentHistory {
|
||||
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.
|
||||
/// Close the open storage interaction at an undo-step boundary, so the staging since the last boundary is one unit
|
||||
/// for retirement and undo, aligned with the legacy step. No-op while unmounted.
|
||||
pub fn end_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.end_interaction() {
|
||||
log::error!("Closing the storage interaction failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo the latest storage interaction while it is still hot by taking it back, so it never becomes a history step.
|
||||
/// `None` when the step already retired or nothing is mounted.
|
||||
pub fn retract_storage_interaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
|
||||
let storage = self.storage.as_mut()?;
|
||||
match storage.retract_interaction() {
|
||||
Ok(retracted) => retracted,
|
||||
Err(error) => {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Redo a step taken back by staging its ops as a fresh interaction. What they name lands in the remote changes.
|
||||
pub fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.restage_ops(ops) {
|
||||
log::error!("Staging the redone step failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether there is a legacy undo step to pop, and so a step storage may take back.
|
||||
pub fn has_undo_step(&self) -> bool {
|
||||
!self.legacy_undo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Whether there is a legacy redo step to pop.
|
||||
pub fn has_redo_step(&self) -> bool {
|
||||
!self.legacy_redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// The resource bytes the steps taken back still name. Nothing in the registry or history refers to them,
|
||||
/// so garbage collection must keep them for a redo.
|
||||
pub fn retracted_resource_hashes(&self) -> impl Iterator<Item = graph_craft::application_io::resource::ResourceHash> + '_ {
|
||||
self.retracted_undos
|
||||
.iter()
|
||||
.filter_map(|note| match note {
|
||||
UndoNote::Retracted(ops) => Some(ops),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.filter_map(|op| match op {
|
||||
document_graph_storage::RegistryDelta::AddResource { entry, .. } => entry.hash,
|
||||
document_graph_storage::RegistryDelta::SetResourceHash { hash, .. } => *hash,
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the next redo step was taken back or dropped rather than cursor-undone, checked before the legacy stacks move.
|
||||
pub fn next_redo_is_storage_driven(&self) -> bool {
|
||||
!matches!(self.retracted_undos.last(), None | Some(UndoNote::Cursor))
|
||||
}
|
||||
|
||||
/// Record how the step just undone reached storage, paired with the legacy redo entry pushed for it.
|
||||
pub fn note_undo(&mut self, note: UndoNote) {
|
||||
self.retracted_undos.push(note);
|
||||
}
|
||||
|
||||
/// How the step about to be redone was undone, cursor-undone when nothing was noted.
|
||||
pub fn take_undo_note(&mut self) -> UndoNote {
|
||||
self.retracted_undos.pop().unwrap_or(UndoNote::Cursor)
|
||||
}
|
||||
|
||||
/// Undo this peer's latest retired step in a session; see [`document_format::Gdd::undo_retired_step`].
|
||||
pub fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
|
||||
let storage = self.storage.as_mut()?;
|
||||
match storage.undo_retired_step() {
|
||||
Ok(rev) => rev,
|
||||
Err(error) => {
|
||||
log::error!("Undoing the retired step failed: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Redo a step dropped out of a session's line.
|
||||
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.redo_retired_step(rev) {
|
||||
log::error!("Redoing the dropped step failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop any retired interaction out of the line; see [`document_format::Gdd::drop_step`].
|
||||
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.drop_step(rev) {
|
||||
log::error!("Removing the step failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the shared head to an ancestor; see [`document_format::Gdd::move_head`].
|
||||
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.move_head(rev) {
|
||||
log::error!("Moving the head failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the legacy snapshots: after a move made from the History panel they describe states off the line the
|
||||
/// head is on, so Ctrl+Z resumes from the next edit and the panel is the way back meanwhile.
|
||||
pub fn clear_legacy(&mut self) {
|
||||
self.legacy_undo_stack.clear();
|
||||
self.legacy_redo_stack.clear();
|
||||
self.retracted_undos.clear();
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one into durable Gdd history. No-op while unmounted.
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.retire_pending_interaction() {
|
||||
@@ -130,11 +264,21 @@ impl DocumentHistory {
|
||||
|
||||
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
|
||||
/// 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.
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
|
||||
/// interaction by [`end_storage_interaction`](Self::end_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) {
|
||||
if !self.stage_graph(deltas, interface, registry, byte_store) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// The graph half of [`stage_snapshot`](Self::stage_snapshot), without the view state. A session stages every frame,
|
||||
/// so peers see each movement of a drag; retirement coarsens them later. Returns whether the working copy took the batch.
|
||||
pub fn stage_graph(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> bool {
|
||||
let needs_whole_document_stage = self.needs_whole_document_stage;
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
|
||||
let staged = match needs_whole_document_stage {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
@@ -152,14 +296,13 @@ impl DocumentHistory {
|
||||
Ok(declarations) => {
|
||||
self.declarations.extend(declarations);
|
||||
self.needs_whole_document_stage = false;
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
@@ -239,15 +382,64 @@ impl DocumentHistory {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
|
||||
storage
|
||||
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
|
||||
}
|
||||
|
||||
/// Build a fresh interface from the working registry, using the declaration cache so no resource load
|
||||
/// is needed. `None` when the registry does not convert.
|
||||
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
let rebuilt = storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
|
||||
.map_err(|error| {
|
||||
log::error!("Storage undo/redo rebuild failed: {error}");
|
||||
CursorMoveError::RebuildFailed
|
||||
})
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()));
|
||||
|
||||
match rebuilt {
|
||||
Ok(interface) => Some(interface),
|
||||
Err(error) => {
|
||||
log::error!("Storage interface rebuild failed: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The hashes of declaration resources the working copy names but holds no decoded declaration for.
|
||||
/// A remote change can name a declaration whose bytes the byte store already holds, so no peer is asked for them.
|
||||
pub fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
|
||||
let Some(storage) = self.storage.as_ref() else { return Vec::new() };
|
||||
|
||||
let mut hashes: Vec<ResourceHash> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, hash)| (!self.declarations.contains_key(&id)).then_some(hash?))
|
||||
.collect();
|
||||
hashes.sort_unstable();
|
||||
hashes.dedup();
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Cache a resource that arrived from a peer as a proto-node declaration, under every declaration
|
||||
/// resource referencing its hash. Ignores resources no declaration refers to, such as images and fonts.
|
||||
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) {
|
||||
let Some(storage) = self.storage.as_ref() else { return };
|
||||
|
||||
let referencing: Vec<ResourceId> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
|
||||
.collect();
|
||||
if referencing.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
match document_graph_storage::decode_declaration(bytes) {
|
||||
Ok(declaration) => self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone()))),
|
||||
Err(error) => log::error!("Failed to deserialize a received ProtoNode declaration: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
|
||||
@@ -56,6 +56,18 @@ pub enum DocumentMessage {
|
||||
DeselectAllLayers,
|
||||
DocumentHistoryBackward,
|
||||
DocumentHistoryForward,
|
||||
/// From the History panel: move the shared head to an earlier interaction, the steps since staying as a branch.
|
||||
HistoryMoveHead {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
/// From the History panel: drop one retired interaction out of the line, the later ones minted again on its parent.
|
||||
HistoryRemoveStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
/// From the History panel: mint a dropped or abandoned interaction again on top of the line.
|
||||
HistoryRestoreStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
DocumentStructureChanged,
|
||||
DrawArtboardOverlays {
|
||||
context: OverlayContext,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::document_diff::diff_networks;
|
||||
use super::document_history::UndoNote;
|
||||
use super::node_graph::{document_node_definitions, node_inspector};
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType, SNAPPING_OPTION_GROUPS, SnappingState};
|
||||
@@ -21,7 +22,7 @@ use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
@@ -34,8 +35,11 @@ use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_container::AnyContainer;
|
||||
use document_graph_storage::Declarations;
|
||||
|
||||
/// The document attribute holding the document's name, so a session shares it and a rename reaches every peer.
|
||||
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceStorage};
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
@@ -172,6 +176,10 @@ pub struct DocumentMessageHandler {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore")]
|
||||
pub(crate) container: Option<AnyContainer>,
|
||||
/// What peers changed in the working registry that the interface does not show yet, applied once every declaration it
|
||||
/// needs is cached. Local edits are constructed against the registry, not diffed from the interface, so none reverts these.
|
||||
#[serde(skip)]
|
||||
pub(crate) pending_remote: document_format::network::RemoteChanges,
|
||||
/// Hash of the document snapshot that was most recently saved to disk by the user.
|
||||
#[serde(skip)]
|
||||
saved_hash: Option<u64>,
|
||||
@@ -232,6 +240,7 @@ impl Default for DocumentMessageHandler {
|
||||
selection_network_path: Vec::new(),
|
||||
history: DocumentHistory::default(),
|
||||
container: None,
|
||||
pending_remote: Default::default(),
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
@@ -457,6 +466,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
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::HistoryMoveHead { rev } => self.apply_history_action(|history| history.move_head_to(rev), responses),
|
||||
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(|history| history.drop_step(rev), responses),
|
||||
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(|history| history.redo_retired_step(rev), responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -1125,6 +1137,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.path = None;
|
||||
self.set_save_state(false);
|
||||
self.set_auto_save_state(false);
|
||||
self.stage_name_attribute();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
|
||||
@@ -1610,7 +1623,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
|
||||
DocumentMessage::StartTransaction => {
|
||||
self.retire_storage_interaction();
|
||||
self.end_storage_interaction();
|
||||
|
||||
self.network_interface.start_transaction();
|
||||
self.history.push_undo(self.network_interface.clone());
|
||||
@@ -2044,7 +2057,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: false });
|
||||
} else {
|
||||
warn!("Cannot zoom due to no bounds")
|
||||
}
|
||||
@@ -2125,7 +2138,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Build a document handler from a `.gdd` working copy.
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn from_storage(
|
||||
interface: NodeNetworkInterface,
|
||||
storage: document_format::GddV1,
|
||||
declarations: Declarations,
|
||||
byte_store: Arc<dyn ResourceStorage>,
|
||||
name: String,
|
||||
path: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
@@ -2134,11 +2154,7 @@ impl DocumentMessageHandler {
|
||||
};
|
||||
|
||||
document.apply_stored_document_settings(storage.view_settings());
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.history.set_storage(storage, declarations);
|
||||
document.set_storage(storage, declarations, byte_store);
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2325,6 +2341,53 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Path to the subnetwork that the user's selection is currently scoped to.
|
||||
/// Empty when the selection lives in the root document network.
|
||||
/// The network the node graph shows, from the document network down.
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
|
||||
/// Write the document's name into its registry as [`DOCUMENT_NAME_ATTRIBUTE`]. No-op without a working copy or when the
|
||||
/// registry already holds this name.
|
||||
pub fn stage_name_attribute(&mut self) {
|
||||
let name = self.name.clone();
|
||||
let Some(gdd) = self.storage_mut() else { return };
|
||||
if gdd
|
||||
.registry()
|
||||
.attributes
|
||||
.get(DOCUMENT_NAME_ATTRIBUTE)
|
||||
.is_some_and(|value| !value.deleted && matches!(&value.value, document_graph_storage::Value::Str(held) if *held == name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let delta = document_graph_storage::AttributeDelta {
|
||||
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
|
||||
value: Some(document_graph_storage::Value::Str(name)),
|
||||
};
|
||||
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
|
||||
log::error!("Staging the document name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the name the registry holds, after peers changed it. Returns whether the name changed.
|
||||
pub fn adopt_name_from_storage(&mut self) -> bool {
|
||||
let Some(name) = self
|
||||
.storage()
|
||||
.and_then(|gdd| gdd.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE))
|
||||
.filter(|value| !value.deleted)
|
||||
.and_then(|value| match &value.value {
|
||||
document_graph_storage::Value::Str(name) => Some(name.clone()),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if name == self.name {
|
||||
return false;
|
||||
}
|
||||
self.name = name;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn selection_network_path(&self) -> &[NodeId] {
|
||||
&self.selection_network_path
|
||||
}
|
||||
@@ -2340,8 +2403,15 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
|
||||
storage.set_byte_store(byte_store);
|
||||
self.history.set_storage(storage, declarations);
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
/// Close the open storage interaction at an undo-step boundary.
|
||||
pub(crate) fn end_storage_interaction(&mut self) {
|
||||
self.history.end_storage_interaction();
|
||||
}
|
||||
|
||||
/// Detach the `Gdd` working copy.
|
||||
@@ -2374,7 +2444,8 @@ impl DocumentMessageHandler {
|
||||
let view_settings = self.storage_view_settings();
|
||||
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
|
||||
|
||||
if validate {
|
||||
// The interface lags the registry by what peers changed, so the two only agree once that is applied.
|
||||
if validate && self.pending_remote.is_empty() {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
@@ -2441,6 +2512,101 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the runtime resource registry in line with storage. The preprocessor resolves `Resource` inputs through it, so an
|
||||
/// interface swapped in from storage needs it refreshed alongside. Storage wins where both have an entry, and entries
|
||||
/// not yet staged, like those a legacy document's migration added, are kept. Keeps the current registry on failure.
|
||||
fn refresh_resource_registry(&mut self) {
|
||||
let Some(storage) = self.history.storage() else { return };
|
||||
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => self.resources.registry.overlay(resource_registry),
|
||||
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stages what the interface recorded since the last drain, so a session sends each movement in the frame it was made
|
||||
/// rather than at the next commit. Nothing else a commit does is done here.
|
||||
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
|
||||
}
|
||||
|
||||
/// Brings the interface into line with what peers changed in the registry. Returns whether nothing is
|
||||
/// left pending: a declaration still on its way keeps the changes for a later call.
|
||||
///
|
||||
/// The touched entities are reconciled in place; only a registry rederived wholesale or a failed reconcile rebuilds it all.
|
||||
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
|
||||
let changes = std::mem::take(&mut self.pending_remote);
|
||||
if changes.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if !changes.rebuilt
|
||||
&& let Some(gdd) = self.history.storage()
|
||||
{
|
||||
let peer = gdd.session().peer();
|
||||
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
|
||||
Ok(reconciled) => {
|
||||
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
|
||||
return true;
|
||||
}
|
||||
Err(ReconcileError::DeclarationMissing(id)) => {
|
||||
log::debug!("Remote changes wait for declaration {id}");
|
||||
self.pending_remote = changes;
|
||||
return false;
|
||||
}
|
||||
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(rebuilt) = self.history.rebuild_interface() {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// What a rebuild does for the whole interface, for the networks a reconcile changed: drops what the
|
||||
/// changed nodes feed and re-derives the layer structure.
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
|
||||
for path in &reconciled.networks {
|
||||
if self.network_interface.document_network().nested_network(path).is_none() {
|
||||
continue;
|
||||
}
|
||||
self.network_interface.unload_stack_dependents(path);
|
||||
self.network_interface.unload_import_export_ports(path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(path);
|
||||
self.network_interface.unload_outward_wires(path);
|
||||
self.network_interface.unload_all_nodes_click_targets(path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
if resources_changed {
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
|
||||
pub(crate) fn cache_declaration_bytes(&mut self, hash: graph_craft::application_io::resource::ResourceHash, bytes: &[u8]) {
|
||||
self.history.cache_declaration_bytes(hash, bytes);
|
||||
}
|
||||
|
||||
/// Declaration resources the working copy names whose bytes are on hand but not yet decoded.
|
||||
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<graph_craft::application_io::resource::ResourceHash> {
|
||||
self.history.undecoded_declaration_hashes()
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
@@ -2452,6 +2618,11 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
self.pending_remote = Default::default();
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
self.refresh_resource_registry();
|
||||
|
||||
if validate {
|
||||
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
|
||||
@@ -2761,16 +2932,78 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
// A hot step is taken back and never becomes history. Its legacy snapshot predates what peers wrote since, so the
|
||||
// interface follows the registry on just the entities the step named instead. Only a retired step moves the cursor.
|
||||
if self.history.has_undo_step()
|
||||
&& let Some(ops) = self.history.retract_storage_interaction()
|
||||
{
|
||||
if let Some(snapshot) = self.history.pop_undo() {
|
||||
self.history.push_redo(snapshot);
|
||||
}
|
||||
self.history.note_undo(UndoNote::Retracted(ops));
|
||||
self.follow_storage_changes(responses);
|
||||
return;
|
||||
}
|
||||
// In a session a retired step is public: it is dropped out of the shared line, by the retirer or on
|
||||
// request, and the room follows the head. Nothing else in a session may install a legacy snapshot.
|
||||
if self.is_in_session() {
|
||||
if self.history.has_undo_step()
|
||||
&& let Some(rev) = self.history.undo_retired_step()
|
||||
{
|
||||
if let Some(snapshot) = self.history.pop_undo() {
|
||||
self.history.push_redo(snapshot);
|
||||
}
|
||||
self.history.note_undo(UndoNote::Dropped(rev));
|
||||
self.follow_storage_changes(responses);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if legacy_applied {
|
||||
self.history.note_undo(UndoNote::Cursor);
|
||||
}
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// An action from the History panel: storage performs it, the interface follows on the entities it named, and the
|
||||
/// legacy snapshots go since they describe states off the head's line.
|
||||
fn apply_history_action(&mut self, action: impl FnOnce(&mut super::document_history::DocumentHistory), responses: &mut VecDeque<Message>) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.history.retire_storage_interaction();
|
||||
action(&mut self.history);
|
||||
self.history.clear_legacy();
|
||||
self.follow_storage_changes(responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
|
||||
/// Bring the interface into line with what storage just changed under it by reconciling the entities those ops named,
|
||||
/// as for remote changes. Anything a peer wrote meanwhile stays as the interface holds it.
|
||||
fn follow_storage_changes(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
let changes = gdd.take_remote_changes();
|
||||
self.pending_remote.extend(changes);
|
||||
}
|
||||
self.apply_remote_changes(responses);
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
}
|
||||
|
||||
fn is_in_session(&self) -> bool {
|
||||
self.storage().is_some_and(|gdd| gdd.role().is_some())
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
|
||||
// Set the previous network navigation metadata to the current navigation metadata
|
||||
@@ -2803,13 +3036,32 @@ impl DocumentMessageHandler {
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
// A step taken back is gone from every hot log, so its redo stages the ops afresh as a new edit, followed as for the undo.
|
||||
if self.history.has_redo_step() && self.history.next_redo_is_storage_driven() {
|
||||
if let Some(snapshot) = self.history.pop_redo() {
|
||||
self.history.push_undo(snapshot);
|
||||
}
|
||||
match self.history.take_undo_note() {
|
||||
UndoNote::Retracted(ops) => self.history.restage_ops(ops),
|
||||
UndoNote::Dropped(rev) => self.history.redo_retired_step(rev),
|
||||
UndoNote::Cursor => {}
|
||||
}
|
||||
self.follow_storage_changes(responses);
|
||||
return;
|
||||
}
|
||||
if self.is_in_session() {
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if legacy_applied {
|
||||
self.history.take_undo_note();
|
||||
}
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
|
||||
}
|
||||
|
||||
@@ -4021,6 +4273,11 @@ impl DocumentMessageHandler {
|
||||
self.resources.collect_garbage(&used_resources);
|
||||
}
|
||||
|
||||
/// Resource bytes only a step taken back on undo still names; see [`DocumentHistory::retracted_resource_hashes`].
|
||||
pub fn retracted_resource_hashes(&self) -> impl Iterator<Item = graph_craft::application_io::resource::ResourceHash> + '_ {
|
||||
self.history.retracted_resource_hashes()
|
||||
}
|
||||
|
||||
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
|
||||
let mut resources = HashSet::new();
|
||||
self.network_interface.collect_used_resources(&mut resources);
|
||||
|
||||
@@ -224,3 +224,17 @@ pub enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Another peer's pointer over the node graph, in viewport pixels, with how to label it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendRemoteCursor {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub name: String,
|
||||
/// A stand-in name for someone who gave none, shown in italics.
|
||||
pub anonymous: bool,
|
||||
pub color: String,
|
||||
/// The icon name of the tool the peer holds, if it told.
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
@@ -46,7 +46,10 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
style: Some(style_name),
|
||||
},
|
||||
);
|
||||
responses.add(ResourceMessage::Resolve { resource_id });
|
||||
responses.add(PortfolioMessage::DocumentPassMessage {
|
||||
document_id,
|
||||
message: ResourceMessage::Resolve { resource_id }.into(),
|
||||
});
|
||||
}
|
||||
ResourceMessage::ResolveAll => {
|
||||
let storage = resource_storage.resources_mut();
|
||||
@@ -55,7 +58,11 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
if self.pending_resolves.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
responses.add(ResourceMessage::Resolve { resource_id: id });
|
||||
// Addressed to this document, since a bare message would reach whichever document is active
|
||||
responses.add(PortfolioMessage::DocumentPassMessage {
|
||||
document_id,
|
||||
message: ResourceMessage::Resolve { resource_id: id }.into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ResourceMessage::Resolve { resource_id } => {
|
||||
@@ -337,7 +344,12 @@ mod tests {
|
||||
},
|
||||
);
|
||||
|
||||
let resolve_requested = |id: ResourceId| responses.contains(&Message::from(ResourceMessage::Resolve { resource_id: id }));
|
||||
let resolve_requested = |id: ResourceId| {
|
||||
responses.contains(&Message::from(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: DocumentId(0),
|
||||
message: ResourceMessage::Resolve { resource_id: id }.into(),
|
||||
}))
|
||||
};
|
||||
assert!(resolve_requested(evicted), "a resource whose bytes are gone should be resolved again");
|
||||
assert!(!resolve_requested(cached), "a resource whose bytes are in storage should be left alone");
|
||||
assert_eq!(handler.registry.hash(&evicted), Some(evicted_hash), "the hash keeps naming the content");
|
||||
|
||||
@@ -100,19 +100,20 @@ async fn legacy_only_container_gets_storage() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_mode_reads_legacy_only_and_leaves_storage_files_alone() {
|
||||
async fn legacy_save_format_still_keeps_a_working_copy() {
|
||||
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();
|
||||
assert!(editor.active_document().storage().is_some(), "every document gets a working copy, whatever the save format");
|
||||
assert!(container.exists("manifest.json").await);
|
||||
|
||||
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");
|
||||
let saved = dispatch(&mut editor, DocumentMessage::SaveDocumentAs);
|
||||
let name = saved.iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveDocument { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(name.as_deref(), Some("Legacy.graphite"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -154,6 +155,8 @@ async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
|
||||
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 });
|
||||
// Retire as the frame tick would: a hot step is taken back on undo and never enters history, leaving no cursor to keep.
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().document_network(), &network_before);
|
||||
@@ -182,20 +185,17 @@ async fn closing_removes_the_stored_document() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn storage_preference_attaches_and_drops_sessions() {
|
||||
async fn storage_preference_keeps_the_working_copy() {
|
||||
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!(editor.active_document().storage().is_some());
|
||||
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());
|
||||
for enabled in [false, true] {
|
||||
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled });
|
||||
assert!(editor.active_document().storage().is_some(), "the preference only picks the save format");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
|
||||
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
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, UserId, to_value};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
@@ -156,9 +158,9 @@ async fn edit_after_open_commits_cleanly() {
|
||||
|
||||
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
|
||||
// reopened registry: the editor's .gdd-open path.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let byte_store = ResourcesHandle::new(Arc::new(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), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let source_network = source.network_interface.document_network().clone();
|
||||
let source_view = StorageMetadataView::new(&source.network_interface);
|
||||
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
|
||||
@@ -174,7 +176,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(reopened, declarations);
|
||||
document.set_storage(reopened, declarations, byte_store.storage());
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
@@ -208,7 +210,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
#[tokio::test]
|
||||
async fn gdd_undo_redo_walks_interactions() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
// Commit the active document's current runtime state as one interaction.
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
@@ -259,7 +261,7 @@ async fn gdd_undo_redo_walks_interactions() {
|
||||
#[tokio::test]
|
||||
async fn reopen_after_undo_restores_consistent_registry() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
@@ -381,7 +383,7 @@ 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), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
|
||||
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
|
||||
@@ -429,7 +431,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
|
||||
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
|
||||
|
||||
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let document = editor.active_document();
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
@@ -662,10 +664,31 @@ 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");
|
||||
editor.active_document_mut().set_storage(gdd, Default::default());
|
||||
HashMapResourceStorage::new()
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
|
||||
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
|
||||
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
|
||||
byte_store
|
||||
}
|
||||
|
||||
/// A legacy document's migration adds registry entries before its working copy exists. Mounting a fresh, empty copy
|
||||
/// keeps them, so their pending resolves still find them.
|
||||
#[tokio::test]
|
||||
async fn mounting_fresh_storage_keeps_unstaged_resources() {
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceId};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let font = ResourceId::from(42);
|
||||
let source = DataSource::Font {
|
||||
family: "Source Sans Pro".into(),
|
||||
style: Some("Regular (400)".into()),
|
||||
};
|
||||
editor.active_document_mut().resources.registry.push_source_back(&font, source.clone());
|
||||
|
||||
mount_in_memory_storage(&mut editor);
|
||||
let registry = &editor.active_document().resources.registry;
|
||||
assert_eq!(registry.info(&font).map(|info| info.sources.to_vec()), Some(vec![source]), "the migrated font survives the mount");
|
||||
}
|
||||
|
||||
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
|
||||
@@ -699,8 +722,9 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
|
||||
|
||||
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
|
||||
// Second autosave verifies the round-trip again; retirement follows a policy, not the commit, so retire before expecting history.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
|
||||
assert!(
|
||||
history_after_edit > history_after_open,
|
||||
@@ -934,3 +958,40 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
"the transform input should shift down intact, but became {transform:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Undoing a hot step takes it back rather than moving the cursor, and redo stages the same ops afresh.
|
||||
#[tokio::test]
|
||||
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_base = editor.active_document().storage().unwrap().session().history().count();
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(64., 64., 192., 192.).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(after_edit, before_edit);
|
||||
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
|
||||
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
// Nothing in storage names the step's declaration bytes, so the step held for redo must keep them from garbage collection.
|
||||
assert!(
|
||||
editor.active_document().retracted_resource_hashes().next().is_some(),
|
||||
"the retracted step names its declaration resource"
|
||||
);
|
||||
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
|
||||
assert_eq!(storage.session().history().count(), history_base);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::PeerId;
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
|
||||
@@ -83,7 +83,7 @@ pub struct RoundTrip {
|
||||
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
|
||||
@@ -14,6 +14,7 @@ mod layout;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
pub mod storage_metadata;
|
||||
mod store;
|
||||
@@ -25,6 +26,7 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
pub use resolved_types::type_feeds_connector;
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
|
||||
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
|
||||
/// never made back to whoever sent it. Writing through the store and then dropping what the store
|
||||
/// recorded keeps the two parallel trees written by one place, which is the property the store
|
||||
/// exists for, without the echo.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
|
||||
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
|
||||
let recorded = self.deltas.len();
|
||||
self.mirror(delta);
|
||||
|
||||
+243
@@ -633,6 +633,249 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a peer receives must bring its interface to what the editing peer holds: the recorded deltas become storage ops on
|
||||
/// the peer's registry, the touched entities are reconciled into a pre-edit clone, and that must equal the edited interface
|
||||
/// and convert back to the registry it was reconciled from.
|
||||
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
// Both interfaces address nodes the way storage does, so they compare directly.
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
// The peer's registry holds what a conversion of the interface holds before the edit.
|
||||
let mut mirror = editor.active_document().network_interface.clone();
|
||||
let baseline = {
|
||||
let document = editor.active_document();
|
||||
Registry::convert_from_runtime(
|
||||
document.network_interface.document_network(),
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
&document.resources.registry,
|
||||
PEER,
|
||||
)
|
||||
.expect("conversion")
|
||||
};
|
||||
let mut peer = Session::with_peer(PeerId(8));
|
||||
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
|
||||
let mut declarations = baseline.declarations;
|
||||
|
||||
edit(&mut editor);
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let recorded = editor.active_document_mut().network_interface.take_deltas();
|
||||
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
|
||||
let constructed = {
|
||||
let document = editor.active_document();
|
||||
construct_batch(
|
||||
&recorded,
|
||||
&baseline.registry,
|
||||
&document.resources.registry,
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
PEER,
|
||||
)
|
||||
.expect("construction")
|
||||
};
|
||||
declarations.extend(constructed.declarations.decoded);
|
||||
|
||||
let mut touched = Touched::default();
|
||||
for op in &constructed.ops {
|
||||
touched.record(op);
|
||||
}
|
||||
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
|
||||
|
||||
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
|
||||
|
||||
let edited = &editor.active_document().network_interface;
|
||||
assert!(
|
||||
mirror.document_network() == edited.document_network(),
|
||||
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
|
||||
recorded.len(),
|
||||
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
|
||||
);
|
||||
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
|
||||
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
|
||||
assert!(
|
||||
reconciled_metadata == edited_metadata,
|
||||
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
|
||||
recorded.len(),
|
||||
json_diff(&edited_metadata, &reconciled_metadata, "")
|
||||
);
|
||||
|
||||
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
|
||||
.expect("the reconciled interface converts")
|
||||
.registry;
|
||||
assert!(
|
||||
peer.registry().value_equal(&converted),
|
||||
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
|
||||
compute_deltas(&converted, peer.registry())
|
||||
);
|
||||
}
|
||||
|
||||
/// The paths at which two JSON values differ, one per line, so a metadata mismatch names the field.
|
||||
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
|
||||
use serde_json::Value;
|
||||
match (expected, actual) {
|
||||
(Value::Object(expected), Value::Object(actual)) => {
|
||||
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
|
||||
keys.into_iter()
|
||||
.map(|key| match (expected.get(key), actual.get(key)) {
|
||||
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
|
||||
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
|
||||
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
|
||||
(None, None) => String::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
|
||||
.iter()
|
||||
.zip(actual)
|
||||
.enumerate()
|
||||
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
|
||||
.collect(),
|
||||
_ if expected == actual => String::new(),
|
||||
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_metadata_edits_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
|
||||
network_interface.set_locked(&group, &[], true);
|
||||
network_interface.set_pinned(&group, &[], true);
|
||||
network_interface.set_visibility(&group, &[], false);
|
||||
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_arity_change_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
|
||||
.expect("rectangle definition")
|
||||
.default_node_template();
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
|
||||
.expect("rectangle definition")
|
||||
.default_node_template();
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), template, &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_group_removal_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
|
||||
panic!("the group should resolve")
|
||||
};
|
||||
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let inner = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| input.as_value().is_some()))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("a node with a value input inside the group");
|
||||
let index = interface
|
||||
.nested_network(&[group])
|
||||
.and_then(|network| network.nodes.get(&inner))
|
||||
.and_then(|node| node.inputs.iter().position(|input| input.as_value().is_some()))
|
||||
.expect("the value input");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A touched node the registry holds unchanged, as a late-writer-wins loser leaves it, must not disturb the interface.
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_untouched_node_changes_nothing() {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let baseline = convert(&editor);
|
||||
let declarations = {
|
||||
let document = editor.active_document();
|
||||
Registry::convert_from_runtime(
|
||||
document.network_interface.document_network(),
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
&document.resources.registry,
|
||||
PEER,
|
||||
)
|
||||
.expect("conversion")
|
||||
.declarations
|
||||
};
|
||||
let mut touched = Touched::default();
|
||||
touched.nodes.extend(baseline.node_instances.keys().copied());
|
||||
touched.networks.extend(baseline.networks.keys().copied());
|
||||
|
||||
let before = editor.active_document().network_interface.clone();
|
||||
let reconciled = editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.reconcile_remote(&baseline, &declarations, &touched, PEER)
|
||||
.expect("reconcile");
|
||||
|
||||
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
|
||||
assert_eq!(editor.active_document().network_interface, before);
|
||||
}
|
||||
|
||||
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
|
||||
#[test]
|
||||
fn a_deleted_ui_key_is_not_cleared_again() {
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! Brings the interface into line with the working registry for the entities peers touched, so a remote
|
||||
//! batch costs deltas for what changed rather than a rebuild of the whole interface.
|
||||
//!
|
||||
//! Each touched node is projected to its runtime form and compared with what the interface holds. The
|
||||
//! difference is applied through `apply` as the `EditorDelta`s a local edit records, mirrored without
|
||||
//! recording so nothing is offered back to its sender. A node held on one side only is added or removed
|
||||
//! whole, and what no field write expresses, such as a changed implementation or scope injection, replaces it.
|
||||
//!
|
||||
//! The touched set over-approximates: a late-writer-wins loser or a failed op names an unchanged entity,
|
||||
//! for which the comparison emits nothing.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::to_runtime::ConversionError;
|
||||
use document_graph_storage::{Declarations, NodeId as StorageNodeId, ROOT_NETWORK, Registry, RuntimeProjection, Touched};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
use super::storage_metadata::{InterfaceRebuildError, node_metadata_from_projection};
|
||||
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReconcileError {
|
||||
/// A declaration the touched nodes need is not cached yet. Nothing was applied; retry once it lands.
|
||||
#[error("waiting for proto-node declaration {0}")]
|
||||
DeclarationMissing(document_graph_storage::ResourceId),
|
||||
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
|
||||
NetworkMissing(Vec<NodeId>),
|
||||
#[error(transparent)]
|
||||
Conversion(ConversionError),
|
||||
#[error(transparent)]
|
||||
Metadata(#[from] InterfaceRebuildError),
|
||||
}
|
||||
|
||||
impl From<ConversionError> for ReconcileError {
|
||||
fn from(error: ConversionError) -> Self {
|
||||
match error {
|
||||
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
|
||||
other => Self::Conversion(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a reconcile changed, for the caller to unload what those changes feed.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Reconciled {
|
||||
/// The networks a delta was applied in.
|
||||
pub networks: BTreeSet<Vec<NodeId>>,
|
||||
}
|
||||
|
||||
/// Where the interface holds each node storage knows, keyed by the identity storage addresses it by.
|
||||
type StorageIndex = HashMap<StorageNodeId, (Vec<NodeId>, NodeId)>;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Applies to the interface whatever the registry holds differently for the touched entities.
|
||||
///
|
||||
/// Can fail part-way through. Retrying with the same touched set is safe, since a reconciled node compares equal
|
||||
/// and emits nothing; the caller retries when a declaration is on its way and otherwise rebuilds from the registry.
|
||||
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
|
||||
let projection = registry.runtime_projection(declarations);
|
||||
let index = self.pin_storage_identities(peer);
|
||||
|
||||
// A touched network is reconciled through the node implementing it, whose comparison covers the
|
||||
// network's exports and metadata. The root has no such node.
|
||||
let mut ids = touched.nodes.clone();
|
||||
let mut root = false;
|
||||
for &network in &touched.networks {
|
||||
match projection.owner(network) {
|
||||
Some(owner) => {
|
||||
ids.insert(owner);
|
||||
}
|
||||
None => root |= network == ROOT_NETWORK,
|
||||
}
|
||||
}
|
||||
|
||||
// A node the runtime cannot reach and the interface does not hold has nothing to reconcile.
|
||||
let mut items: Vec<(Vec<NodeId>, NodeId, StorageNodeId)> = ids
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let (path, local_id) = projection.node_address(id).or_else(|| index.get(&id).cloned())?;
|
||||
Some((path, local_id, id))
|
||||
})
|
||||
.collect();
|
||||
// A network's path is a prefix of the paths inside it, so this puts each node after the one
|
||||
// implementing its network, and a nested node finds its network in place.
|
||||
items.sort();
|
||||
|
||||
let mut reconciled = Reconciled::default();
|
||||
for (path, local_id, id) in items {
|
||||
self.reconcile_node(&projection, &index, &path, local_id, id, &mut reconciled)?;
|
||||
}
|
||||
if root {
|
||||
let target = projection.network_entry(ROOT_NETWORK)?;
|
||||
let current_exports = self.document_network().exports.clone();
|
||||
let current = &self.document_network_metadata().persistent_metadata;
|
||||
let mut deltas = Vec::new();
|
||||
export_deltas(&[], ¤t_exports, &target.exports, &mut deltas);
|
||||
network_metadata_deltas(
|
||||
&[],
|
||||
current.reference.as_deref(),
|
||||
¤t.pinned_node_order,
|
||||
target.metadata.reference.as_deref(),
|
||||
&target.metadata.pinned_order,
|
||||
&mut deltas,
|
||||
);
|
||||
self.apply_reconciled(&[], deltas, &mut reconciled);
|
||||
}
|
||||
|
||||
Ok(reconciled)
|
||||
}
|
||||
|
||||
fn reconcile_node(
|
||||
&mut self,
|
||||
projection: &RuntimeProjection,
|
||||
index: &StorageIndex,
|
||||
path: &[NodeId],
|
||||
local_id: NodeId,
|
||||
id: StorageNodeId,
|
||||
reconciled: &mut Reconciled,
|
||||
) -> Result<(), ReconcileError> {
|
||||
// The interface holds the node elsewhere, under another id or in a network it has left; that copy goes first.
|
||||
if let Some((held_path, held_id)) = index.get(&id)
|
||||
&& (held_path.as_slice() != path || *held_id != local_id)
|
||||
&& self.holds_node(held_path, *held_id)
|
||||
{
|
||||
self.apply_reconciled(held_path, vec![remove_node(held_path, *held_id)], reconciled);
|
||||
}
|
||||
|
||||
let stored = projection.node_address(id).is_some();
|
||||
let held = self.holds_node(path, local_id);
|
||||
match (stored, held) {
|
||||
(false, false) => {}
|
||||
(false, true) => self.apply_reconciled(path, vec![remove_node(path, local_id)], reconciled),
|
||||
(true, false) => {
|
||||
if !self.holds_network(path) {
|
||||
return Err(ReconcileError::NetworkMissing(path.to_vec()));
|
||||
}
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
let nested = matches!(node.implementation, DocumentNodeImplementation::Network(_));
|
||||
let deltas = vec![
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
node: Box::new(node),
|
||||
}),
|
||||
EditorDelta::NodeMetadataSnapshot {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
metadata: Box::new(metadata),
|
||||
},
|
||||
];
|
||||
self.apply_reconciled(path, deltas, reconciled);
|
||||
if nested {
|
||||
reconciled.networks.insert(nested_path(path, local_id));
|
||||
}
|
||||
}
|
||||
(true, true) => {
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
self.diff_node(path, local_id, node, metadata, reconciled);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Emits what differs between the node the interface holds at `path` / `local_id` and `target`, which
|
||||
/// the registry describes. A network node's contents are left to their own reconciliation: only its
|
||||
/// exports and its network's metadata are compared here.
|
||||
fn diff_node(&mut self, path: &[NodeId], local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
|
||||
let Some(current) = self.document_network().nested_network(path).and_then(|network| network.nodes.get(&local_id)) else {
|
||||
return;
|
||||
};
|
||||
let Some(current_metadata) = self
|
||||
.document_network_metadata()
|
||||
.nested_metadata(path)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
|
||||
.map(|node| &node.persistent_metadata)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut deltas = Vec::new();
|
||||
let mut nested_changed = false;
|
||||
let at = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
change,
|
||||
};
|
||||
|
||||
// What no field write expresses replaces the node whole, and its metadata with it.
|
||||
if !same_implementation(¤t.implementation, &target.implementation) || current.skip_deduplication != target.skip_deduplication {
|
||||
nested_changed = matches!(target.implementation, DocumentNodeImplementation::Network(_)) || matches!(current.implementation, DocumentNodeImplementation::Network(_));
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::ReplaceNode {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
node: Box::new(target),
|
||||
}));
|
||||
deltas.push(EditorDelta::NodeMetadataSnapshot {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
metadata: Box::new(target_metadata),
|
||||
});
|
||||
} else {
|
||||
// The slots first, so the metadata array that indexes them lands on a list of the right length.
|
||||
if current.inputs.len() != target.inputs.len() {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
inputs: target.inputs.clone(),
|
||||
}));
|
||||
deltas.push(EditorDelta::NodeInputMetadata {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
input_metadata: target_metadata.input_metadata.clone(),
|
||||
});
|
||||
} else {
|
||||
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
|
||||
if held != wanted {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
input_index,
|
||||
input: wanted.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if current_metadata.input_metadata != target_metadata.input_metadata {
|
||||
deltas.push(EditorDelta::NodeInputMetadata {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
input_metadata: target_metadata.input_metadata.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Export slot writes rename the encapsulating node's outputs as a side effect, so the names are
|
||||
// restated after them whenever the slot count moved.
|
||||
let mut restate_output_names = false;
|
||||
if let (DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) = (¤t.implementation, &target.implementation) {
|
||||
let nested = nested_path(path, local_id);
|
||||
let before = deltas.len();
|
||||
export_deltas(&nested, &held.exports, &wanted.exports, &mut deltas);
|
||||
restate_output_names = held.exports.len() != wanted.exports.len();
|
||||
|
||||
let (held_reference, held_order) = current_metadata
|
||||
.network_metadata
|
||||
.as_ref()
|
||||
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
|
||||
.unwrap_or((None, &[]));
|
||||
let (wanted_reference, wanted_order) = target_metadata
|
||||
.network_metadata
|
||||
.as_ref()
|
||||
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
|
||||
.unwrap_or((None, &[]));
|
||||
network_metadata_deltas(&nested, held_reference, held_order, wanted_reference, wanted_order, &mut deltas);
|
||||
nested_changed = deltas.len() != before;
|
||||
}
|
||||
|
||||
if current.visible != target.visible {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
visible: target.visible,
|
||||
}));
|
||||
}
|
||||
if current.call_argument != target.call_argument {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
call_argument: target.call_argument.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(at(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(at(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
}
|
||||
if current_metadata.locked != target_metadata.locked {
|
||||
deltas.push(at(NodeMetadataChange::Locked(target_metadata.locked)));
|
||||
}
|
||||
if current_metadata.pinned != target_metadata.pinned {
|
||||
deltas.push(at(NodeMetadataChange::Pinned(target_metadata.pinned)));
|
||||
}
|
||||
if restate_output_names || current_metadata.output_names != target_metadata.output_names {
|
||||
deltas.push(at(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
|
||||
}
|
||||
}
|
||||
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.apply_reconciled(path, deltas, reconciled);
|
||||
if nested_changed {
|
||||
reconciled.networks.insert(nested_path(path, local_id));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_reconciled(&mut self, path: &[NodeId], deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
for delta in &deltas {
|
||||
self.apply(delta);
|
||||
}
|
||||
reconciled.networks.insert(path.to_vec());
|
||||
}
|
||||
|
||||
fn holds_node(&self, path: &[NodeId], local_id: NodeId) -> bool {
|
||||
self.document_network().nested_network(path).is_some_and(|network| network.nodes.contains_key(&local_id))
|
||||
&& self
|
||||
.document_network_metadata()
|
||||
.nested_metadata(path)
|
||||
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
|
||||
}
|
||||
|
||||
fn holds_network(&self, path: &[NodeId]) -> bool {
|
||||
self.document_network().nested_network(path).is_some() && self.document_network_metadata().nested_metadata(path).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_node(path: &[NodeId], local_id: NodeId) -> EditorDelta {
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode {
|
||||
network_path: path.to_vec(),
|
||||
node_id: local_id,
|
||||
})
|
||||
}
|
||||
|
||||
fn nested_path(path: &[NodeId], local_id: NodeId) -> Vec<NodeId> {
|
||||
[path, &[local_id]].concat()
|
||||
}
|
||||
|
||||
/// Whether a field-by-field comparison can bring `current` to `target`, which it cannot across a
|
||||
/// change of what the node computes.
|
||||
fn same_implementation(current: &DocumentNodeImplementation, target: &DocumentNodeImplementation) -> bool {
|
||||
match (current, target) {
|
||||
(DocumentNodeImplementation::ProtoNode(held), DocumentNodeImplementation::ProtoNode(wanted)) => held == wanted,
|
||||
(DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) => held.scope_injections == wanted.scope_injections,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot writes taking `current` to `target`: a write per slot that differs, then a removal at the
|
||||
/// end for each slot too many, which the mirror applies as removals of that index in turn.
|
||||
fn export_deltas(network_path: &[NodeId], current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
|
||||
for (export_index, input) in target.iter().enumerate() {
|
||||
if current.get(export_index) != Some(input) {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index,
|
||||
input: Some(input.clone()),
|
||||
}));
|
||||
}
|
||||
}
|
||||
for _ in target.len()..current.len() {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: target.len(),
|
||||
input: None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
fn network_metadata_deltas(network_path: &[NodeId], current_reference: Option<&str>, current_order: &[NodeId], target_reference: Option<&str>, target_order: &[NodeId], deltas: &mut Vec<EditorDelta>) {
|
||||
if current_reference != target_reference {
|
||||
deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: network_path.to_vec(),
|
||||
change: NetworkMetadataChange::Reference(target_reference.map(str::to_string)),
|
||||
});
|
||||
}
|
||||
if current_order != target_order {
|
||||
deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: network_path.to_vec(),
|
||||
change: NetworkMetadataChange::PinnedOrder(target_order.to_vec()),
|
||||
});
|
||||
}
|
||||
}
|
||||
+40
@@ -194,6 +194,46 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
|
||||
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
|
||||
}
|
||||
|
||||
/// The runtime node and the persistent metadata for it and everything nested under it, from a single-node projection
|
||||
/// of the registry. Uses the same entry patching as a whole rebuild, so a reconciled node matches what a rebuild holds.
|
||||
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
|
||||
let document_graph_storage::ProjectedNode {
|
||||
network_path: prefix,
|
||||
local_id,
|
||||
node,
|
||||
node_entries,
|
||||
network_entries,
|
||||
} = projected;
|
||||
|
||||
// The entries carry absolute paths; the scratch tree is rooted at the node's own network.
|
||||
let rebase = |path: Vec<NodeId>| path.get(prefix.len()..).map(<[NodeId]>::to_vec).unwrap_or_default();
|
||||
let node_entries = node_entries
|
||||
.into_iter()
|
||||
.map(|entry| NodeMetadataEntry {
|
||||
network_path: rebase(entry.network_path),
|
||||
..entry
|
||||
})
|
||||
.collect();
|
||||
let network_entries = network_entries
|
||||
.into_iter()
|
||||
.map(|entry| NetworkMetadataEntry {
|
||||
network_path: rebase(entry.network_path),
|
||||
..entry
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut scratch = NodeNetwork::default();
|
||||
scratch.nodes.insert(local_id, node);
|
||||
let mut metadata = NodeNetworkMetadata::default();
|
||||
seed_metadata_tree(&scratch, &mut metadata);
|
||||
apply_entries_into_tree(&scratch, &mut metadata, node_entries)?;
|
||||
apply_network_entries_into_tree(&mut metadata, network_entries);
|
||||
|
||||
let persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
|
||||
let node = scratch.nodes.remove(&local_id).expect("inserted above");
|
||||
Ok((node, persistent))
|
||||
}
|
||||
|
||||
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
|
||||
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
|
||||
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, document_graph_storage::NetworkId> {
|
||||
|
||||
@@ -360,6 +360,48 @@ impl NodeNetworkInterface {
|
||||
self.deltas.clear();
|
||||
}
|
||||
|
||||
/// Pins every node to the identity storage addresses it by, returning where each is held.
|
||||
///
|
||||
/// A node created here is addressed by a hash of its location until pinned, the identity a conversion derives anyway.
|
||||
/// Pinning changes no document content, so nothing is recorded.
|
||||
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (Vec<NodeId>, NodeId)> {
|
||||
let mut index = HashMap::new();
|
||||
let mut unpinned = Vec::new();
|
||||
{
|
||||
let view = super::storage_metadata::StorageMetadataView::new(self);
|
||||
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
|
||||
let mut stack = vec![(Vec::new(), &*self.network_metadata)];
|
||||
while let Some((path, metadata)) = stack.pop() {
|
||||
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
|
||||
let storage_id = match node.persistent_metadata.storage_id {
|
||||
Some(pinned) => document_graph_storage::NodeId(pinned),
|
||||
None => {
|
||||
let derived = resolver.node_id(&path, local_id);
|
||||
unpinned.push((path.clone(), local_id, derived));
|
||||
derived
|
||||
}
|
||||
};
|
||||
index.insert(storage_id, (path.clone(), local_id));
|
||||
if let Some(nested) = &node.persistent_metadata.network_metadata {
|
||||
stack.push(([path.as_slice(), &[local_id]].concat(), nested));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (path, local_id, storage_id) in unpinned {
|
||||
if let Some(node) = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(&path)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
|
||||
{
|
||||
node.persistent_metadata.storage_id = Some(storage_id.0);
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// Records the open transaction's bookkeeping, so writes that are undone before [`Self::restore_transaction_checkpoint`] don't count toward it.
|
||||
pub fn transaction_checkpoint(&mut self) -> TransactionCheckpoint {
|
||||
self.scan_transaction_edited_nodes();
|
||||
|
||||
@@ -16,7 +16,7 @@ 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 document_graph_storage::{Declarations, PeerId, UserId};
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -69,9 +69,9 @@ pub(super) async fn list_stored_documents(store: DocumentStoreHandle) -> Message
|
||||
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 {
|
||||
pub(super) async fn load_stored_document(store: DocumentStoreHandle, document_id: DocumentId, resources: ResourcesHandle, reset_nodes: 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,
|
||||
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes).await,
|
||||
Err(error) => {
|
||||
log::error!("Opening the stored document {document_id:?} failed: {error}");
|
||||
(None, None)
|
||||
@@ -88,7 +88,7 @@ pub(super) async fn load_stored_document(store: DocumentStoreHandle, document_id
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
pub(super) async fn attach_container(store: DocumentStoreHandle, document_id: DocumentId, resources: ResourcesHandle) -> Message {
|
||||
let container = match store.open(document_key(document_id)).await {
|
||||
Ok(container) => container,
|
||||
Err(error) => {
|
||||
@@ -102,23 +102,6 @@ pub(super) async fn attach_container(store: DocumentStoreHandle, document_id: Do
|
||||
.into();
|
||||
}
|
||||
};
|
||||
let gdd = if !legacy_only {
|
||||
open_storage_or_fallback_to_legacy(container.clone(), document_id).await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let declarations = load_declarations(gdd.as_ref(), &resources).await;
|
||||
PortfolioMessage::StorageAttached {
|
||||
document_id,
|
||||
container: Some(container),
|
||||
gdd: gdd.map(Box::new),
|
||||
declarations,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -138,15 +121,16 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
|
||||
}
|
||||
|
||||
/// Materializes a `.gdd` archive into a fresh store container and loads it like a stored document.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn open_document_file(
|
||||
store: DocumentStoreHandle,
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
fresh_identity: bool,
|
||||
resources: ResourcesHandle,
|
||||
reset_nodes: bool,
|
||||
legacy_only: bool,
|
||||
) -> Message {
|
||||
let materialized = async {
|
||||
let mut container = store.open(document_key(document_id)).await.map_err(|error| error.to_string())?;
|
||||
@@ -154,13 +138,25 @@ pub(super) async fn open_document_file(
|
||||
Ok::<_, String>(container)
|
||||
}
|
||||
.await;
|
||||
let (document, gdd) = match materialized {
|
||||
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes, legacy_only).await,
|
||||
let (mut document, mut gdd) = match materialized {
|
||||
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes).await,
|
||||
Err(error) => {
|
||||
log::error!("Opening the document archive for {document_id:?} failed: {error}");
|
||||
(None, None)
|
||||
}
|
||||
};
|
||||
// The session room derives from the manifest's id, so a copy of a distributed file such as a demo artwork gets its own.
|
||||
if fresh_identity {
|
||||
let storage = match gdd.as_mut() {
|
||||
Some(gdd) => Some(gdd),
|
||||
None => document.as_mut().and_then(|document| document.storage_mut()),
|
||||
};
|
||||
if let Some(storage) = storage
|
||||
&& let Err(error) = storage.update_manifest(|manifest| manifest.document_id = generate_uuid())
|
||||
{
|
||||
log::error!("Giving the copy of {document_id:?} its own id failed: {error}");
|
||||
}
|
||||
}
|
||||
let declarations = load_declarations(gdd.as_ref(), &resources).await;
|
||||
PortfolioMessage::DocumentFileLoaded {
|
||||
document_id,
|
||||
@@ -174,7 +170,7 @@ pub(super) async fn open_document_file(
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
async fn load_from_container(container: AnyContainer, document_id: DocumentId, resources: &ResourcesHandle, reset_nodes: 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())
|
||||
@@ -185,7 +181,7 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
|
||||
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 };
|
||||
let gdd = open_storage_or_fallback_to_legacy(container, document_id).await;
|
||||
(Some(document), gdd)
|
||||
}
|
||||
Err(legacy_error) => {
|
||||
@@ -201,9 +197,6 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
|
||||
return (None, None);
|
||||
};
|
||||
document.container = Some(container);
|
||||
if legacy_only {
|
||||
document.clear_storage();
|
||||
}
|
||||
(Some(document), None)
|
||||
}
|
||||
}
|
||||
@@ -227,7 +220,11 @@ async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id
|
||||
container.remove(&path).await?;
|
||||
}
|
||||
}
|
||||
GddV1::create_in(container, GddV1Layout, PeerId(generate_uuid()), document_id.0, version.clone(), version)
|
||||
{
|
||||
// The person at this device is set when the storage is attached; until then the peer stands for itself.
|
||||
let peer = PeerId(generate_uuid());
|
||||
GddV1::create_in(container, GddV1Layout, peer, UserId(peer.0), document_id.0, version.clone(), version)
|
||||
}
|
||||
}
|
||||
.await;
|
||||
match created {
|
||||
@@ -281,7 +278,7 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
|
||||
};
|
||||
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
|
||||
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, byte_store.storage(), String::new(), None);
|
||||
document.finalize_storage_load();
|
||||
Some(document)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Browser tabs of one origin share the document store, so only one tab at a time may use it. Another tab
|
||||
//! restoring the same documents would write the same containers and rejoin their sessions as the same peer.
|
||||
//! The first tab holds a Web Lock until it closes; a tab that finds it held keeps its documents in memory,
|
||||
//! which still lets it join a session hosted in the first tab, as when trying collaboration locally.
|
||||
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
const LOCK_NAME: &str = "graphite-document-store";
|
||||
|
||||
/// Whether this tab owns the document store, taking it when no other tab does. A browser without Web Locks
|
||||
/// cannot tell, so the tab owns it as before.
|
||||
pub async fn claim() -> bool {
|
||||
let Some(window) = web_sys::window() else { return true };
|
||||
let navigator = window.navigator();
|
||||
if !js_sys::Reflect::has(&navigator, &JsValue::from_str("locks")).unwrap_or(false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
// A granted lock is held while the returned promise is pending, and this one never settles.
|
||||
let callback = Closure::once_into_js(move |lock: JsValue| {
|
||||
let granted = !lock.is_null();
|
||||
let _ = sender.send(granted);
|
||||
match granted {
|
||||
true => js_sys::Promise::new(&mut |_, _| {}),
|
||||
false => js_sys::Promise::resolve(&JsValue::UNDEFINED),
|
||||
}
|
||||
});
|
||||
let options = web_sys::LockOptions::new();
|
||||
options.set_if_available(true);
|
||||
let _ = navigator.locks().request_with_options_and_callback(LOCK_NAME, &options, callback.unchecked_ref());
|
||||
|
||||
receiver.await.unwrap_or(true)
|
||||
}
|
||||
@@ -229,6 +229,7 @@ mod tests {
|
||||
name: name.to_string(),
|
||||
path: None,
|
||||
is_saved: true,
|
||||
session: None,
|
||||
});
|
||||
|
||||
let names: HashSet<_> = recovery_file_names(infos.iter()).into_iter().map(|(_, name)| name).collect();
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, History)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum HistoryMessage {
|
||||
/// Send the History panel's content for the active document, whether or not anything changed.
|
||||
Refresh,
|
||||
/// Once per frame while the panel is open: send the content again if the history moved since the last send.
|
||||
Tick,
|
||||
/// Show or hide the deltas of one interaction, named by the rev that closes it.
|
||||
Expand { id: String, expanded: bool },
|
||||
/// Show older interactions than the ones on hand.
|
||||
LoadMore,
|
||||
/// Move the head to the interaction: back along the line, or forward again over undone ones.
|
||||
GoBack { id: String },
|
||||
/// Drop one interaction out of the line, the later ones staying.
|
||||
RemoveStep { id: String },
|
||||
/// Bring an undone or abandoned interaction back.
|
||||
BringBack { id: String },
|
||||
/// Show the line of the branch whose tip is `id`, or the head's line again with `None`.
|
||||
Follow { id: Option<String> },
|
||||
/// Give the interaction a name of its own, or take it away with an empty one.
|
||||
Rename { id: String, label: String },
|
||||
/// Put a tag on the interaction, or take it off.
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
|
||||
use crate::messages::portfolio::sync::now_ms;
|
||||
use crate::messages::prelude::*;
|
||||
use document_format::GddV1;
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, UserId, rev_attr};
|
||||
use peer_transport::RemotePeer;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct HistoryMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
/// Whether the History panel is showing; nothing is computed while it is not.
|
||||
pub panel_open: bool,
|
||||
}
|
||||
|
||||
/// Feeds the History panel with the active document's history as interactions along a line, sent again
|
||||
/// whenever it moved, and turns the panel's actions into moves of the document's head.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct HistoryMessageHandler {
|
||||
/// Whether the per-frame tick is subscribed.
|
||||
ticking: bool,
|
||||
/// Interactions shown with their deltas, by closing rev.
|
||||
expanded: HashSet<Rev>,
|
||||
/// How many interactions of the line to send; grows on request.
|
||||
limit: usize,
|
||||
/// The tip of the branch shown instead of the head's line.
|
||||
following: Option<Rev>,
|
||||
/// What the last send described, so a frame with no movement sends nothing.
|
||||
last_sent: Option<u64>,
|
||||
}
|
||||
|
||||
/// Interactions sent at first, and added per request for older ones.
|
||||
const PAGE: usize = 100;
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
|
||||
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
|
||||
match message {
|
||||
HistoryMessage::Refresh => {
|
||||
if !self.ticking {
|
||||
self.ticking = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(HistoryMessage::Tick.into()),
|
||||
});
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tick => {
|
||||
if context.panel_open {
|
||||
self.send(&context, responses, false);
|
||||
}
|
||||
}
|
||||
HistoryMessage::Expand { id, expanded } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
match expanded {
|
||||
true => self.expanded.insert(rev),
|
||||
false => self.expanded.remove(&rev),
|
||||
};
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::LoadMore => {
|
||||
self.limit = self.limit.max(PAGE) + PAGE;
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Follow { id } => {
|
||||
self.following = id.as_deref().and_then(parse_rev);
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::GoBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
let session = gdd.session();
|
||||
match place(session, rev) {
|
||||
// Above the head: forward again over the undone interactions, one redo each.
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
// On the head's line: in a session one shared move for everyone; alone, the cursor walks back one
|
||||
// interaction at a time so the editor's own undo stays in step.
|
||||
Some(Place::Line(0)) => {}
|
||||
Some(Place::Line(steps)) => match gdd.role().is_some() {
|
||||
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
|
||||
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
|
||||
},
|
||||
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
|
||||
}
|
||||
}
|
||||
HistoryMessage::RemoveStep { id } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
responses.add(DocumentMessage::HistoryRemoveStep { rev });
|
||||
}
|
||||
}
|
||||
HistoryMessage::BringBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
match place(gdd.session(), rev) {
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
Some(Place::Line(_)) => {}
|
||||
// Off the line: minted again on top of it.
|
||||
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
|
||||
}
|
||||
}
|
||||
HistoryMessage::Rename { id, label } => {
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record_rev_attribute(rev, rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
|
||||
log::warn!("Naming the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tag { id, tag, on } => {
|
||||
let tag = tag.trim();
|
||||
if tag.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record_rev_attribute(rev, &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
|
||||
log::warn!("Tagging the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(HistoryMessageDiscriminant;);
|
||||
}
|
||||
|
||||
impl HistoryMessageHandler {
|
||||
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
|
||||
let Some(gdd) = active_storage(context) else {
|
||||
if force {
|
||||
self.last_sent = None;
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
|
||||
}
|
||||
return;
|
||||
};
|
||||
// A branch whose tip this copy no longer holds is nothing to follow.
|
||||
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
|
||||
self.following = None;
|
||||
}
|
||||
let limit = self.limit.max(PAGE);
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
|
||||
if !force && self.last_sent == Some(fingerprint) {
|
||||
return;
|
||||
}
|
||||
self.last_sent = Some(fingerprint);
|
||||
let state = panel_state(gdd, limit, &self.expanded, self.following);
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state });
|
||||
}
|
||||
}
|
||||
|
||||
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
|
||||
}
|
||||
|
||||
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
|
||||
}
|
||||
|
||||
fn parse_rev(id: &str) -> Option<Rev> {
|
||||
id.parse::<u128>().ok().and_then(Rev::new)
|
||||
}
|
||||
|
||||
/// Where an interaction sits relative to the head.
|
||||
enum Place {
|
||||
/// On the head's line, this many interactions back; zero is the head itself.
|
||||
Line(usize),
|
||||
/// Above the head on the undone line, this many redos forward.
|
||||
Undone(usize),
|
||||
}
|
||||
|
||||
fn place(session: &Session, rev: Rev) -> Option<Place> {
|
||||
let head = session.head_rev();
|
||||
let (kept, _) = line(session, head, None, usize::MAX);
|
||||
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
|
||||
return Some(Place::Line(steps));
|
||||
}
|
||||
let checkpoint = *session.redo_stack().last()?;
|
||||
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
|
||||
let groups = interactions(&undone);
|
||||
let index = groups.iter().position(|group| group[0].id == rev)?;
|
||||
Some(Place::Undone(groups.len() - index))
|
||||
}
|
||||
|
||||
/// Everything the panel's content depends on, hashed: cheap to take every frame.
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
|
||||
let session = gdd.session();
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
document_id.hash(&mut hasher);
|
||||
session.history_len().hash(&mut hasher);
|
||||
session.head_rev().hash(&mut hasher);
|
||||
session.redo_stack().hash(&mut hasher);
|
||||
session.hot_log().len().hash(&mut hasher);
|
||||
gdd.role().is_some().hash(&mut hasher);
|
||||
for record in &gdd.metadata().users {
|
||||
record.user.hash(&mut hasher);
|
||||
if let Some(name) = gdd.metadata().user_name(record.user) {
|
||||
name.hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
for remote in gdd.peers() {
|
||||
remote.user.hash(&mut hasher);
|
||||
remote.name.hash(&mut hasher);
|
||||
}
|
||||
for record in &gdd.metadata().revs {
|
||||
record.rev.hash(&mut hasher);
|
||||
for (key, fact) in &record.attributes {
|
||||
key.hash(&mut hasher);
|
||||
fact.stamp.hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
limit.hash(&mut hasher);
|
||||
expanded.len().hash(&mut hasher);
|
||||
following.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
let session = gdd.session();
|
||||
let people = People {
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
peers: gdd.peers(),
|
||||
};
|
||||
|
||||
// Where branches leave the lines shown: every delta's children, minus the lines themselves.
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in session.history() {
|
||||
for parent in delta.all_parents() {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
|
||||
let head = session.head_rev();
|
||||
let (head_line, _) = line(session, head, None, usize::MAX);
|
||||
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
|
||||
|
||||
// Taken back and not yet redone: from the redo stack's top down to the head, shown above it. Not while
|
||||
// following a branch, whose line is shown whole instead.
|
||||
let undone = match (following, session.redo_stack().last()) {
|
||||
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let (shown, more) = match following {
|
||||
Some(tip) => line(session, Some(tip), None, limit),
|
||||
None => (
|
||||
head_line
|
||||
.iter()
|
||||
.take_while({
|
||||
let mut ends = 0;
|
||||
move |delta| {
|
||||
if delta.is_interaction_end() {
|
||||
ends += 1;
|
||||
}
|
||||
ends <= limit
|
||||
}
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
interactions(&head_line).len() > limit,
|
||||
),
|
||||
};
|
||||
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
|
||||
|
||||
let view = View {
|
||||
children: &children,
|
||||
on_line: &on_line,
|
||||
head_line: &head_line_revs,
|
||||
head,
|
||||
people: &people,
|
||||
expanded,
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for group in interactions(&undone) {
|
||||
rows.push(view.row(&group, true));
|
||||
}
|
||||
for group in interactions(&shown) {
|
||||
rows.push(view.row(&group, false));
|
||||
}
|
||||
|
||||
// What has not entered history yet: every author's open interaction first, then each closed interaction
|
||||
// waiting for the retirer as a step of its own, the newest first like the rows below.
|
||||
let hot_log = session.hot_log();
|
||||
let closed = session.closed_interactions();
|
||||
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
|
||||
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
|
||||
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
|
||||
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
|
||||
Some((_, ops)) => ops.push(&hot_op.op),
|
||||
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
|
||||
}
|
||||
}
|
||||
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
|
||||
for interaction in closed.iter().rev() {
|
||||
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
|
||||
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
|
||||
progress.push(progress_row(&people, interaction.author, &ops, false));
|
||||
}
|
||||
|
||||
HistoryPanelState {
|
||||
rows,
|
||||
progress,
|
||||
more,
|
||||
following: following.map(|tip| tip.to_string()),
|
||||
session: gdd.role().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deltas from `from` back along first parents to `until` exclusive, or the root, newest first.
|
||||
/// Stops after `limit` interaction ends and says so.
|
||||
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
|
||||
let mut deltas = Vec::new();
|
||||
let mut ends = 0;
|
||||
let mut current = from;
|
||||
while let Some(rev) = current
|
||||
&& Some(rev) != until
|
||||
{
|
||||
let Some(delta) = session.delta(rev) else { break };
|
||||
if delta.is_interaction_end() {
|
||||
if ends == limit {
|
||||
return (deltas, true);
|
||||
}
|
||||
ends += 1;
|
||||
}
|
||||
deltas.push(delta.clone());
|
||||
current = delta.parent;
|
||||
}
|
||||
(deltas, false)
|
||||
}
|
||||
|
||||
/// Group a line, newest first, into interactions: each starts at an interaction end and runs back to the
|
||||
/// delta after the previous end. A newest delta that is not an end, from work retired mid-interaction, opens a group of its own.
|
||||
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
|
||||
let mut groups: Vec<Vec<&Delta>> = Vec::new();
|
||||
for delta in deltas {
|
||||
match groups.last_mut() {
|
||||
Some(group) if !delta.is_interaction_end() => group.push(delta),
|
||||
_ => groups.push(vec![delta]),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// What one send of the panel is computed against.
|
||||
struct View<'a> {
|
||||
children: &'a HashMap<Rev, Vec<Rev>>,
|
||||
on_line: &'a HashSet<Rev>,
|
||||
head_line: &'a HashSet<Rev>,
|
||||
head: Option<Rev>,
|
||||
people: &'a People<'a>,
|
||||
expanded: &'a HashSet<Rev>,
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
}
|
||||
|
||||
impl View<'_> {
|
||||
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
|
||||
let closing = group[0];
|
||||
let person = self.people.person(closing.author);
|
||||
let branches = group
|
||||
.iter()
|
||||
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
|
||||
.filter(|child| !self.on_line.contains(child))
|
||||
.map(|&child| self.branch(child))
|
||||
.collect();
|
||||
let is_expanded = self.expanded.contains(&closing.id);
|
||||
let details = match is_expanded {
|
||||
true => group
|
||||
.iter()
|
||||
.map(|delta| {
|
||||
let author = self.people.person(delta.author);
|
||||
HistoryDeltaRow {
|
||||
id: delta.id.to_string(),
|
||||
label: describe(&delta.kind),
|
||||
author: author.name,
|
||||
color: author.color,
|
||||
time: delta.retired_at().map(|ms| ms as f64),
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let given = self.metadata.rev_label(closing.id);
|
||||
HistoryRow {
|
||||
id: closing.id.to_string(),
|
||||
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
|
||||
named: given.is_some(),
|
||||
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
|
||||
deltas: group.len(),
|
||||
branches,
|
||||
undone,
|
||||
abandoned: !undone && !self.head_line.contains(&closing.id),
|
||||
head: Some(closing.id) == self.head,
|
||||
expanded: is_expanded,
|
||||
details,
|
||||
}
|
||||
}
|
||||
|
||||
/// The branch that starts at `first`: its tip, following first children, and what its newest interaction did.
|
||||
fn branch(&self, first: Rev) -> HistoryBranch {
|
||||
let mut tip = first;
|
||||
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
|
||||
tip = next;
|
||||
}
|
||||
let (newest, _) = line(self.session, Some(tip), None, 1);
|
||||
let label = self
|
||||
.metadata
|
||||
.rev_label(tip)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
|
||||
HistoryBranch { id: tip.to_string(), label }
|
||||
}
|
||||
}
|
||||
|
||||
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
|
||||
let person = people.person(peer);
|
||||
HistoryProgressRow {
|
||||
label: summarize(ops.iter().copied()),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
ops: ops.len(),
|
||||
open,
|
||||
}
|
||||
}
|
||||
|
||||
/// One line for a run of changes: the kinds among them, the most frequent first.
|
||||
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
|
||||
let kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
|
||||
let mut counts: Vec<(String, usize)> = Vec::new();
|
||||
for kind in &kinds {
|
||||
// A registration or a marker says nothing about the document; it labels a run only when it is all there is.
|
||||
if matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Meta) && kinds.len() > 1 {
|
||||
continue;
|
||||
}
|
||||
let label = describe(kind);
|
||||
match counts.iter_mut().find(|(known, _)| *known == label) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => counts.push((label, 1)),
|
||||
}
|
||||
}
|
||||
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
|
||||
let mut parts: Vec<String> = counts
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|(label, count)| match count {
|
||||
1 => label.clone(),
|
||||
count => format!("{label} ×{count}"),
|
||||
})
|
||||
.collect();
|
||||
if counts.len() > 2 {
|
||||
parts.push(format!("{} more", counts.len() - 2));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
|
||||
fn describe(kind: &RegistryDelta) -> String {
|
||||
match kind {
|
||||
RegistryDelta::AddNode { .. } => "Added a node".into(),
|
||||
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
|
||||
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
|
||||
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
|
||||
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
|
||||
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
|
||||
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
|
||||
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
|
||||
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
|
||||
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
|
||||
RegistryDelta::AddResource { .. } => "Added a resource".into(),
|
||||
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
|
||||
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
|
||||
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
|
||||
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
|
||||
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
|
||||
RegistryDelta::Meta => "Marked a step".into(),
|
||||
RegistryDelta::Other(_) => "Changed something".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How authors are named and coloured: the document's record first, then what the room announced, then
|
||||
/// the stand-in, all by user id so a person is one person across their peers.
|
||||
struct People<'a> {
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
peers: Vec<RemotePeer>,
|
||||
}
|
||||
|
||||
struct Person {
|
||||
name: String,
|
||||
anonymous: bool,
|
||||
mine: bool,
|
||||
color: String,
|
||||
}
|
||||
|
||||
impl People<'_> {
|
||||
fn person(&self, peer: PeerId) -> Person {
|
||||
// A peer that never registered, from a copy older than registrations, is its own user by convention.
|
||||
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
|
||||
let recorded = self.metadata.user_name(user).map(str::to_string);
|
||||
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
|
||||
let (name, anonymous) = match recorded.or_else(announced) {
|
||||
Some(name) => (name, false),
|
||||
None => (anonymous_name(user), true),
|
||||
};
|
||||
Person {
|
||||
name,
|
||||
anonymous,
|
||||
mine: self.session.is_mine(peer),
|
||||
color: user_color(user),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
|
||||
@@ -0,0 +1,84 @@
|
||||
//! What the History panel shows, as the frontend receives it.
|
||||
|
||||
/// The panel's content: a line as interactions, newest first. The head's line with the undone ones above it,
|
||||
/// or a branch's line while one is followed.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryPanelState {
|
||||
pub rows: Vec<HistoryRow>,
|
||||
/// Work under way in the room that has not entered history yet, one row per person.
|
||||
pub progress: Vec<HistoryProgressRow>,
|
||||
/// Whether older interactions exist beyond the rows sent.
|
||||
pub more: bool,
|
||||
/// The tip of the branch being followed instead of the head's line, if any.
|
||||
pub following: Option<String>,
|
||||
/// Whether the document is in a session, where moving the head moves it for everyone.
|
||||
pub session: bool,
|
||||
}
|
||||
|
||||
/// One interaction: a run of deltas that undo takes back together.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryRow {
|
||||
/// The rev closing the interaction, in decimal.
|
||||
pub id: String,
|
||||
/// The name a person gave it, or one derived from what it changed.
|
||||
pub label: String,
|
||||
/// Whether `label` was given by a person.
|
||||
pub named: bool,
|
||||
/// The tags standing on it, in name order.
|
||||
pub tags: Vec<String>,
|
||||
pub author: String,
|
||||
/// The author has no name on record, so `author` is a stand-in.
|
||||
pub anonymous: bool,
|
||||
/// The author is the person at this editor.
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
/// When the interaction entered history, in milliseconds since the Unix epoch, if its retirer recorded it.
|
||||
pub time: Option<f64>,
|
||||
pub deltas: usize,
|
||||
/// Branches leaving this interaction that are not on the line shown, each by its tip.
|
||||
pub branches: Vec<HistoryBranch>,
|
||||
/// Above the head: taken back, and redo would bring it back.
|
||||
pub undone: bool,
|
||||
/// On a followed branch and not on the head's line: no head reaches it.
|
||||
pub abandoned: bool,
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
/// The interaction's deltas, newest first, when expanded.
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
}
|
||||
|
||||
/// A branch leaving an interaction, named by its tip and what its newest interaction did.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryBranch {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// One delta of an expanded interaction.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryDeltaRow {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub color: String,
|
||||
pub time: Option<f64>,
|
||||
}
|
||||
|
||||
/// A person with ops in the room's hot log: their open or not yet retired work.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryProgressRow {
|
||||
/// What the work changes so far, in the words of the rows.
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub anonymous: bool,
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
pub ops: usize,
|
||||
/// Still being made, rather than closed and waiting to enter history.
|
||||
pub open: bool,
|
||||
}
|
||||
@@ -49,6 +49,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
IngestMessage::Ingest { data, action, mime_type, path } => {
|
||||
let data_type = DataType::detect(&data, &mime_type, path.as_deref());
|
||||
|
||||
let fresh_identity = matches!(action, IngestAction::OpenDemo);
|
||||
let placement = match action {
|
||||
IngestAction::ResourceInput {
|
||||
document_id,
|
||||
@@ -80,7 +81,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
}
|
||||
return;
|
||||
}
|
||||
IngestAction::Open => None,
|
||||
IngestAction::Open | IngestAction::OpenDemo => None,
|
||||
IngestAction::Import | IngestAction::Paste => Some((None, None)),
|
||||
IngestAction::DropOnCanvas { mouse } => Some((Some(mouse), None)),
|
||||
IngestAction::DropOnLayers { parent, insert_index } => Some((None, Some((parent, insert_index as usize)))),
|
||||
@@ -109,6 +110,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
document_name: name,
|
||||
document_path,
|
||||
content: data,
|
||||
fresh_identity,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
pub enum IngestAction {
|
||||
Open,
|
||||
/// Open a distributed file such as a demo artwork as a copy with its own document id, so its openers do not share a session room.
|
||||
OpenDemo,
|
||||
Import,
|
||||
Paste,
|
||||
DropOnCanvas {
|
||||
|
||||
@@ -4,10 +4,14 @@ mod portfolio_message_handler;
|
||||
pub mod document;
|
||||
pub mod document_migration;
|
||||
pub mod document_storage_io;
|
||||
#[cfg(target_family = "wasm")]
|
||||
mod document_store_owner;
|
||||
pub mod failed_documents;
|
||||
pub mod fonts;
|
||||
pub mod history;
|
||||
pub mod ingest;
|
||||
pub mod persistent_state;
|
||||
pub mod sync;
|
||||
pub mod utility_types;
|
||||
pub mod workspace;
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ use crate::messages::prelude::*;
|
||||
#[derive(Default, Debug, Clone, ExtractField)]
|
||||
pub struct PersistentStateMessageHandler {
|
||||
loaded: bool,
|
||||
/// Another tab owns the stored state, so this one writes none.
|
||||
read_only: bool,
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -22,6 +24,9 @@ impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for P
|
||||
responses.add(FrontendMessage::TriggerPersistenceReadState);
|
||||
}
|
||||
PersistentStateMessage::WriteState => {
|
||||
if self.read_only {
|
||||
return;
|
||||
}
|
||||
if !self.loaded && (state.documents.is_empty() && (state.workspace_layout == Some(WorkspacePanelLayout::default()) || state.workspace_layout.is_none())) {
|
||||
return;
|
||||
}
|
||||
@@ -42,4 +47,8 @@ impl PersistentStateMessageHandler {
|
||||
pub fn loaded(&self) -> bool {
|
||||
self.loaded
|
||||
}
|
||||
|
||||
pub fn set_read_only(&mut self) {
|
||||
self.read_only = true;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::history::HistoryMessage;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::sync::SyncMessage;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::prelude::*;
|
||||
use document_container::AnyContainer;
|
||||
@@ -21,10 +23,18 @@ pub enum PortfolioMessage {
|
||||
#[child]
|
||||
PersistentState(PersistentStateMessage),
|
||||
#[child]
|
||||
History(HistoryMessage),
|
||||
#[child]
|
||||
Sync(SyncMessage),
|
||||
#[child]
|
||||
Workspace(WorkspaceMessage),
|
||||
|
||||
// Messages
|
||||
Init,
|
||||
/// Whether this tab took the document store, or another tab has it and this one keeps its documents in memory.
|
||||
DocumentStoreClaimed {
|
||||
owned: bool,
|
||||
},
|
||||
DocumentPassMessage {
|
||||
document_id: DocumentId,
|
||||
message: DocumentMessage,
|
||||
@@ -74,6 +84,11 @@ pub enum PortfolioMessage {
|
||||
NewDocumentWithName {
|
||||
name: String,
|
||||
},
|
||||
/// Creates the document under a given id, so the sender can recognize it when it mounts.
|
||||
NewDocumentWithId {
|
||||
name: String,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
OpenLegacyDocumentFile {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
@@ -83,6 +98,8 @@ pub enum PortfolioMessage {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
/// Give the copy a document id of its own, so everyone opening the same distributed file does not share one session room.
|
||||
fresh_identity: bool,
|
||||
},
|
||||
DocumentFileLoaded {
|
||||
document_id: DocumentId,
|
||||
@@ -98,7 +115,6 @@ pub enum PortfolioMessage {
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
declarations: document_graph_storage::Declarations,
|
||||
},
|
||||
StorageUpdated,
|
||||
StorageAttached {
|
||||
document_id: DocumentId,
|
||||
#[serde(skip, default)]
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::application::{Environment, generate_uuid};
|
||||
use crate::consts::DEFAULT_DOCUMENT_NAME;
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState, SessionStatus};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledShortcut};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
@@ -14,7 +14,7 @@ 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,
|
||||
DocumentStoreHandle, attach_container, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, remove_stored_document,
|
||||
};
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -41,6 +41,8 @@ pub struct PortfolioMessageContext<'a> {
|
||||
pub animation: &'a AnimationMessageHandler,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
/// The icon name of the active tool, which the session shows beside this peer's pointer.
|
||||
pub current_tool_icon: String,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub timing_information: TimingInformation,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
@@ -57,6 +59,8 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
@@ -65,6 +69,8 @@ pub struct PortfolioMessageHandler {
|
||||
pending_opens: usize,
|
||||
restore_select: Option<DocumentId>,
|
||||
store_unavailable: bool,
|
||||
/// Another tab owns the document store, so this one keeps its documents in memory; see [`PortfolioMessage::DocumentStoreClaimed`].
|
||||
memory_only: bool,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -77,6 +83,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
animation,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
current_tool_icon,
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
viewport,
|
||||
@@ -131,6 +138,26 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
self.ingest.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::History(message) => {
|
||||
let context = HistoryMessageContext {
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::Sync(message) => {
|
||||
let context = SyncMessageContext {
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
resource_storage,
|
||||
preferences,
|
||||
ipp,
|
||||
viewport,
|
||||
current_tool_icon,
|
||||
};
|
||||
self.sync.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::Workspace(message) => {
|
||||
let context = WorkspaceMessageContext {
|
||||
has_active_document: self.active_document_id.is_some(),
|
||||
@@ -144,7 +171,15 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Tell frontend to load persistent preferences
|
||||
responses.add(FrontendMessage::TriggerLoadPreferences);
|
||||
|
||||
responses.add(PersistentStateMessage::ReadState);
|
||||
#[cfg(target_family = "wasm")]
|
||||
responses.add(async {
|
||||
PortfolioMessage::DocumentStoreClaimed {
|
||||
owned: super::document_store_owner::claim().await,
|
||||
}
|
||||
.into()
|
||||
});
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(PortfolioMessage::DocumentStoreClaimed { owned: true });
|
||||
|
||||
// Initialize the frontend with environment information
|
||||
responses.add(FrontendMessage::UpdatePlatform { platform: environment.into() });
|
||||
@@ -344,10 +379,22 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
responses.add(PersistentStateMessage::WriteState);
|
||||
}
|
||||
PortfolioMessage::DocumentStoreClaimed { owned } => {
|
||||
if owned {
|
||||
responses.add(PersistentStateMessage::ReadState);
|
||||
return;
|
||||
}
|
||||
// Nothing is restored, written to the store, or remembered for the next visit, and resources stay
|
||||
// uncollected, since the owning tab's documents use them too.
|
||||
log::warn!("Another tab has the stored documents open, so this tab keeps its documents in memory only");
|
||||
self.document_store = DocumentStoreHandle::default();
|
||||
self.memory_only = true;
|
||||
self.persistent_state.set_read_only();
|
||||
}
|
||||
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() || self.pending_opens > 0 || !self.loading_documents.is_empty() || self.store_unavailable || self.memory_only {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -359,6 +406,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
if let Some(storage) = document.storage() {
|
||||
used_resources.extend(storage.all_referenced_resource_hashes());
|
||||
}
|
||||
// A step taken back on undo names resources nothing else refers to until it is redone.
|
||||
used_resources.extend(document.retracted_resource_hashes());
|
||||
}
|
||||
used_resources.extend(self.fonts.used_resources());
|
||||
responses.add(ResourceStorageMessage::GarbageCollect {
|
||||
@@ -379,6 +428,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
PortfolioMessage::LoadPersistedState { state } => {
|
||||
if let Some(layout) = state.workspace_layout {
|
||||
self.workspace.panel_layout = layout;
|
||||
// A workspace without the Session panel gets it as a background tab beside Inspector, unless the user closed it.
|
||||
let panel_layout = &mut self.workspace.panel_layout;
|
||||
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
|
||||
match panel_layout.find_panel(PanelType::Inspector).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
|
||||
Some(group) => group.tabs.push(PanelType::Session),
|
||||
None => panel_layout.restore_panel(PanelType::Session),
|
||||
}
|
||||
}
|
||||
responses.add(WorkspaceMessage::UpdatePanelsLayout);
|
||||
|
||||
// Refill panels whose content was lost when the layout load remounted their frontend components
|
||||
@@ -427,6 +484,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
name: String::new(),
|
||||
path: None,
|
||||
is_saved: false,
|
||||
session: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -439,7 +497,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_id,
|
||||
resource_storage.resources_mut(),
|
||||
reset_node_definitions_on_open,
|
||||
!preferences.save_as_gdd,
|
||||
));
|
||||
}
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
@@ -467,8 +524,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
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);
|
||||
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
}
|
||||
None => {
|
||||
self.document_ids.retain(|id| *id != document_id);
|
||||
@@ -488,18 +545,23 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithName { name } => {
|
||||
responses.add_front(PortfolioMessage::NewDocumentWithId {
|
||||
name,
|
||||
document_id: DocumentId(generate_uuid()),
|
||||
});
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithId { name, document_id } => {
|
||||
let mut new_document = DocumentMessageHandler::default();
|
||||
new_document.name = self.resolve_document_name(name, None);
|
||||
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
if self.active_document().is_some() {
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
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.resources_mut(), responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::OpenLegacyDocumentFile {
|
||||
@@ -521,7 +583,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
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.load_document(document, document_id, resource_storage.resources_mut(), responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
responses.add(AppWindowMessage::Focus);
|
||||
}
|
||||
@@ -529,6 +591,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
fresh_identity,
|
||||
} => {
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
|
||||
@@ -541,9 +604,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
fresh_identity,
|
||||
resource_storage.resources_mut(),
|
||||
reset_node_definitions_on_open,
|
||||
!preferences.save_as_gdd,
|
||||
));
|
||||
}
|
||||
PortfolioMessage::DocumentFileLoaded {
|
||||
@@ -566,19 +629,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
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);
|
||||
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
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,
|
||||
@@ -595,7 +649,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
};
|
||||
document.container = Some(container);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
self.save_if_needed(document_id, responses);
|
||||
}
|
||||
PortfolioMessage::NextDocument => {
|
||||
@@ -840,6 +894,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
|
||||
responses.add(ToolMessage::InitTools);
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
responses.add(NodeGraphMessage::Init);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
@@ -861,10 +916,19 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
if !document.is_loaded {
|
||||
document.is_loaded = true;
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
responses.add(InspectorMessage::Clear);
|
||||
}
|
||||
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DeferMessage::AfterGraphRun {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
}
|
||||
.into(),
|
||||
],
|
||||
});
|
||||
}
|
||||
PortfolioMessage::RenameDocument { new_name } => {
|
||||
let resolved_name = self.resolve_document_name(new_name, self.active_document_id);
|
||||
@@ -1070,6 +1134,8 @@ impl PortfolioMessageHandler {
|
||||
persistent_state: Default::default(),
|
||||
fonts: Default::default(),
|
||||
ingest: Default::default(),
|
||||
history: Default::default(),
|
||||
sync: Default::default(),
|
||||
executor,
|
||||
selection_mode: Default::default(),
|
||||
reset_node_definitions_on_open: Default::default(),
|
||||
@@ -1078,6 +1144,7 @@ impl PortfolioMessageHandler {
|
||||
pending_opens: Default::default(),
|
||||
restore_select: Default::default(),
|
||||
store_unavailable: Default::default(),
|
||||
memory_only: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1156,7 +1223,7 @@ 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, resources: ResourcesHandle, 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);
|
||||
@@ -1173,6 +1240,9 @@ impl PortfolioMessageHandler {
|
||||
|
||||
self.documents.insert(document_id, new_document);
|
||||
|
||||
// Resolved on load rather than on first activation, so a document saved without ever being viewed still embeds its resources
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
|
||||
if self.active_document().is_some() {
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
responses.add(ToolMessage::DeactivateTools);
|
||||
@@ -1185,7 +1255,7 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
|
||||
if self.documents[&document_id].container.is_none() {
|
||||
responses.add(attach_container(self.document_store.clone(), document_id, resources, legacy_only));
|
||||
responses.add(attach_container(self.document_store.clone(), document_id, resources));
|
||||
} else {
|
||||
self.save_if_needed(document_id, responses);
|
||||
}
|
||||
@@ -1200,12 +1270,30 @@ impl PortfolioMessageHandler {
|
||||
declarations: Declarations,
|
||||
resource_storage: &ResourceStorageMessageHandler,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
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();
|
||||
let Some(document) = self.documents.get_mut(&document_id) else { return };
|
||||
let user = document_graph_storage::UserId(preferences.user_id);
|
||||
match gdd {
|
||||
Some(mut gdd) => {
|
||||
// The copy follows the person at this device, whoever wrote it last.
|
||||
if let Err(error) = gdd.set_user(user) {
|
||||
log::error!("Setting the user of {document_id:?} failed: {error}");
|
||||
}
|
||||
document.set_storage(*gdd, declarations, resource_storage.resources_mut().storage());
|
||||
document.require_whole_document_stage();
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
}
|
||||
// Recovered from its storage alone, the document already holds it.
|
||||
None => {
|
||||
let Some(storage) = document.storage_mut() else { return };
|
||||
if let Err(error) = storage.set_user(user) {
|
||||
log::error!("Setting the user of {document_id:?} failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
responses.add(SyncMessage::StorageMounted { document_id });
|
||||
}
|
||||
|
||||
fn save_if_needed(&self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
@@ -1254,6 +1342,11 @@ impl PortfolioMessageHandler {
|
||||
name: document.name.clone(),
|
||||
path: document.path.clone(),
|
||||
is_saved: document.is_saved(),
|
||||
session: document.storage().and_then(|gdd| match (gdd.role().is_some(), gdd.is_shared()) {
|
||||
(true, _) => Some(SessionStatus::Connected),
|
||||
(false, true) => Some(SessionStatus::Disconnected),
|
||||
(false, false) => None,
|
||||
}),
|
||||
})
|
||||
} else {
|
||||
self.loading_documents.get(&document_id).cloned()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! How a person is shown wherever the editor names one: the stand-in for someone unnamed, and the colour that
|
||||
//! follows a user id through the cursors, the Session panel and the History panel.
|
||||
|
||||
use document_graph_storage::UserId;
|
||||
|
||||
/// A stand-in for a person who has not given a name, the same on every device of theirs and everywhere
|
||||
/// in the room, since it comes from the user id alone.
|
||||
pub(crate) fn anonymous_name(user: UserId) -> String {
|
||||
let index = (user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40) as usize % ANONYMOUS_ANIMALS.len();
|
||||
format!("Anonymous {}", ANONYMOUS_ANIMALS[index])
|
||||
}
|
||||
|
||||
pub(crate) const ANONYMOUS_ANIMALS: [&str; 64] = [
|
||||
"Alligator",
|
||||
"Anteater",
|
||||
"Armadillo",
|
||||
"Axolotl",
|
||||
"Badger",
|
||||
"Bat",
|
||||
"Beaver",
|
||||
"Buffalo",
|
||||
"Camel",
|
||||
"Capybara",
|
||||
"Chameleon",
|
||||
"Cheetah",
|
||||
"Chinchilla",
|
||||
"Chipmunk",
|
||||
"Cormorant",
|
||||
"Coyote",
|
||||
"Crow",
|
||||
"Dingo",
|
||||
"Dolphin",
|
||||
"Duck",
|
||||
"Elephant",
|
||||
"Ferret",
|
||||
"Fox",
|
||||
"Frog",
|
||||
"Giraffe",
|
||||
"Gopher",
|
||||
"Grizzly",
|
||||
"Hedgehog",
|
||||
"Heron",
|
||||
"Hippo",
|
||||
"Hyena",
|
||||
"Ibex",
|
||||
"Iguana",
|
||||
"Jackal",
|
||||
"Jaguar",
|
||||
"Kangaroo",
|
||||
"Koala",
|
||||
"Kraken",
|
||||
"Lemur",
|
||||
"Leopard",
|
||||
"Liger",
|
||||
"Llama",
|
||||
"Manatee",
|
||||
"Mink",
|
||||
"Monkey",
|
||||
"Moose",
|
||||
"Narwhal",
|
||||
"Nyan Cat",
|
||||
"Orangutan",
|
||||
"Otter",
|
||||
"Panda",
|
||||
"Penguin",
|
||||
"Platypus",
|
||||
"Python",
|
||||
"Quagga",
|
||||
"Rabbit",
|
||||
"Raccoon",
|
||||
"Rhino",
|
||||
"Sheep",
|
||||
"Shrew",
|
||||
"Skunk",
|
||||
"Squirrel",
|
||||
"Tiger",
|
||||
"Turtle",
|
||||
];
|
||||
|
||||
/// A colour for a person derived from their user id, so every peer sees the same one without anything on the
|
||||
/// wire, and one person has one colour across their tabs and in the history.
|
||||
pub(crate) fn user_color(user: UserId) -> String {
|
||||
let hue = (user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) % 360;
|
||||
let (h, s, l): (f64, f64, f64) = (hue as f64 / 60., 0.65, 0.5);
|
||||
let c = (1. - (2. * l - 1.).abs()) * s;
|
||||
let x = c * (1. - (h % 2. - 1.).abs());
|
||||
let m = l - c / 2.;
|
||||
let (r, g, b) = match h as u32 {
|
||||
0 => (c, x, 0.),
|
||||
1 => (x, c, 0.),
|
||||
2 => (0., c, x),
|
||||
3 => (0., x, c),
|
||||
4 => (x, 0., c),
|
||||
_ => (c, 0., x),
|
||||
};
|
||||
let channel = |value: f64| ((value + m) * 255.).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", channel(r), channel(g), channel(b))
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub(crate) mod identity;
|
||||
mod sync_message;
|
||||
mod sync_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
|
||||
pub(crate) use sync_message_handler::now_ms;
|
||||
#[doc(inline)]
|
||||
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
|
||||
@@ -0,0 +1,38 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use peer_transport::TransportPeerId;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Sync)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SyncMessage {
|
||||
/// Host the active document in the room every copy of it shares, and hand the frontend a link for others.
|
||||
Share,
|
||||
/// Open a new document that follows the session behind `token`.
|
||||
Join { token: String },
|
||||
/// Disconnect the active document from its room; editing goes on alone until the next share.
|
||||
Leave,
|
||||
/// Leave the room and host the active document as a new session with its own link, keeping its content and
|
||||
/// history; the others keep the room they are in.
|
||||
Fork,
|
||||
/// Send the Session panel's layout for the active document.
|
||||
RefreshPanel,
|
||||
/// Per frame: apply what peers sent and answer their requests.
|
||||
Poll,
|
||||
/// A packet arrived for a document's room: poll it now rather than at the next frame. `generation`
|
||||
/// names the connection it was armed for, so a wake from an earlier connection is ignored.
|
||||
Wake { document_id: DocumentId, generation: u32 },
|
||||
/// A document's working copy mounted; attaches it to a pending join.
|
||||
StorageMounted { document_id: DocumentId },
|
||||
/// The transport loop of a document's session ended. `generation` names the connection it drove, so the end of
|
||||
/// a connection the document already left, or replaced by a fork, is nothing to act on.
|
||||
Disconnected { document_id: DocumentId, generation: u32 },
|
||||
/// A declaration a remote change names, read from the byte store to be decoded; `None` when the store did not hold it.
|
||||
DeclarationLoaded { document_id: DocumentId, hash: ResourceHash, bytes: Option<Vec<u8>> },
|
||||
/// A resource a peer asked for was read from the byte store.
|
||||
ResourceLoaded {
|
||||
document_id: DocumentId,
|
||||
to: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,775 @@
|
||||
use super::identity::{anonymous_name, user_color};
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendRemoteCursor;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use crate::messages::viewport::Position;
|
||||
use document_graph_storage::{HistoryMetadata, UserId, user_attr};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::{LoadResource, ResourceHash};
|
||||
use peer_transport::{CursorPosition, CursorSpace, DEFAULT_SIGNALING_SERVER, Event, Incoming, RemotePeer, Role, Room, SessionToken, SyncTarget};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct SyncMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub current_tool_icon: String,
|
||||
}
|
||||
|
||||
/// Drives every document's collaborative session: attaches transports, polls them once per frame and as
|
||||
/// packets arrive, and turns remote changes into interface rebuilds.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct SyncMessageHandler {
|
||||
/// The session link waiting for the document created to join it.
|
||||
pending_join: Option<(DocumentId, SessionToken)>,
|
||||
polling: bool,
|
||||
/// Each connected document's room inbox, tagged with the connection it belongs to. One wake future is in
|
||||
/// flight per entry: it resolves to a `Wake`, which polls and arms the next one.
|
||||
incoming: HashMap<DocumentId, (u32, Incoming)>,
|
||||
connections: u32,
|
||||
/// Documents whose registry changed remotely since their interface was last rebuilt.
|
||||
dirty: HashSet<DocumentId>,
|
||||
/// Documents that just took the host's state on: once their interface follows and the graph has run, the
|
||||
/// viewport is fitted to the document, so a guest sees what it joined rather than an empty canvas.
|
||||
fit_after_sync: HashSet<DocumentId>,
|
||||
/// When each document connected to its room still undecided, so the host role is taken once no host has
|
||||
/// greeted it for the grace period.
|
||||
undecided_since: HashMap<DocumentId, f64>,
|
||||
blocked_reason: HashMap<DocumentId, String>,
|
||||
/// Declarations being read from the byte store to be decoded, so a document waiting on them asks once.
|
||||
decoding: HashSet<(DocumentId, ResourceHash)>,
|
||||
/// The pointer position last sent for each connected document, so one is sent only when it moved.
|
||||
last_cursor: HashMap<DocumentId, Option<CursorPosition>>,
|
||||
/// The other peers' pointers over the node graph as last sent to the frontend.
|
||||
graph_cursors: Vec<FrontendRemoteCursor>,
|
||||
document_cursors: Vec<FrontendRemoteCursor>,
|
||||
/// When each document whose transport went down is next to be reconnected.
|
||||
reconnect_at: HashMap<DocumentId, f64>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler {
|
||||
fn process_message(&mut self, message: SyncMessage, responses: &mut VecDeque<Message>, context: SyncMessageContext) {
|
||||
let SyncMessageContext {
|
||||
documents,
|
||||
active_document_id,
|
||||
resource_storage,
|
||||
preferences,
|
||||
ipp,
|
||||
viewport,
|
||||
current_tool_icon,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
SyncMessage::Share => {
|
||||
let Some(document) = active_document_id.and_then(|id| documents.get_mut(&id)) else { return };
|
||||
let Some(gdd) = document.storage_mut() else {
|
||||
log::warn!("Cannot share a document before its working copy is mounted");
|
||||
return;
|
||||
};
|
||||
if gdd.role().is_some() {
|
||||
return;
|
||||
}
|
||||
// Guests learn the name from the registry.
|
||||
document.stage_name_attribute();
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
|
||||
let document_id = active_document_id.expect("checked above");
|
||||
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
|
||||
// The panel shows the link; the clipboard gets it too, so sharing stays one step.
|
||||
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
|
||||
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
|
||||
self.start_polling(responses);
|
||||
}
|
||||
SyncMessage::Join { token } => {
|
||||
if token.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let token = match token.parse::<SessionToken>() {
|
||||
Ok(token) => token,
|
||||
Err(error) => {
|
||||
log::warn!("Ignoring session link: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
self.pending_join = Some((document_id, token));
|
||||
responses.add(PortfolioMessage::NewDocumentWithId {
|
||||
name: "Shared session".into(),
|
||||
document_id,
|
||||
});
|
||||
}
|
||||
SyncMessage::StorageMounted { document_id } => {
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
// Retirement runs on the frame tick, so every document polls, shared or not.
|
||||
self.start_polling(responses);
|
||||
if let Some((_, token)) = self.pending_join.take_if(|(join_id, _)| *join_id == document_id) {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let incoming = room.incoming();
|
||||
gdd.join(room, UserId(preferences.user_id));
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
|
||||
self.attach(document_id, incoming, responses);
|
||||
responses.add(driver_future(document_id, self.connections, driver));
|
||||
refresh_session_views(responses);
|
||||
self.start_polling(responses);
|
||||
} else if gdd.is_shared() && gdd.role().is_none() {
|
||||
// The document was in its room when it was last persisted: a reload rejoins on its own.
|
||||
self.connect_document(document_id, gdd, preferences, responses);
|
||||
} else {
|
||||
// The panel may have shown the document still mounting.
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
}
|
||||
SyncMessage::Leave => {
|
||||
let Some(document_id) = active_document_id else { return };
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
gdd.leave();
|
||||
self.incoming.remove(&document_id);
|
||||
self.last_cursor.remove(&document_id);
|
||||
self.reconnect_at.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::Fork => {
|
||||
let Some(document_id) = active_document_id else { return };
|
||||
let Some(document) = documents.get_mut(&document_id) else { return };
|
||||
document.stage_name_attribute();
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
// The room is derived from the manifest's document id, so a fresh id is a fresh room. A guest
|
||||
// already rewrites the id when it joins, and the working copy's directory is keyed by the editor's
|
||||
// own id, so nothing moves on disk.
|
||||
gdd.leave();
|
||||
self.incoming.remove(&document_id);
|
||||
self.last_cursor.remove(&document_id);
|
||||
if let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = crate::application::generate_uuid()) {
|
||||
log::error!("Forking the session failed: {error}");
|
||||
refresh_session_views(responses);
|
||||
return;
|
||||
}
|
||||
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
|
||||
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
|
||||
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
|
||||
self.start_polling(responses);
|
||||
}
|
||||
SyncMessage::Disconnected { document_id, generation } => {
|
||||
if self.incoming.get(&document_id).is_none_or(|(current, _)| *current != generation) {
|
||||
return;
|
||||
}
|
||||
// The transport went down under a document that meant to stay in its room: it stays shared, so
|
||||
// the panel shows it disconnected and offers to reconnect, and a reopen reconnects on its own.
|
||||
if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) {
|
||||
gdd.disconnect();
|
||||
self.reconnect_at.insert(document_id, now_ms() + RECONNECT_AFTER_MS);
|
||||
}
|
||||
self.incoming.remove(&document_id);
|
||||
self.last_cursor.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::RefreshPanel => {
|
||||
let layout = session_panel_layout(documents, active_document_id, preferences);
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout,
|
||||
layout_target: LayoutTarget::SessionPanel,
|
||||
});
|
||||
}
|
||||
SyncMessage::Poll | SyncMessage::Wake { .. } => {
|
||||
// A wake names the connection it was armed for; one from a connection since left is nothing to act on.
|
||||
let woken = match message {
|
||||
SyncMessage::Wake { document_id, generation } => {
|
||||
if self.incoming.get(&document_id).is_none_or(|(current, _)| *current != generation) {
|
||||
return;
|
||||
}
|
||||
Some(document_id)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let resources = resource_storage.resources_mut();
|
||||
for (&document_id, document) in documents.iter_mut() {
|
||||
// Closed transactions retire by the working copy's policy, once enough have waited long enough, never on a gesture.
|
||||
let idle = document.network_interface.transaction_status() == TransactionStatus::Finished;
|
||||
if let Some(gdd) = document.storage_mut()
|
||||
&& let Err(error) = gdd.retire_due(now_ms(), idle)
|
||||
{
|
||||
log::error!("Retirement failed: {error}");
|
||||
}
|
||||
// Record the person behind this copy in the document's users, so whoever opens it later can name every step's author.
|
||||
if let Some(gdd) = document.storage_mut() {
|
||||
record_profile(gdd, preferences);
|
||||
}
|
||||
// A document whose transport went down tries again after a pause, for as long as it is meant to be shared.
|
||||
if self.reconnect_at.get(&document_id).is_some_and(|&due| now_ms() >= due)
|
||||
&& let Some(gdd) = document.storage_mut()
|
||||
{
|
||||
self.reconnect_at.remove(&document_id);
|
||||
if gdd.is_shared() && gdd.role().is_none() {
|
||||
log::info!("Reconnecting {document_id:?} to its session");
|
||||
self.connect_document(document_id, gdd, preferences, responses);
|
||||
}
|
||||
}
|
||||
if document.storage().is_none_or(|gdd| gdd.role().is_none()) {
|
||||
continue;
|
||||
}
|
||||
// A document without a host, connected that way or left that way by a host that went before
|
||||
// syncing it, takes the role itself once no host has greeted it for the grace period.
|
||||
if document.storage().is_some_and(|gdd| gdd.role() == Some(peer_transport::Role::Undecided)) {
|
||||
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
|
||||
if now_ms() - since >= ROLE_GRACE_MS
|
||||
&& let Some(gdd) = document.storage_mut()
|
||||
&& gdd.decide_role().is_some()
|
||||
{
|
||||
self.undecided_since.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
} else {
|
||||
self.undecided_since.remove(&document_id);
|
||||
}
|
||||
// Stage, and so broadcast, what the interface recorded since the last frame, so each movement reaches peers live.
|
||||
document.stage_pending_edits(&resources);
|
||||
// Presence rides outside the causal broadcast: the name whenever it changed, and the pointer
|
||||
// over the active document once per frame when it moved, `None` for every other document.
|
||||
let cursor = (Some(document_id) == active_document_id)
|
||||
.then(|| cursor_position(document, ipp, viewport, ¤t_tool_icon))
|
||||
.flatten();
|
||||
let Some(gdd) = document.storage_mut() else { continue };
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
if self.last_cursor.get(&document_id) != Some(&cursor) {
|
||||
match gdd.send_cursor(cursor.clone()) {
|
||||
Ok(()) => {
|
||||
self.last_cursor.insert(document_id, cursor);
|
||||
}
|
||||
Err(error) => log::warn!("Sending the pointer position failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
let events = gdd.poll_peers();
|
||||
// Taken every poll rather than on an event: a full sync a hello triggers can replace the
|
||||
// registry with no change event to announce it.
|
||||
let changes = gdd.take_remote_changes();
|
||||
if !changes.is_empty() {
|
||||
document.pending_remote.extend(changes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
for event in events {
|
||||
match event {
|
||||
Event::Synced => {
|
||||
log::debug!("Join handshake: synced, applying the host's state");
|
||||
refresh_session_views(responses);
|
||||
self.dirty.insert(document_id);
|
||||
self.fit_after_sync.insert(document_id);
|
||||
}
|
||||
Event::Changed => {
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
Event::ResourceRequested { from, hash } => {
|
||||
log::debug!("Peer asked for resource {hash}");
|
||||
responses.add(load_resource_future(document_id, from, hash, resources.clone()));
|
||||
}
|
||||
// The replica already put the bytes in the byte store; only the decoded form is missing.
|
||||
Event::ResourceReceived { hash, bytes } => {
|
||||
log::debug!("Received resource {hash} ({} bytes)", bytes.len());
|
||||
document.cache_declaration_bytes(hash, &bytes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
Event::RoleChanged { role } => {
|
||||
log::debug!("Session role is now {role:?}");
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
Event::PeerJoined { .. } | Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
|
||||
Event::MetadataChanged => {
|
||||
refresh_session_views(responses);
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
// Cursors are gathered afresh below every poll, so a move needs no action of its own.
|
||||
Event::CursorMoved { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The other peers' pointers over the node graph go to the frontend as viewport points, like the box
|
||||
// selection, whenever they change; the canvas overlay draws the ones over the document.
|
||||
let graph_cursors = active_document_id
|
||||
.and_then(|id| documents.get(&id))
|
||||
.map(|document| graph_cursors(document, preferences))
|
||||
.unwrap_or_default();
|
||||
if graph_cursors != self.graph_cursors {
|
||||
self.graph_cursors = graph_cursors.clone();
|
||||
responses.add(FrontendMessage::UpdateNodeGraphCursors { cursors: graph_cursors });
|
||||
}
|
||||
let document_cursors = active_document_id
|
||||
.and_then(|id| documents.get(&id))
|
||||
.map(|document| document_cursors(document, preferences))
|
||||
.unwrap_or_default();
|
||||
if document_cursors != self.document_cursors {
|
||||
self.document_cursors = document_cursors.clone();
|
||||
responses.add(FrontendMessage::UpdateDocumentCursors { cursors: document_cursors });
|
||||
}
|
||||
|
||||
// Apply only once every referenced resource is in the app cache, and never underneath an
|
||||
// open transaction, whose tool state names nodes a peer may have removed.
|
||||
for document_id in self.dirty.clone() {
|
||||
let Some(document) = documents.get_mut(&document_id) else {
|
||||
self.dirty.remove(&document_id);
|
||||
continue;
|
||||
};
|
||||
let Some(gdd) = document.storage() else { continue };
|
||||
let missing = SyncTarget::missing_resources(gdd).len();
|
||||
let transaction = document.network_interface.transaction_status();
|
||||
if missing > 0 || transaction != TransactionStatus::Finished {
|
||||
let reason = format!("missing {missing} transaction {transaction:?}");
|
||||
if self.blocked_reason.get(&document_id) != Some(&reason) {
|
||||
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
|
||||
self.blocked_reason.insert(document_id, reason);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Every resource is on hand, but a declaration held since an earlier session was never received from
|
||||
// a peer and so never decoded: read it from the byte store, and apply once it is cached.
|
||||
let undecoded = document.undecoded_declaration_hashes();
|
||||
if !undecoded.is_empty() {
|
||||
let reason = format!("decoding {} held declarations", undecoded.len());
|
||||
if self.blocked_reason.get(&document_id) != Some(&reason) {
|
||||
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
|
||||
self.blocked_reason.insert(document_id, reason);
|
||||
}
|
||||
for hash in undecoded {
|
||||
if self.decoding.insert((document_id, hash)) {
|
||||
responses.add(decode_declaration_future(document_id, hash, resources.clone()));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.blocked_reason.remove(&document_id);
|
||||
|
||||
// Stays dirty while a declaration the changes need is still on its way.
|
||||
if document.apply_remote_changes(responses) {
|
||||
self.dirty.remove(&document_id);
|
||||
if document.adopt_name_from_storage() {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
if self.fit_after_sync.remove(&document_id) && Some(document_id) == active_document_id {
|
||||
log::debug!("Join handshake: the host's state is applied, fitting the viewport after the graph runs");
|
||||
// The bounds come from the render, so the fit waits for the graph to run on the new document.
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
// The registry names resources this peer may still have to fetch or resolve.
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
}
|
||||
|
||||
// The inbox was drained above; the next arrival wakes the next poll.
|
||||
if let Some(document_id) = woken {
|
||||
self.arm(document_id, responses);
|
||||
}
|
||||
}
|
||||
SyncMessage::DeclarationLoaded { document_id, hash, bytes } => {
|
||||
let Some(bytes) = bytes else {
|
||||
// Stays in `decoding` so it is not asked for again every frame; the document waits on it.
|
||||
log::warn!("Declaration {hash} is recorded as held but the byte store has no bytes for it");
|
||||
return;
|
||||
};
|
||||
self.decoding.remove(&(document_id, hash));
|
||||
let Some(document) = documents.get_mut(&document_id) else { return };
|
||||
log::debug!("Decoded held declaration {hash} ({} bytes)", bytes.len());
|
||||
document.cache_declaration_bytes(hash, &bytes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => {
|
||||
log::debug!("Sending resource {hash} ({} bytes)", bytes.len());
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = gdd.send_resource(to, hash, bytes) {
|
||||
log::warn!("Failed to send resource {hash} to a peer: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(SyncMessageDiscriminant; Share, Leave);
|
||||
}
|
||||
|
||||
impl SyncMessageHandler {
|
||||
/// Connect `document_id`'s working copy to the room every copy of the document shares, and hand the
|
||||
/// frontend the link. Returns the token, `None` when the connection could not be set up.
|
||||
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut document_format::GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id);
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let incoming = room.incoming();
|
||||
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
|
||||
log::error!("Connecting to the session failed: {error}");
|
||||
return None;
|
||||
}
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
self.undecided_since.insert(document_id, now_ms());
|
||||
self.reconnect_at.remove(&document_id);
|
||||
self.attach(document_id, incoming, responses);
|
||||
responses.add(driver_future(document_id, self.connections, driver));
|
||||
refresh_session_views(responses);
|
||||
self.start_polling(responses);
|
||||
Some(token)
|
||||
}
|
||||
|
||||
/// Poll `document_id`'s room as packets arrive, not only per frame: a hidden browser tab gets about one frame a second,
|
||||
/// which would delay each step of a join by that. The wake rides on the editor's future plumbing, so desktop works alike.
|
||||
fn attach(&mut self, document_id: DocumentId, incoming: Incoming, responses: &mut VecDeque<Message>) {
|
||||
self.connections += 1;
|
||||
self.incoming.insert(document_id, (self.connections, incoming));
|
||||
self.arm(document_id, responses);
|
||||
}
|
||||
|
||||
/// Put one wake future in flight for `document_id`'s current connection.
|
||||
fn arm(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
let Some((generation, incoming)) = self.incoming.get(&document_id).cloned() else { return };
|
||||
let future = async move {
|
||||
match incoming.wait().await {
|
||||
true => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Wake { document_id, generation })),
|
||||
// The room's loop ended; its driver reports the disconnection.
|
||||
false => Message::NoOp,
|
||||
}
|
||||
};
|
||||
responses.add(future);
|
||||
}
|
||||
|
||||
fn start_polling(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if self.polling {
|
||||
return;
|
||||
}
|
||||
self.polling = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(SyncMessage::Poll.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn driver_future(document_id: DocumentId, generation: u32, driver: peer_transport::MessageLoopFuture) -> Message {
|
||||
let future = async move {
|
||||
if let Err(error) = driver.await {
|
||||
log::warn!("Session transport for {document_id:?} ended: {error}");
|
||||
}
|
||||
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Disconnected { document_id, generation }))
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
/// Read a declaration the byte store already holds, so it can be decoded for a remote change that names it.
|
||||
fn decode_declaration_future(document_id: DocumentId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
|
||||
let future = async move {
|
||||
let bytes = resources.load(hash).await.map(|resource| resource.as_ref().to_vec());
|
||||
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::DeclarationLoaded { document_id, hash, bytes }))
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
fn load_resource_future(document_id: DocumentId, to: peer_transport::TransportPeerId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
|
||||
let future = async move {
|
||||
match resources.load(hash).await {
|
||||
Some(resource) => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceLoaded {
|
||||
document_id,
|
||||
to,
|
||||
hash,
|
||||
bytes: resource.as_ref().to_vec(),
|
||||
})),
|
||||
None => {
|
||||
log::warn!("A peer asked for resource {hash} which is not in the byte store");
|
||||
Message::NoOp
|
||||
}
|
||||
}
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
/// How long a peer that connected to an empty-looking room waits for a host's hello before it takes the
|
||||
/// role itself.
|
||||
const ROLE_GRACE_MS: f64 = 1_500.;
|
||||
|
||||
/// A monotonic-enough millisecond clock for the retirement policy, which only ever compares differences.
|
||||
pub(crate) fn now_ms() -> f64 {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
js_sys::Date::now()
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|elapsed| elapsed.as_secs_f64() * 1000.)
|
||||
.unwrap_or(0.)
|
||||
}
|
||||
}
|
||||
|
||||
/// The session state changed: the document tabs show it as a circle and the Session panel in full.
|
||||
fn refresh_session_views(responses: &mut VecDeque<Message>) {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
|
||||
/// The Session panel for the active document: its state in words, the join link, the peers, and the actions
|
||||
/// that apply in that state.
|
||||
fn session_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
|
||||
let heading = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).bold(true).widget_instance()]);
|
||||
let note = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).multiline(true).widget_instance()]);
|
||||
let user_name = preferences.user_name.as_str();
|
||||
// The name and the cursor switch are preferences, so they are the same in every session and asked for once.
|
||||
let name_row = || {
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new("Your name").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(user_name)
|
||||
.placeholder(anonymous_name(UserId(preferences.user_id)))
|
||||
.on_update(|input: &TextInput| PreferencesMessage::UserName { name: input.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
])
|
||||
};
|
||||
let cursors_row = || {
|
||||
let checkbox_id = CheckboxId::new();
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new("Show cursors")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(90))
|
||||
.for_checkbox(checkbox_id)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.show_remote_cursors)
|
||||
.tooltip_description("Draw the other peers' pointers over the document.")
|
||||
.on_update(|checkbox: &CheckboxInput| PreferencesMessage::ShowRemoteCursors { enabled: checkbox.checked }.into())
|
||||
.for_label(checkbox_id)
|
||||
.widget_instance(),
|
||||
])
|
||||
};
|
||||
|
||||
let Some(document) = active_document_id.and_then(|id| documents.get(&id)) else {
|
||||
return Layout(vec![note("Open a document to share it.")]);
|
||||
};
|
||||
let Some(gdd) = document.storage() else {
|
||||
return Layout(vec![name_row(), cursors_row(), note("The document's working copy is still being mounted.")]);
|
||||
};
|
||||
|
||||
let fork = || {
|
||||
TextButton::new("Fork")
|
||||
.tooltip_label("Fork the session")
|
||||
.tooltip_description("Leave this room and host the document as a new session with its own link. The others keep the room they are in.")
|
||||
.on_commit(|_| SyncMessage::Fork.into())
|
||||
.widget_instance()
|
||||
};
|
||||
// The same shape in every state: the state, the actions that apply in it, then the detail.
|
||||
let (state, actions, detail) = match gdd.role() {
|
||||
None if gdd.is_shared() => (
|
||||
"Disconnected, reconnecting",
|
||||
vec![
|
||||
TextButton::new("Reconnect").icon("Link").emphasized(true).on_commit(|_| SyncMessage::Share.into()).widget_instance(),
|
||||
TextButton::new("Stop Sharing").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
|
||||
fork(),
|
||||
],
|
||||
note("The connection to the session was lost. The editor keeps trying to reconnect, and the document stays editable meanwhile."),
|
||||
),
|
||||
None => (
|
||||
"Not shared",
|
||||
vec![
|
||||
TextButton::new("Share Live Session")
|
||||
.icon("Link")
|
||||
.emphasized(true)
|
||||
.on_commit(|_| SyncMessage::Share.into())
|
||||
.widget_instance(),
|
||||
],
|
||||
LayoutGroup::column(vec![
|
||||
TextLabel::new("Share this document to edit it live with others. Everyone who opens the link works on the same document.")
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
),
|
||||
Some(role) => {
|
||||
let live = role == Role::Host || (role == Role::Guest && gdd.is_synced());
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id).to_string();
|
||||
let copy_token = token.clone();
|
||||
let bare_token = token.clone();
|
||||
(
|
||||
if live { "Live session" } else { "Connecting" },
|
||||
vec![
|
||||
TextButton::new("Copy Link")
|
||||
.icon("Copy")
|
||||
.emphasized(true)
|
||||
.on_commit(move |_| FrontendMessage::TriggerSessionLinkCopy { token: copy_token.clone() }.into())
|
||||
.widget_instance(),
|
||||
TextButton::new("Disconnect").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
|
||||
fork(),
|
||||
],
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(token)
|
||||
.monospace(true)
|
||||
.selectable(true)
|
||||
.tooltip_label("Session")
|
||||
.tooltip_description("Opening the editor with this session in the link joins the room.")
|
||||
.widget_instance(),
|
||||
// The text itself, for the CLI or a message where a link is not wanted; the label is selectable but the
|
||||
// editor owns the copy shortcut.
|
||||
IconButton::new("Copy", 24)
|
||||
.tooltip_label("Copy Session Token")
|
||||
.on_update(move |_| FrontendMessage::TriggerClipboardWrite { content: bare_token.clone() }.into())
|
||||
.widget_instance(),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut groups = vec![name_row(), cursors_row(), heading(state), LayoutGroup::row(actions), detail];
|
||||
if gdd.role().is_none() && !gdd.is_shared() {
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Join a session").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new("")
|
||||
.placeholder("Paste a link")
|
||||
.tooltip_description("Opens the shared document in a new tab, following the session behind the link.")
|
||||
.on_update(|input: &TextInput| SyncMessage::Join { token: input.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
}
|
||||
|
||||
if gdd.role().is_some() {
|
||||
let mut peers = gdd.peers();
|
||||
peers.sort_by_key(|remote| remote.peer);
|
||||
groups.push(heading(&format!("In the session ({})", peers.len() + 1)));
|
||||
let me = match user_name.is_empty() {
|
||||
true => anonymous_name(UserId(preferences.user_id)),
|
||||
false => user_name.to_string(),
|
||||
};
|
||||
groups.push(peer_row(&format!("{me} (you)"), user_name.is_empty()));
|
||||
let metadata = gdd.metadata();
|
||||
groups.extend(peers.iter().map(|remote| peer_row(&display_name(remote, metadata), is_anonymous(remote, metadata))));
|
||||
}
|
||||
Layout(groups)
|
||||
}
|
||||
|
||||
/// One peer in the list; an anonymous one shows its stand-in name in italics.
|
||||
fn peer_row(name: &str, anonymous: bool) -> LayoutGroup {
|
||||
LayoutGroup::row(vec![TextLabel::new(name).italic(anonymous).widget_instance()])
|
||||
}
|
||||
|
||||
/// Put this user's display name on the document's record of its users. An empty name is recorded only to clear one on record.
|
||||
fn record_profile(gdd: &mut document_format::GddV1, preferences: &PreferencesMessageHandler) {
|
||||
let name = preferences.user_name.trim();
|
||||
let user = UserId(preferences.user_id);
|
||||
if name.is_empty() && gdd.metadata().user_name(user).is_none() {
|
||||
return;
|
||||
}
|
||||
if let Err(error) = gdd.record_user_attribute(user, user_attr::NAME, serde_json::Value::from(name), now_ms()) {
|
||||
log::warn!("Recording the display name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the room this peer's display name; a no-op when it has not changed.
|
||||
fn announce_name(gdd: &mut document_format::GddV1, name: &str) {
|
||||
if let Err(error) = gdd.set_name(name) {
|
||||
log::warn!("Announcing the display name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer while it is over the viewport, in the space it is over: the node graph's network when the
|
||||
/// graph is open, the document otherwise. Rounded so jitter below a hundredth of a unit sends nothing.
|
||||
fn cursor_position(document: &DocumentMessageHandler, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler, tool_icon: &str) -> Option<CursorPosition> {
|
||||
let mouse = ipp.mouse.position;
|
||||
let size = viewport.size();
|
||||
if mouse.x < 0. || mouse.y < 0. || mouse.x > size.x() || mouse.y > size.y() {
|
||||
return None;
|
||||
}
|
||||
let (to_viewport, space) = match document.is_graph_overlay_open() {
|
||||
true => (graph_to_viewport(document)?, CursorSpace::Graph { network: shown_network(document) }),
|
||||
false => (document.metadata().document_to_viewport, CursorSpace::Document),
|
||||
};
|
||||
let position = to_viewport.inverse().transform_point2(mouse);
|
||||
Some(CursorPosition {
|
||||
position: [(position.x * 100.).round() / 100., (position.y * 100.).round() / 100.],
|
||||
space,
|
||||
tool: (!tool_icon.is_empty()).then(|| tool_icon.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The other peers' pointers over the document, in viewport pixels for the frontend, while the canvas is showing.
|
||||
fn document_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
|
||||
if !preferences.show_remote_cursors || document.is_graph_overlay_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
|
||||
let to_viewport = document.metadata().document_to_viewport;
|
||||
gdd.peers()
|
||||
.iter()
|
||||
.filter_map(|remote| {
|
||||
let cursor = remote.cursor.as_ref()?;
|
||||
matches!(cursor.space, CursorSpace::Document).then(|| remote_cursor(remote, cursor, to_viewport, gdd.metadata()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The other peers' pointers over the network the node graph shows, in viewport pixels for the frontend.
|
||||
fn graph_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
|
||||
if !preferences.show_remote_cursors || !document.is_graph_overlay_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
|
||||
let Some(to_viewport) = graph_to_viewport(document) else { return Vec::new() };
|
||||
let shown = shown_network(document);
|
||||
gdd.peers()
|
||||
.iter()
|
||||
.filter_map(|remote| {
|
||||
let cursor = remote.cursor.as_ref()?;
|
||||
let CursorSpace::Graph { network } = &cursor.space else { return None };
|
||||
(*network == shown).then(|| remote_cursor(remote, cursor, to_viewport, gdd.metadata()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One pointer for the frontend: its position mapped into viewport pixels, with the peer's name, colour and tool.
|
||||
fn remote_cursor(remote: &RemotePeer, cursor: &CursorPosition, to_viewport: DAffine2, metadata: &HistoryMetadata) -> FrontendRemoteCursor {
|
||||
let [x, y] = cursor.position;
|
||||
let point = to_viewport.transform_point2(DVec2::new(x, y));
|
||||
FrontendRemoteCursor {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
name: display_name(remote, metadata),
|
||||
anonymous: is_anonymous(remote, metadata),
|
||||
color: user_color(remote.user),
|
||||
tool: cursor.tool.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn graph_to_viewport(document: &DocumentMessageHandler) -> Option<DAffine2> {
|
||||
let metadata = document.network_interface.network_metadata(document.breadcrumb_network_path())?;
|
||||
Some(metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
|
||||
}
|
||||
|
||||
fn shown_network(document: &DocumentMessageHandler) -> Vec<u64> {
|
||||
document.breadcrumb_network_path().iter().map(|id| id.0).collect()
|
||||
}
|
||||
|
||||
/// The one rule for a name shown anywhere: the document's record of the user, else what the peer announced
|
||||
/// for the room, else the stand-in.
|
||||
fn display_name(remote: &RemotePeer, metadata: &HistoryMetadata) -> String {
|
||||
if let Some(name) = metadata.user_name(remote.user) {
|
||||
return name.to_string();
|
||||
}
|
||||
match remote.name.is_empty() {
|
||||
true => anonymous_name(remote.user),
|
||||
false => remote.name.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_anonymous(remote: &RemotePeer, metadata: &HistoryMetadata) -> bool {
|
||||
metadata.user_name(remote.user).is_none() && remote.name.is_empty()
|
||||
}
|
||||
|
||||
/// How long a document whose transport went down waits before it tries its room again.
|
||||
const RECONNECT_AFTER_MS: f64 = 3_000.;
|
||||
@@ -12,6 +12,10 @@ pub enum PanelType {
|
||||
#[serde(alias = "Properties")]
|
||||
Inspector,
|
||||
Data,
|
||||
/// The live session of the active document: its state, the join link, the peers, and the sharing actions.
|
||||
Session,
|
||||
/// The active document's history as interactions along the head's line, with who did what and when.
|
||||
History,
|
||||
}
|
||||
|
||||
impl From<String> for PanelType {
|
||||
@@ -22,6 +26,8 @@ impl From<String> for PanelType {
|
||||
"Layers" => PanelType::Layers,
|
||||
"Inspector" | "Properties" => PanelType::Inspector,
|
||||
"Data" => PanelType::Data,
|
||||
"Session" => PanelType::Session,
|
||||
"History" => PanelType::History,
|
||||
_ => panic!("Unknown panel type: {value}"),
|
||||
}
|
||||
}
|
||||
@@ -29,7 +35,7 @@ impl From<String> for PanelType {
|
||||
|
||||
impl PanelType {
|
||||
pub fn non_document_panels() -> &'static [PanelType] {
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data]
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,6 +258,11 @@ impl WorkspacePanelLayout {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the panel was closed by the user, so its position is remembered for a later restore.
|
||||
pub fn was_closed(&self, panel_type: PanelType) -> bool {
|
||||
self.saved_positions.iter().any(|saved| saved.panel_type == panel_type)
|
||||
}
|
||||
|
||||
/// Restore a panel to its previous position if available, otherwise to its default position.
|
||||
pub fn restore_panel(&mut self, panel_type: PanelType) {
|
||||
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
|
||||
@@ -302,6 +313,21 @@ impl WorkspacePanelLayout {
|
||||
/// - Inspector: top of the right column (root child 1)
|
||||
/// - Layers: bottom of the right column (root child 1)
|
||||
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
|
||||
// The Session panel's home is a tab beside Inspector and the History panel's beside Layers, so each joins
|
||||
// that group whenever one is present.
|
||||
let beside = match panel_type {
|
||||
PanelType::Session => Some(PanelType::Inspector),
|
||||
PanelType::History => Some(PanelType::Layers),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(beside) = beside
|
||||
&& let Some(group_id) = self.find_panel(beside)
|
||||
&& let Some(group) = self.panel_group_mut(group_id)
|
||||
{
|
||||
group.tabs.push(panel_type);
|
||||
group.active_tab_index = group.tabs.len() - 1;
|
||||
return;
|
||||
}
|
||||
let new_id = self.next_id();
|
||||
let new_group = SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
@@ -316,9 +342,9 @@ impl WorkspacePanelLayout {
|
||||
|
||||
// Determine which root child column to insert into and at which position
|
||||
let (root_child_index, insert_at_end) = match panel_type {
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector => (1, false), // Right column, at top
|
||||
PanelType::Layers => (1, true), // Right column, at bottom
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
|
||||
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
|
||||
_ => (1, true),
|
||||
};
|
||||
|
||||
@@ -403,7 +429,7 @@ impl Default for WorkspacePanelLayout {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
id: PanelGroupId(1),
|
||||
state: PanelGroupState {
|
||||
tabs: vec![PanelType::Inspector],
|
||||
tabs: vec![PanelType::Inspector, PanelType::Session],
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -30,7 +30,13 @@ pub enum WorkspaceMessage {
|
||||
active_tab_index: usize,
|
||||
},
|
||||
ToggleFocusDocument,
|
||||
/// Bring a panel to the front: the active tab of its group, restored to its default position first when it is closed.
|
||||
FocusPanel {
|
||||
panel_type: PanelType,
|
||||
},
|
||||
ToggleDataPanelOpen,
|
||||
ToggleSessionPanelOpen,
|
||||
ToggleHistoryPanelOpen,
|
||||
ToggleInspectorOpen,
|
||||
ToggleLayersPanelOpen,
|
||||
UpdatePanelsLayout,
|
||||
|
||||
@@ -267,6 +267,19 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
|
||||
let panel_type = PanelType::Layers;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::FocusPanel { panel_type } => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
let Some(group) = self.panel_layout.find_panel(panel_type) else {
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
return;
|
||||
};
|
||||
let Some(tab_index) = self.panel_layout.panel_group(group).and_then(|state| state.tabs.iter().position(|&tab| tab == panel_type)) else {
|
||||
return;
|
||||
};
|
||||
responses.add(WorkspaceMessage::SetPanelGroupActiveTab { group, tab_index });
|
||||
}
|
||||
WorkspaceMessage::ToggleDataPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
@@ -275,6 +288,22 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
|
||||
let panel_type = PanelType::Data;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::ToggleSessionPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
|
||||
let panel_type = PanelType::Session;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::ToggleHistoryPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
|
||||
let panel_type = PanelType::History;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::UpdatePanelsLayout => {
|
||||
let panel_layout = match self.panel_layout.focus_document {
|
||||
true => self.panel_layout.document_only_layout(),
|
||||
@@ -390,7 +419,8 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Inspector => &[LayoutTarget::Inspector],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
|
||||
PanelType::Data => &[LayoutTarget::DataPanel],
|
||||
PanelType::Document | PanelType::Welcome => return,
|
||||
PanelType::Session => &[LayoutTarget::SessionPanel],
|
||||
PanelType::Document | PanelType::Welcome | PanelType::History => return,
|
||||
};
|
||||
|
||||
for &layout_target in targets {
|
||||
@@ -416,6 +446,12 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Data => {
|
||||
// The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here
|
||||
}
|
||||
PanelType::Session => {
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
PanelType::History => {
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
PanelType::Document | PanelType::Welcome => {
|
||||
// Re-send the welcome screen buttons layout to repopulate after a remount
|
||||
if has_no_documents {
|
||||
@@ -440,11 +476,11 @@ mod tests {
|
||||
};
|
||||
let group_of = |handler: &WorkspaceMessageHandler, panel_type| handler.panel_layout.find_panel(panel_type).expect("the default layout has this panel");
|
||||
|
||||
// The Layers panel joins the Inspector's group as its active tab
|
||||
// The Layers panel joins the Inspector's group as its active tab, ahead of the Inspector so that is what is left active
|
||||
let join = WorkspaceMessage::MovePanelTab {
|
||||
source_group: group_of(&handler, PanelType::Layers),
|
||||
target_group: group_of(&handler, PanelType::Inspector),
|
||||
insert_index: 1,
|
||||
insert_index: 0,
|
||||
};
|
||||
handler.process_message(join, &mut VecDeque::new(), context());
|
||||
|
||||
|
||||
@@ -43,6 +43,14 @@ pub enum PreferencesMessage {
|
||||
enabled: bool,
|
||||
},
|
||||
ToggleShowStoragePreferences,
|
||||
/// The display name shown to peers in a live session.
|
||||
UserName {
|
||||
name: String,
|
||||
},
|
||||
/// Whether the other peers' pointers are drawn over a shared document.
|
||||
ShowRemoteCursors {
|
||||
enabled: bool,
|
||||
},
|
||||
#[cfg(target_os = "macos")]
|
||||
VSync {
|
||||
vsync: bool,
|
||||
|
||||
@@ -26,6 +26,15 @@ pub struct PreferencesMessageHandler {
|
||||
pub validate_storage_round_trip: bool,
|
||||
pub save_as_gdd: bool,
|
||||
pub show_storage_preferences: bool,
|
||||
/// Who this person is across documents and devices, drawn once and kept; `0` until then.
|
||||
/// Kept as a decimal string in the preferences file: a 64-bit number does not survive the browser's JSON store.
|
||||
#[serde(with = "u64_as_string")]
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "string"))]
|
||||
pub user_id: u64,
|
||||
/// The display name peers see in a live session; empty means unnamed.
|
||||
pub user_name: String,
|
||||
/// Draw the other peers' pointers over a shared document.
|
||||
pub show_remote_cursors: bool,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub vsync: bool,
|
||||
}
|
||||
@@ -72,6 +81,9 @@ impl Default for PreferencesMessageHandler {
|
||||
validate_storage_round_trip: false,
|
||||
save_as_gdd: false,
|
||||
show_storage_preferences: false,
|
||||
user_id: 0,
|
||||
user_name: String::new(),
|
||||
show_remote_cursors: true,
|
||||
#[cfg(target_os = "macos")]
|
||||
vsync: false,
|
||||
}
|
||||
@@ -87,6 +99,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
// Management messages
|
||||
PreferencesMessage::Load { preferences } => {
|
||||
*self = preferences;
|
||||
if self.user_id == 0 {
|
||||
self.user_id = crate::application::generate_uuid();
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::EditorPreferences);
|
||||
responses.add(PreferencesMessage::ModifyLayout {
|
||||
@@ -94,7 +109,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,12 +159,20 @@ 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;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
}
|
||||
PreferencesMessage::UserName { name } => {
|
||||
self.user_name = name.trim().to_string();
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
PreferencesMessage::ShowRemoteCursors { enabled } => {
|
||||
self.show_remote_cursors = enabled;
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
PreferencesMessage::VSync { vsync } => {
|
||||
self.vsync = vsync;
|
||||
@@ -163,3 +185,26 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
advertise_actions!(PreferencesMessageDiscriminant;
|
||||
);
|
||||
}
|
||||
|
||||
/// A `u64` written as a decimal string, since the browser's JSON loses precision on a number this wide and cannot write a
|
||||
/// BigInt. Reads a number too.
|
||||
mod u64_as_string {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(&value.to_string())
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Stored {
|
||||
Text(String),
|
||||
Number(u64),
|
||||
}
|
||||
match Stored::deserialize(deserializer)? {
|
||||
Stored::Text(text) => text.parse().map_err(serde::de::Error::custom),
|
||||
Stored::Number(number) => Ok(number),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,8 +33,10 @@ pub use crate::messages::portfolio::document::resource::{ResourceMessage, Resour
|
||||
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
|
||||
pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageDiscriminant, FailedDocumentsMessageHandler};
|
||||
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
|
||||
pub use crate::messages::portfolio::history::{HistoryMessage, HistoryMessageContext, HistoryMessageDiscriminant, HistoryMessageHandler};
|
||||
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
|
||||
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
|
||||
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
|
||||
pub use crate::messages::portfolio::workspace::{WorkspaceMessage, WorkspaceMessageContext, WorkspaceMessageDiscriminant, WorkspaceMessageHandler};
|
||||
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
|
||||
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
|
||||
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user