mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0969ba97f1 | ||
|
|
b835338fe5 | ||
|
|
36cf718600 | ||
|
|
e7d7788bae | ||
|
|
1d989f7276 | ||
|
|
7d25cd4f1f | ||
|
|
0dca4007e4 | ||
|
|
08a6a08285 | ||
|
|
891ebcbe30 | ||
|
|
aa6b204513 | ||
|
|
06bc29bd5e | ||
|
|
6d08976b00 | ||
|
|
5764e0a7e6 | ||
|
|
7c44a43d4a | ||
|
|
661a101cb5 | ||
|
|
6f4dbc58f1 | ||
|
|
499da4f7f6 | ||
|
|
8da352fffe | ||
|
|
7654304179 | ||
|
|
49711cd375 | ||
|
|
b837b39944 | ||
|
|
c7e9d79f7e | ||
|
|
713b50c2a9 | ||
|
|
58b8aeb0e2 | ||
|
|
74a361aafc | ||
|
|
ab99e0e513 | ||
|
|
e1bc46a6bb | ||
|
|
9e19a46ba6 | ||
|
|
514b894be3 | ||
|
|
347e6ac7e4 | ||
|
|
46f48a5410 | ||
|
|
243a83ce17 | ||
|
|
006807fafe | ||
|
|
225ae8613e | ||
|
|
b796a32617 | ||
|
|
5ba834f92c | ||
|
|
3f23ae7550 | ||
|
|
64fc98e0d8 | ||
|
|
a89f1c5c9b | ||
|
|
e62977e73d | ||
|
|
13b481da1c | ||
|
|
7cd8477c1a | ||
|
|
26c808d374 | ||
|
|
1185d1de45 | ||
|
|
f20825d8ba | ||
|
|
6373264efa | ||
|
|
b5b6664d9a | ||
|
|
6b2241fdb6 | ||
|
|
15a7d080a2 | ||
|
|
fc9b616814 | ||
|
|
a5106771b6 | ||
|
|
70a51a5fb5 | ||
|
|
1478a14ebb | ||
|
|
e0936929da | ||
|
|
53dcdc194a | ||
|
|
1829e1b80a | ||
|
|
d91f3878be | ||
|
|
13d9c1d947 |
No files matched your search
Generated
+1772
-82
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
|
||||
|
||||
+96
-33
@@ -16,16 +16,18 @@ 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;
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
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, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, Scheduling, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -53,6 +55,7 @@ pub(crate) struct App {
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
hide_ui: bool,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -77,36 +80,59 @@ impl App {
|
||||
|
||||
let exiting = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
|
||||
|
||||
let async_runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct tokio runtime");
|
||||
|
||||
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
|
||||
|
||||
let wake_scheduler = app_event_scheduler.clone();
|
||||
let editor_wake = move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
};
|
||||
let runtime_wake_sender = start_render_sender.clone();
|
||||
let runtime_wake = move || {
|
||||
let _ = runtime_wake_sender.try_send(());
|
||||
};
|
||||
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
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,
|
||||
);
|
||||
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let exiting_clone = exiting.clone();
|
||||
std::thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
loop {
|
||||
let result = runtime.block_on(DesktopWrapper::execute_node_graph());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::NodeGraphExecutionResult(result));
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
|
||||
|
||||
// Wake the winit event loop when an editor future completes.
|
||||
let wake_scheduler = app_event_scheduler.clone();
|
||||
let wake = Arc::new(move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
wake,
|
||||
);
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
wgpu_context,
|
||||
@@ -133,6 +159,7 @@ impl App {
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
hide_ui: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,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;
|
||||
@@ -278,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
|
||||
{
|
||||
@@ -296,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();
|
||||
}
|
||||
@@ -401,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,20 +499,20 @@ impl App {
|
||||
}
|
||||
}
|
||||
AppEvent::DesktopWrapperMessage(message) => self.dispatch_desktop_wrapper_message(message),
|
||||
AppEvent::NodeGraphExecutionResult(result) => match result {
|
||||
NodeGraphExecutionResult::HasRun(texture) => {
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::PollNodeGraphEvaluation);
|
||||
if let Some(texture) = texture
|
||||
&& let Some(render_state) = self.render_state.as_mut()
|
||||
&& let Some(window) = self.window.as_ref()
|
||||
{
|
||||
render_state.bind_viewport_texture(texture);
|
||||
window.request_redraw();
|
||||
}
|
||||
AppEvent::ViewportTexture(texture) => {
|
||||
if let Some(texture) = texture
|
||||
&& let Some(render_state) = self.render_state.as_mut()
|
||||
&& let Some(window) = self.window.as_ref()
|
||||
{
|
||||
render_state.bind_viewport_texture(texture);
|
||||
window.request_redraw();
|
||||
}
|
||||
NodeGraphExecutionResult::NotRun => {}
|
||||
},
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::ui::Cursor;
|
||||
use crate::wrapper::NodeGraphExecutionResult;
|
||||
use crate::wrapper::Texture;
|
||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
||||
|
||||
pub(crate) enum AppEvent {
|
||||
@@ -7,7 +7,7 @@ pub(crate) enum AppEvent {
|
||||
CursorChange(Cursor),
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
ViewportTexture(Option<Texture>),
|
||||
ClipboardRead,
|
||||
ClipboardWrite {
|
||||
content: String,
|
||||
|
||||
@@ -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;
|
||||
@@ -22,6 +23,7 @@ mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
mod socket;
|
||||
mod spawner;
|
||||
mod window;
|
||||
|
||||
pub(crate) mod consts;
|
||||
|
||||
@@ -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;
|
||||
@@ -228,7 +233,7 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::wrapper::{Spawn, Task};
|
||||
|
||||
pub(crate) struct TokioSpawner(tokio::runtime::Handle);
|
||||
impl TokioSpawner {
|
||||
pub(crate) fn new(handle: tokio::runtime::Handle) -> Self {
|
||||
Self(handle)
|
||||
}
|
||||
}
|
||||
impl Spawn for TokioSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
self.0.spawn(task);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.queue_editor_message(*message);
|
||||
}
|
||||
DesktopWrapperMessage::Wake => {
|
||||
dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake));
|
||||
dispatcher.queue_editor_message(EditorMessage::Wake);
|
||||
}
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
@@ -35,7 +35,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
dispatcher.queue_editor_message(message);
|
||||
@@ -78,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
|
||||
|
||||
+35
-18
@@ -1,8 +1,9 @@
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
|
||||
use graphite_editor::messages::frontend::FrontendMessage;
|
||||
use graphite_editor::messages::prelude::Wake;
|
||||
use graphite_editor::node_graph_executor::NodeRuntime;
|
||||
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
@@ -11,6 +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::{Clock, Scheduling, Spawn, Task};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
@@ -33,7 +35,18 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
#[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) {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -43,9 +56,26 @@ impl DesktopWrapper {
|
||||
let env = Environment { platform: Platform::Desktop, host };
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
Self {
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
|
||||
}
|
||||
let (editor, runtime) = Builder::new()
|
||||
.with_editor(
|
||||
EditorBuilder::new()
|
||||
.with_wake(editor_wake)
|
||||
.with_environment(env)
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.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();
|
||||
|
||||
(Self { editor }, runtime)
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
|
||||
@@ -53,19 +83,6 @@ impl DesktopWrapper {
|
||||
executor.queue_desktop_wrapper_message(message);
|
||||
executor.execute()
|
||||
}
|
||||
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
|
||||
(false, _) => NodeGraphExecutionResult::NotRun,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum NodeGraphExecutionResult {
|
||||
HasRun(Option<Texture>),
|
||||
NotRun,
|
||||
}
|
||||
|
||||
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
||||
|
||||
@@ -42,18 +42,6 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
self.responses.push(response);
|
||||
}
|
||||
|
||||
pub(super) fn poll_node_graph_evaluation(&mut self) {
|
||||
let mut responses = VecDeque::new();
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error polling node graph: {}", e);
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_queue(&mut self) {
|
||||
let mut frontend_messages = Vec::new();
|
||||
|
||||
|
||||
@@ -71,6 +71,8 @@ pub enum DesktopFrontendMessage {
|
||||
WindowShowAll,
|
||||
Restart,
|
||||
LoadThirdPartyLicenses,
|
||||
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
|
||||
pub enum DesktopWrapperMessage {
|
||||
@@ -79,7 +81,6 @@ pub enum DesktopWrapperMessage {
|
||||
Input(InputMessage),
|
||||
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
LoadPersistedState { state: PersistedState },
|
||||
@@ -88,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.
|
||||
@@ -123,6 +123,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -138,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 {
|
||||
@@ -148,6 +149,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -156,6 +158,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: HotSequence(2),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -184,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 {
|
||||
@@ -194,6 +197,7 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -214,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");
|
||||
@@ -242,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");
|
||||
@@ -267,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");
|
||||
@@ -290,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[..]);
|
||||
@@ -320,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[..]);
|
||||
@@ -349,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";
|
||||
@@ -373,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[..]);
|
||||
@@ -401,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.
|
||||
@@ -466,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";
|
||||
@@ -507,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[..]);
|
||||
@@ -560,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);
|
||||
@@ -581,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)],
|
||||
@@ -623,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 {
|
||||
@@ -632,6 +636,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -675,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();
|
||||
@@ -703,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)
|
||||
@@ -54,9 +54,10 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
},
|
||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
||||
sequence: HotSequence(counter),
|
||||
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();
|
||||
@@ -79,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");
|
||||
});
|
||||
}
|
||||
@@ -102,10 +102,10 @@ impl Attributes {
|
||||
|
||||
/// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A
|
||||
/// deletion leaves a tombstone.
|
||||
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) {
|
||||
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp);
|
||||
if !force && timestamp <= decided {
|
||||
if timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
@@ -68,6 +67,7 @@ pub mod network {
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta.
|
||||
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on
|
||||
/// the last hot op of an interaction.
|
||||
pub const INTERACTION_END: &str = "interaction_end";
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use crate::{
|
||||
Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
|
||||
};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -13,7 +15,8 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
||||
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
@@ -26,7 +29,7 @@ pub struct Delta {
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -54,7 +57,7 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: kind.clone(),
|
||||
reverse: Vec::new(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
@@ -208,6 +211,9 @@ 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),
|
||||
}
|
||||
@@ -219,26 +225,13 @@ pub struct AttributeDelta {
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
|
||||
let base = Delta::new(
|
||||
None,
|
||||
PeerId(1),
|
||||
TimeStamp { counter: 1, peer: PeerId(1) },
|
||||
RegistryDelta::Other(Value::None),
|
||||
RegistryDelta::Other(Value::None),
|
||||
);
|
||||
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::Other(Value::None), Vec::new());
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@ 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, Value, reverse_attribute_delta,
|
||||
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,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
@@ -17,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
|
||||
@@ -76,17 +75,12 @@ impl Document {
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
/// Undo `delta` by putting back what it overwrote: in the snapshot, and in the working registry when nothing is hot.
|
||||
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
|
||||
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
|
||||
if self.hot_log.is_empty() {
|
||||
crate::prior::restore(&mut self.working_registry, &delta.reverse);
|
||||
}
|
||||
std::mem::swap(&mut delta.kind, &mut delta.reverse);
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Stage a local op onto the working registry and the hot log, skipping the retired check so local work is never dropped.
|
||||
@@ -118,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();
|
||||
@@ -139,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.
|
||||
@@ -190,13 +208,6 @@ impl Document {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
|
||||
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
|
||||
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
|
||||
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
|
||||
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
|
||||
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
|
||||
@@ -206,7 +217,6 @@ impl Document {
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
let strict = mode == ApplyMode::Strict;
|
||||
let force = mode == ApplyMode::Force;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
@@ -215,10 +225,10 @@ impl Document {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
|
||||
@@ -231,12 +241,7 @@ impl Document {
|
||||
.collect();
|
||||
ensure_seen(registry, &referenced, mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force {
|
||||
node.inputs = inputs;
|
||||
node.inputs_timestamp = timestamp;
|
||||
} else {
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
}
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
@@ -251,7 +256,7 @@ impl Document {
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
if force || timestamp > input.timestamp {
|
||||
if timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
@@ -267,7 +272,7 @@ impl Document {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
if timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
@@ -276,14 +281,14 @@ impl Document {
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
node.attributes.apply_delta(delta, timestamp, force);
|
||||
node.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
input.attributes.apply_delta(delta, timestamp, force);
|
||||
input.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
@@ -300,7 +305,7 @@ impl Document {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
// Past the end of a newer list the slot is gone, as with input slots.
|
||||
if !force && timestamp <= net.exports_timestamp {
|
||||
if timestamp <= net.exports_timestamp {
|
||||
return Ok(());
|
||||
}
|
||||
let shape = net.exports_timestamp;
|
||||
@@ -308,7 +313,7 @@ impl Document {
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
@@ -322,20 +327,20 @@ impl Document {
|
||||
if strict && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
net.attributes.apply_delta(delta, timestamp, force);
|
||||
net.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
if timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
@@ -344,24 +349,20 @@ impl Document {
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
entry.set_source(key, value);
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force {
|
||||
entry.force_remove_source(&key);
|
||||
} else {
|
||||
entry.remove_source(&key, timestamp);
|
||||
}
|
||||
entry.remove_source(&key, timestamp);
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force);
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::RegisterPeer { peer, user } => {
|
||||
// The newest registration of a device wins, whatever order they land in.
|
||||
@@ -370,117 +371,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
registry.attributes.apply_delta(delta, timestamp, force);
|
||||
registry.attributes.apply_delta(delta, timestamp);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
||||
///
|
||||
/// A write reads its pre-op value from wherever it lands: the live entity, its tombstone, or for an
|
||||
/// entity never seen, a placeholder.
|
||||
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||
let registry = self.registry_ref(target);
|
||||
let node = |id: NodeId| registry.node_or_removed(id).map_or_else(|| Cow::Owned(Node::placeholder()), Cow::Borrowed);
|
||||
let unset = InputSlot::unset(TimeStamp::ORIGIN);
|
||||
let network = |id: NetworkId| registry.network_or_removed(id);
|
||||
let resource = |id: ResourceId| registry.resources.get(&id).or_else(|| registry.removed_resources.get(&id).map(|mark| &mark.content));
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() },
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node(id).implementation.clone(),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = node(id);
|
||||
let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: input_idx,
|
||||
new_input: slot.input.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node(id).attributes()),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = node(id);
|
||||
let input = node.inputs().get(index as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: reverse_attribute_delta(delta, &input.attributes),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// Absent network or slot: pre-op there was no export to point at.
|
||||
let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||
let empty = Attributes::new();
|
||||
let current = network(id).map_or(&empty, |net| &net.attributes);
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: reverse_attribute_delta(delta, ®istry.attributes),
|
||||
},
|
||||
// Registrations are append-only and not user-undoable; reverse is the same op,
|
||||
// which applies as a no-op on the already-registered PeerId.
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: resource(id).and_then(|entry| entry.hash),
|
||||
},
|
||||
&RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
// The slot already held a source: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// Nothing to restore; reverse is a no-op removal.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
|
||||
// Overwrote an existing entry: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
|
||||
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
|
||||
None => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: ResourceEntry::default(),
|
||||
},
|
||||
},
|
||||
&RegistryDelta::RemoveResource { id, .. } => {
|
||||
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
|
||||
RegistryDelta::AddResource { id, entry: snapshot }
|
||||
}
|
||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||
&RegistryDelta::Other(_) => RegistryDelta::Other(Value::None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
@@ -649,7 +546,7 @@ fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: App
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
|
||||
if timestamp <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
@@ -688,23 +585,18 @@ fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead:
|
||||
}
|
||||
|
||||
/// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead.
|
||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp, force: bool) {
|
||||
if force {
|
||||
dead.remove(&id);
|
||||
live.insert(id, content);
|
||||
return;
|
||||
}
|
||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp) {
|
||||
content.stamp_all(timestamp);
|
||||
merge_entity(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an
|
||||
/// entity never seen still lands.
|
||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) {
|
||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp) {
|
||||
merge_entity(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
|
||||
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
|
||||
mark.timestamp = mark.timestamp.max(timestamp);
|
||||
} else if live.get(&id).is_some_and(|content| timestamp > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(
|
||||
id,
|
||||
@@ -728,7 +620,6 @@ fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
) -> Result<(), CrdtError> {
|
||||
let force = mode == ApplyMode::Force;
|
||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
||||
if unseen {
|
||||
if mode == ApplyMode::Strict {
|
||||
@@ -752,9 +643,6 @@ fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(timestamp));
|
||||
if force && let Some(mark) = dead.remove(&id) {
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
@@ -818,6 +706,4 @@ pub(crate) enum ApplyMode {
|
||||
Strict,
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// Silent-zone undo/redo rewind: every write lands, whatever its timestamp.
|
||||
Force,
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::Context;
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -447,9 +446,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
attributes
|
||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
@@ -477,11 +473,6 @@ pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::A
|
||||
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
|
||||
}
|
||||
|
||||
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
|
||||
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
|
||||
}
|
||||
|
||||
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
|
||||
|
||||
|
||||
@@ -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,11 +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))]
|
||||
@@ -23,11 +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))]
|
||||
@@ -38,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;
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
use crate::{
|
||||
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
|
||||
Tombstone,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// What a slot held before a delta wrote it, stamps included. Undo puts it back bypassing LWW, so the registry is again
|
||||
/// the fold of history up to the delta's parent. Never sent or applied as an op.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Prior {
|
||||
/// The whole entity, live, tombstoned, or absent. Restoring an absent one leaves no tombstone, so undoing an addition erases it.
|
||||
Node {
|
||||
id: NodeId,
|
||||
node: Node,
|
||||
},
|
||||
RemovedNode {
|
||||
id: NodeId,
|
||||
tombstone: Tombstone<Node>,
|
||||
},
|
||||
AbsentNode {
|
||||
id: NodeId,
|
||||
},
|
||||
Network {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
RemovedNetwork {
|
||||
id: NetworkId,
|
||||
tombstone: Tombstone<Network>,
|
||||
},
|
||||
AbsentNetwork {
|
||||
id: NetworkId,
|
||||
},
|
||||
Resource {
|
||||
id: ResourceId,
|
||||
resource: ResourceEntry,
|
||||
},
|
||||
RemovedResource {
|
||||
id: ResourceId,
|
||||
tombstone: Tombstone<ResourceEntry>,
|
||||
},
|
||||
AbsentResource {
|
||||
id: ResourceId,
|
||||
},
|
||||
/// One field of a live node, and the node's presence, which every write moves.
|
||||
NodeField {
|
||||
id: NodeId,
|
||||
presence: TimeStamp,
|
||||
field: NodeField,
|
||||
},
|
||||
/// One field of a live network, and its presence.
|
||||
NetworkField {
|
||||
id: NetworkId,
|
||||
presence: TimeStamp,
|
||||
field: NetworkField,
|
||||
},
|
||||
DocumentAttribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
PeerUser {
|
||||
peer: PeerId,
|
||||
previous: Option<PeerRegistration>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeField {
|
||||
/// Only the presence moved, by a reference from another entity's op.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Input {
|
||||
index: u32,
|
||||
previous: InputSlot,
|
||||
},
|
||||
InputAttribute {
|
||||
index: u32,
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Inputs {
|
||||
previous: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp,
|
||||
},
|
||||
Implementation {
|
||||
previous: Implementation,
|
||||
implementation_timestamp: TimeStamp,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NetworkField {
|
||||
/// Only the presence moved, by a node added to or implemented by it.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Exports {
|
||||
previous: Vec<ExportSlot>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
|
||||
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
|
||||
let mut priors = Vec::new();
|
||||
let node_input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
|
||||
priors.push(whole_node(registry, *id));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
}));
|
||||
priors.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.filter_map(|slot| node_input(&slot.input))
|
||||
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
|
||||
);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::Input {
|
||||
index: *index,
|
||||
previous: slot.clone(),
|
||||
})
|
||||
}));
|
||||
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let Implementation::Network(network) = implementation {
|
||||
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
|
||||
}
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
|
||||
previous: node.implementation.clone(),
|
||||
implementation_timestamp: node.implementation_timestamp,
|
||||
}));
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: node.attributes.get(&delta.key).cloned(),
|
||||
})),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::InputAttribute {
|
||||
index: *index,
|
||||
key: delta.key.clone(),
|
||||
previous: slot.attributes.get(&delta.key).cloned(),
|
||||
})
|
||||
})),
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
|
||||
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: network.attributes.get(&delta.key).cloned(),
|
||||
}));
|
||||
}
|
||||
RegistryDelta::AddResource { id, .. }
|
||||
| RegistryDelta::RemoveResource { id, .. }
|
||||
| RegistryDelta::SetResourceHash { id, .. }
|
||||
| RegistryDelta::AddSource { id, .. }
|
||||
| RegistryDelta::RemoveSource { id, .. } => priors.push(whole_resource(registry, *id)),
|
||||
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
|
||||
peer: *peer,
|
||||
previous: registry.peer_users.get(peer).copied(),
|
||||
}),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
|
||||
key: delta.key.clone(),
|
||||
previous: registry.attributes.get(&delta.key).cloned(),
|
||||
}),
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
priors
|
||||
}
|
||||
|
||||
/// Puts back what `priors` recorded, newest write first.
|
||||
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
|
||||
for prior in priors.iter().rev() {
|
||||
match prior {
|
||||
Prior::Node { id, node } => put_live(&mut registry.node_instances, &mut registry.removed_nodes, *id, node),
|
||||
Prior::RemovedNode { id, tombstone } => put_removed(&mut registry.node_instances, &mut registry.removed_nodes, *id, tombstone),
|
||||
Prior::AbsentNode { id } => put_absent(&mut registry.node_instances, &mut registry.removed_nodes, *id),
|
||||
Prior::Network { id, network } => put_live(&mut registry.networks, &mut registry.removed_networks, *id, network),
|
||||
Prior::RemovedNetwork { id, tombstone } => put_removed(&mut registry.networks, &mut registry.removed_networks, *id, tombstone),
|
||||
Prior::AbsentNetwork { id } => put_absent(&mut registry.networks, &mut registry.removed_networks, *id),
|
||||
Prior::Resource { id, resource } => put_live(&mut registry.resources, &mut registry.removed_resources, *id, resource),
|
||||
Prior::RemovedResource { id, tombstone } => put_removed(&mut registry.resources, &mut registry.removed_resources, *id, tombstone),
|
||||
Prior::AbsentResource { id } => put_absent(&mut registry.resources, &mut registry.removed_resources, *id),
|
||||
Prior::NodeField { id, presence, field } => {
|
||||
let Some(node) = registry.node_instances.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
node.presence = *presence;
|
||||
match field {
|
||||
NodeField::Presence => {}
|
||||
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
|
||||
NodeField::Input { index, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
*slot = previous.clone();
|
||||
}
|
||||
}
|
||||
NodeField::InputAttribute { index, key, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
put_attribute(&mut slot.attributes, key, previous.as_ref());
|
||||
}
|
||||
}
|
||||
NodeField::Inputs { previous, inputs_timestamp } => {
|
||||
node.inputs = previous.clone();
|
||||
node.inputs_timestamp = *inputs_timestamp;
|
||||
}
|
||||
NodeField::Implementation { previous, implementation_timestamp } => {
|
||||
node.implementation = previous.clone();
|
||||
node.implementation_timestamp = *implementation_timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
Prior::NetworkField { id, presence, field } => {
|
||||
let Some(network) = registry.networks.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
network.presence = *presence;
|
||||
match field {
|
||||
NetworkField::Presence => {}
|
||||
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
|
||||
NetworkField::Exports { previous } => network.exports = previous.clone(),
|
||||
}
|
||||
}
|
||||
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
|
||||
Prior::PeerUser { peer, previous } => match previous {
|
||||
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
|
||||
None => _ = registry.peer_users.remove(peer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
|
||||
if let Some(node) = registry.node_instances.get(&id) {
|
||||
Prior::Node { id, node: node.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_nodes.get(&id) {
|
||||
Prior::RemovedNode { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentNode { id }
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
|
||||
if let Some(network) = registry.networks.get(&id) {
|
||||
Prior::Network { id, network: network.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_networks.get(&id) {
|
||||
Prior::RemovedNetwork { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentNetwork { id }
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_resource(registry: &Registry, id: ResourceId) -> Prior {
|
||||
if let Some(resource) = registry.resources.get(&id) {
|
||||
Prior::Resource { id, resource: resource.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_resources.get(&id) {
|
||||
Prior::RemovedResource { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentResource { id }
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a live node; a write landing on a tombstone or placeholder records the whole entity instead.
|
||||
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
|
||||
match registry.node_instances.get(&id) {
|
||||
Some(node) => Prior::NodeField {
|
||||
id,
|
||||
presence: node.presence,
|
||||
field: field(node),
|
||||
},
|
||||
None => whole_node(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
|
||||
match registry.networks.get(&id) {
|
||||
Some(network) => Prior::NetworkField {
|
||||
id,
|
||||
presence: network.presence,
|
||||
field: field(network),
|
||||
},
|
||||
None => whole_network(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
|
||||
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
|
||||
match node.inputs.get(index as usize) {
|
||||
Some(slot) => field(slot),
|
||||
None => NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn put_live<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: &T) {
|
||||
dead.remove(&id);
|
||||
live.insert(id, content.clone());
|
||||
}
|
||||
|
||||
fn put_removed<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, tombstone: &Tombstone<T>) {
|
||||
live.remove(&id);
|
||||
dead.insert(id, tombstone.clone());
|
||||
}
|
||||
|
||||
fn put_absent<K: Hash + Eq + Copy, T>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
live.remove(&id);
|
||||
dead.remove(&id);
|
||||
}
|
||||
|
||||
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
|
||||
match previous {
|
||||
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
|
||||
None => _ = attributes.remove(key),
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -44,11 +44,13 @@ pub struct Tombstone<T> {
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
@@ -64,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
|
||||
|
||||
@@ -173,7 +173,7 @@ impl ResourceEntry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
}
|
||||
@@ -187,17 +187,6 @@ impl ResourceEntry {
|
||||
true
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
||||
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||
pub fn has_embedded_source(&self) -> bool {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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() {
|
||||
@@ -25,6 +31,7 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.replay_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
@@ -42,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.
|
||||
@@ -77,12 +312,33 @@ 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 {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.replay_hot_op(op.clone()).unwrap();
|
||||
@@ -165,6 +421,7 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(1) },
|
||||
sequence: crate::HotSequence(7),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
marks.extend([own.id()]);
|
||||
@@ -176,3 +433,22 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
assert!(next.sequence > own.sequence, "a fresh sequence");
|
||||
assert!(next.timestamp > own.timestamp, "a later stamp");
|
||||
}
|
||||
|
||||
/// 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));
|
||||
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");
|
||||
assert!(host.closed_interactions().is_empty(), "the interaction is open");
|
||||
|
||||
host.replay_hot_op(closing(guest_op(11, 2, set_attribute("guest", 1)))).expect("flagged write");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].ops.len(), 2, "both writes, and no marker of its own");
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use graph_craft::concrete;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::InputSlot;
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, RegistryTarget, Session, TimeStamp, Value};
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, Session, TimeStamp, Value};
|
||||
|
||||
fn fresh_document(peer: PeerId) -> Document {
|
||||
Session::with_peer(peer).document
|
||||
@@ -20,7 +20,7 @@ fn remove_node_op(node_id: NodeId) -> RegistryDelta {
|
||||
/// Commit a single op to a document as a retired delta. Mints a fresh timestamp, links to
|
||||
/// current head, applies, records in history, advances head.
|
||||
fn commit_op(document: &mut Document, op: RegistryDelta) {
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &op).expect("compute_reverse_delta failed");
|
||||
let reverse = crate::prior::capture(&document.working_registry, &op);
|
||||
let timestamp = document.clock.tick();
|
||||
let delta = Delta::new(document.head, document.peer, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -41,6 +41,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
op: remove_node_op(NodeId(99)),
|
||||
timestamp: observed,
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
document
|
||||
@@ -160,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(),
|
||||
@@ -169,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
|
||||
@@ -420,6 +354,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
|
||||
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
|
||||
attributes.live().any(|(held, _)| held == key)
|
||||
}
|
||||
|
||||
fn ts(counter: u64, peer: u64) -> TimeStamp {
|
||||
TimeStamp { counter, peer: PeerId(peer) }
|
||||
}
|
||||
@@ -519,85 +458,146 @@ fn register_resource_hash_is_last_writer_wins() {
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().hash, Some(hash_b), "later resolve wins");
|
||||
}
|
||||
|
||||
/// The reverse delta of a RemoveSource restores the prior source body, and applying op-then-reverse
|
||||
/// round-trips the source chain.
|
||||
/// For every kind of op, landing on a live entity, a removed one or one never seen.
|
||||
#[test]
|
||||
fn remove_source_reverse_restores_prior() {
|
||||
fn restoring_what_an_op_overwrote_gives_back_the_registry_exactly() {
|
||||
use crate::{AttributeDelta, Implementation, Network, NodeInput, ROOT_NETWORK};
|
||||
let attribute = |key: &str, value: i64| AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::Int(value.into())),
|
||||
};
|
||||
let reference = |id: u64| NodeInput::Node { id: NodeId(id), index: 0 };
|
||||
let (live, removed, unseen, network, resource) = (NodeId(1), NodeId(2), NodeId(3), NetworkId(7), ResourceId::new());
|
||||
let node = || Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2);
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Compute the reverse while the body is still present, then apply the removal.
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap();
|
||||
match &reverse {
|
||||
RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
for (op, at) in [
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: network,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(RD::AddNode { id: live, node: node() }, 2),
|
||||
(RD::AddNode { id: removed, node: node() }, 2),
|
||||
(RD::RemoveNode { id: removed, snapshot: node() }, 3),
|
||||
(
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 1),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(RD::ChangeDocumentAttribute { delta: attribute("kept", 1) }, 4),
|
||||
(
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 0,
|
||||
export: Some(reference(1)),
|
||||
},
|
||||
4,
|
||||
),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(at, 2)).unwrap();
|
||||
}
|
||||
|
||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||
assert!(
|
||||
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
|
||||
"source removed, a tombstone left"
|
||||
);
|
||||
|
||||
// Applying the reverse restores the chain.
|
||||
document.apply_op(reverse, ts(6, 1)).unwrap();
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, Value::Str("kept".into()));
|
||||
}
|
||||
|
||||
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
||||
#[test]
|
||||
fn add_source_reverse_depends_on_prior_state() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
// Fresh slot: reverse removes.
|
||||
let reverse_fresh = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("first".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(reverse_fresh, RD::RemoveSource { .. }), "reverse of add-to-empty is remove, got {reverse_fresh:?}");
|
||||
|
||||
// Occupy the slot, then reverse of a new add restores the existing body.
|
||||
document
|
||||
.apply_op(
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("existing".into()),
|
||||
},
|
||||
ts(1, 1),
|
||||
)
|
||||
.unwrap();
|
||||
let reverse_overwrite = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("overwrite".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match reverse_overwrite {
|
||||
RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
let ops = [
|
||||
RD::AddNode { id: live, node: node() },
|
||||
RD::AddNode { id: unseen, node: node() },
|
||||
RD::RemoveNode { id: live, snapshot: node() },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute { id: live, delta: attribute("new", 2) },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: removed,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute {
|
||||
id: unseen,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 1,
|
||||
new_input: reference(2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 5,
|
||||
new_input: reference(3),
|
||||
},
|
||||
RD::ChangeNodeInputAttribute {
|
||||
id: live,
|
||||
index: 0,
|
||||
delta: attribute("name", 2),
|
||||
},
|
||||
RD::SetNodeInputs {
|
||||
id: live,
|
||||
inputs: vec![crate::InputSlot::unset(TimeStamp::ORIGIN); 3],
|
||||
},
|
||||
RD::SetNodeImplementation {
|
||||
id: live,
|
||||
implementation: Implementation::Network(NetworkId(8)),
|
||||
},
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 3,
|
||||
export: Some(reference(3)),
|
||||
},
|
||||
RD::ChangeNetworkAttribute {
|
||||
id: network,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::RemoveNetwork {
|
||||
id: network,
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("new".into()),
|
||||
},
|
||||
RD::RemoveSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
},
|
||||
RD::SetResourceHash { id: ResourceId::new(), hash: None },
|
||||
RD::RemoveResource {
|
||||
id: resource,
|
||||
snapshot: Default::default(),
|
||||
},
|
||||
RD::ChangeDocumentAttribute { delta: attribute("kept", 2) },
|
||||
RD::RegisterPeer {
|
||||
peer: PeerId(5),
|
||||
user: crate::UserId(5),
|
||||
},
|
||||
];
|
||||
for op in ops {
|
||||
let before = document.working_registry.clone();
|
||||
let priors = crate::prior::capture(&before, &op);
|
||||
let mut after = document.clone();
|
||||
after.apply_op_idempotent(op.clone(), ts(10, 2)).unwrap();
|
||||
assert_ne!(after.working_registry, before, "{op:?} should change something for this to check anything");
|
||||
crate::prior::restore(&mut after.working_registry, &priors);
|
||||
assert_eq!(after.working_registry, before, "restoring {op:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -867,10 +867,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
let delta_reversed = Delta::new(
|
||||
parent,
|
||||
@@ -880,21 +877,28 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone.
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
for delta in session.cloned_deltas().into_iter().skip(before) {
|
||||
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
let network = Network::default();
|
||||
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)),
|
||||
@@ -908,6 +912,7 @@ fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp {
|
||||
op,
|
||||
timestamp: ts(counter, peer),
|
||||
sequence,
|
||||
attributes: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -964,6 +969,31 @@ fn retiring_over_a_gap_lands_beyond_the_prefix() {
|
||||
assert!(marks.covers(second.id()));
|
||||
}
|
||||
|
||||
/// Undo and redo never promote the hot tail, a fold skips undone deltas, and a published commit is not rewound.
|
||||
#[test]
|
||||
fn undo_and_redo_move_only_unpublished_retired_history() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
|
||||
let mut published = session.clone();
|
||||
published.publish_up_to(published.head_rev().expect("a head"));
|
||||
assert!(session.can_undo() && !published.can_undo());
|
||||
|
||||
let retired = |session: &Session, key| holds(&session.retired_registry().attributes, key);
|
||||
session.undo().expect("undo");
|
||||
assert!(!retired(&session, "second") && !retired(&session, "hot"));
|
||||
let folded = session.snapshot_from_history().expect("fold");
|
||||
assert!(holds(&folded.attributes, "first") && !holds(&folded.attributes, "second"));
|
||||
|
||||
session.redo().expect("redo");
|
||||
assert!(retired(&session, "second") && !retired(&session, "hot"));
|
||||
assert!(holds(&session.registry().attributes, "hot"));
|
||||
}
|
||||
|
||||
/// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after.
|
||||
#[test]
|
||||
fn retirement_preserves_the_live_lww_winner() {
|
||||
@@ -985,7 +1015,7 @@ fn retirement_preserves_the_live_lww_winner() {
|
||||
}
|
||||
|
||||
/// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover
|
||||
/// sends them, a fold of some earlier ops.
|
||||
/// sends them, a fold of some earlier ops; restoring each op's priors gives back the registry it applied to.
|
||||
#[test]
|
||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
||||
@@ -999,11 +1029,17 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the ops in order.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
|
||||
/// Folds the ops in order; `check_restore` also checks each op's priors restore the registry it applied to.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)], check_restore: bool) -> crate::Registry {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in ops {
|
||||
let before = check_restore.then(|| (document.working_registry.clone(), crate::prior::capture(&document.working_registry, op)));
|
||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
||||
if let Some((registry, priors)) = before {
|
||||
let mut restored = document.working_registry.clone();
|
||||
crate::prior::restore(&mut restored, &priors);
|
||||
assert_eq!(restored, registry, "restoring what {op:?} overwrote");
|
||||
}
|
||||
}
|
||||
document.working_registry
|
||||
}
|
||||
@@ -1033,7 +1069,7 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
};
|
||||
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
|
||||
// which a fabricated snapshot only does by being constant.
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>());
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>(), false);
|
||||
match rng.below(22) {
|
||||
0 => {
|
||||
// An export list of its own, so additions of different lengths meet.
|
||||
@@ -1181,14 +1217,18 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
ops.push((op, at));
|
||||
}
|
||||
|
||||
let reference = fold(&ops);
|
||||
let reference = fold(&ops, true);
|
||||
for _ in 0..6 {
|
||||
let mut shuffled = ops.clone();
|
||||
for i in (1..shuffled.len()).rev() {
|
||||
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
|
||||
}
|
||||
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
|
||||
assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}");
|
||||
assert_eq!(
|
||||
fold(&shuffled, false),
|
||||
reference,
|
||||
"seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(_))));
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
@@ -244,11 +243,6 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
@@ -258,7 +252,6 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
context_features,
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
..Default::default()
|
||||
@@ -292,9 +285,6 @@ fn test_metadata_preservation() {
|
||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||
|
||||
// Verify context_features is preserved
|
||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
||||
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
|
||||
@@ -353,11 +343,6 @@ fn test_demo_artwork_round_trip() {
|
||||
"{}: call_argument should be preserved for node {:?}",
|
||||
artwork_name, node_id
|
||||
);
|
||||
assert_eq!(
|
||||
orig_node.context_features, conv_node.context_features,
|
||||
"{}: context_features should be preserved for node {:?}",
|
||||
artwork_name, node_id
|
||||
);
|
||||
assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id);
|
||||
assert_eq!(
|
||||
orig_node.skip_deduplication, conv_node.skip_deduplication,
|
||||
|
||||
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
|
||||
@@ -334,8 +457,8 @@ fn convert_node(
|
||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_dependencies: None,
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
+1
-4
@@ -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
|
||||
@@ -53,7 +54,6 @@ once_cell = { workspace = true }
|
||||
web-sys = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
spin = { workspace = true }
|
||||
image = { workspace = true }
|
||||
color = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
@@ -69,9 +69,6 @@ wasm-bindgen = { workspace = true, optional = true }
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
tokio = { workspace = true }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
|
||||
+24
-59
@@ -1,76 +1,17 @@
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
pub use graphene_std::uuid::*;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
pub struct Editor {
|
||||
pub dispatcher: Dispatcher,
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub fn new(
|
||||
environment: Environment,
|
||||
uuid_random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
mut application_io: PlatformApplicationIo,
|
||||
wake: Wake,
|
||||
) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
|
||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
crate::node_graph_executor::replace_application_io(application_io);
|
||||
|
||||
Self { dispatcher }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_local_executor() -> (Self, crate::node_graph_executor::NodeRuntime) {
|
||||
let _ = ENVIRONMENT.set(*Editor::environment());
|
||||
graphene_std::uuid::set_uuid_seed(0);
|
||||
|
||||
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
|
||||
let editor = Self {
|
||||
dispatcher: Dispatcher::with_executor(executor),
|
||||
};
|
||||
|
||||
let mut application_io = PlatformApplicationIo::default();
|
||||
application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
runtime.replace_application_io(application_io);
|
||||
|
||||
(editor, runtime)
|
||||
}
|
||||
|
||||
pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Vec<FrontendMessage> {
|
||||
self.dispatcher.handle_message(message, true);
|
||||
|
||||
std::mem::take(&mut self.dispatcher.responses)
|
||||
}
|
||||
|
||||
pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
self.dispatcher.poll_node_graph_evaluation(responses)
|
||||
}
|
||||
}
|
||||
|
||||
static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
|
||||
impl Editor {
|
||||
#[cfg(not(test))]
|
||||
pub fn environment() -> &'static Environment {
|
||||
ENVIRONMENT.get().expect("Editor environment accessed before initialization")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn environment() -> &'static Environment {
|
||||
&Environment {
|
||||
platform: Platform::Desktop,
|
||||
host: Host::Linux,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -78,6 +19,11 @@ pub struct Environment {
|
||||
pub platform: Platform,
|
||||
pub host: Host,
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) const DEFAULT_ENVIRONMENT: Environment = Environment {
|
||||
platform: Platform::Desktop,
|
||||
host: Host::Linux,
|
||||
};
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Platform {
|
||||
Desktop,
|
||||
@@ -107,6 +53,25 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EnvironmentDisplay {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter, environment: Environment) -> std::fmt::Result;
|
||||
|
||||
fn display(&self, environment: Environment) -> WithEnvironment<'_, Self> {
|
||||
WithEnvironment { value: self, environment }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WithEnvironment<'a, T: ?Sized> {
|
||||
value: &'a T,
|
||||
environment: Environment,
|
||||
}
|
||||
|
||||
impl<T: EnvironmentDisplay + ?Sized> std::fmt::Display for WithEnvironment<'_, T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
self.value.fmt(f, self.environment)
|
||||
}
|
||||
}
|
||||
|
||||
pub const GRAPHITE_RELEASE_SERIES: &str = env!("GRAPHITE_RELEASE_SERIES");
|
||||
pub const GRAPHITE_GIT_COMMIT_BRANCH: Option<&str> = option_env!("GRAPHITE_GIT_COMMIT_BRANCH");
|
||||
pub const GRAPHITE_GIT_COMMIT_HASH: &str = env!("GRAPHITE_GIT_COMMIT_HASH");
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
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, Arc<dyn Clock>>;
|
||||
|
||||
pub struct Builder<E = (), R = (), S = (), N = ()> {
|
||||
editor: E,
|
||||
runtime: R,
|
||||
spawner: S,
|
||||
random_seed: N,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
editor: (),
|
||||
runtime: (),
|
||||
spawner: (),
|
||||
random_seed: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Builder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S, N> Builder<(), R, S, N> {
|
||||
pub fn with_editor(self, editor: ReadyEditorBuilder) -> Builder<ReadyEditorBuilder, R, S, N> {
|
||||
Builder {
|
||||
editor,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, S, N> Builder<E, (), S, N> {
|
||||
pub fn with_runtime(self, runtime: ReadyRuntimeBuilder) -> Builder<E, ReadyRuntimeBuilder, S, N> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, N> Builder<E, R, (), N> {
|
||||
pub fn with_spawner(self, spawner: impl Spawn + Send + Sync + 'static) -> Builder<E, R, Spawner, N> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime: self.runtime,
|
||||
spawner: Arc::new(spawner),
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, S> Builder<E, R, S, ()> {
|
||||
pub fn with_random_seed(self, random_seed: u64) -> Builder<E, R, S, u64> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
pub fn build(self) -> (Editor, NodeRuntime) {
|
||||
let Self {
|
||||
editor,
|
||||
runtime,
|
||||
spawner,
|
||||
random_seed,
|
||||
} = self;
|
||||
let EditorBuilder {
|
||||
wake: editor_wake,
|
||||
environment,
|
||||
resource_storage,
|
||||
document_store,
|
||||
} = editor;
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
|
||||
let (executor, mut node_runtime) = NodeGraphExecutor::new(editor_wake.clone());
|
||||
|
||||
let future_message_handler = FutureMessageHandler::new(spawner.clone(), editor_wake);
|
||||
let dispatcher = Dispatcher::new(environment, resource_storage, document_store, executor, future_message_handler);
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EditorBuilder<W = (), E = (), R = (), D = ()> {
|
||||
wake: W,
|
||||
environment: E,
|
||||
resource_storage: R,
|
||||
document_store: D,
|
||||
}
|
||||
|
||||
impl EditorBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
environment: (),
|
||||
resource_storage: (),
|
||||
document_store: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EditorBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, D> EditorBuilder<(), E, R, D> {
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> EditorBuilder<Wake, E, R, D> {
|
||||
EditorBuilder {
|
||||
wake: Arc::new(wake),
|
||||
environment: self.environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, R, D> EditorBuilder<W, (), R, D> {
|
||||
pub fn with_environment(self, environment: Environment) -> EditorBuilder<W, Environment, R, D> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, E, D> EditorBuilder<W, E, (), D> {
|
||||
pub fn with_resource_storage(self, resource_storage: Arc<dyn ResourceStorage>) -> EditorBuilder<W, E, Arc<dyn ResourceStorage>, D> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment: self.environment,
|
||||
resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
pub fn with_document_store(self, document_store: Arc<dyn DocumentStore>) -> EditorBuilder<W, E, R, Arc<dyn DocumentStore>> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment: self.environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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: (),
|
||||
clock: (),
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
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, C> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.;
|
||||
@@ -46,7 +46,6 @@ pub const SNAP_POINT_TOLERANCE: f64 = 5.;
|
||||
pub const DRAG_THRESHOLD: f64 = 1.;
|
||||
|
||||
// TRANSFORMING LAYER
|
||||
pub const ROTATE_INCREMENT: f64 = 15.;
|
||||
pub const SCALE_INCREMENT: f64 = 0.1;
|
||||
pub const SLOWING_DIVISOR: f64 = 10.;
|
||||
pub const NUDGE_AMOUNT: f64 = 1.;
|
||||
@@ -108,7 +107,6 @@ pub const MANIPULATOR_GROUP_MARKER_SIZE: f64 = 6.;
|
||||
pub const SELECTION_THRESHOLD: f64 = 10.;
|
||||
pub const DRILL_THROUGH_THRESHOLD: f64 = 10.;
|
||||
pub const HIDE_HANDLE_DISTANCE: f64 = 3.;
|
||||
pub const HANDLE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
pub const SEGMENT_INSERTION_DISTANCE: f64 = 5.;
|
||||
pub const SEGMENT_OVERLAY_SIZE: f64 = 10.;
|
||||
pub const SEGMENT_SELECTED_THICKNESS: f64 = 3.;
|
||||
@@ -126,9 +124,6 @@ pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
|
||||
// SPLINE TOOL
|
||||
pub const PATH_JOIN_THRESHOLD: f64 = 5.;
|
||||
|
||||
// LINE TOOL
|
||||
pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
|
||||
// BRUSH TOOL
|
||||
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
|
||||
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
|
||||
@@ -139,11 +134,10 @@ pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
|
||||
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
|
||||
|
||||
// GIZMOS
|
||||
pub const POINT_RADIUS_HANDLE_SNAP_THRESHOLD: f64 = 8.;
|
||||
pub const SPIRAL_END_HOVER_RADIUS: f64 = 8.;
|
||||
pub const POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD: f64 = 7.9;
|
||||
pub const NUMBER_OF_POINTS_DIAL_SPOKE_EXTENSION: f64 = 1.2;
|
||||
pub const NUMBER_OF_POINTS_DIAL_SPOKE_LENGTH: f64 = 10.;
|
||||
pub const ARC_SNAP_THRESHOLD: f64 = 5.;
|
||||
pub const ARC_SWEEP_GIZMO_RADIUS: f64 = 14.;
|
||||
pub const ARC_SWEEP_GIZMO_TEXT_HEIGHT: f64 = 12.;
|
||||
pub const GIZMO_HIDE_THRESHOLD: f64 = 20.;
|
||||
|
||||
+65
-43
@@ -1,3 +1,4 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
||||
use crate::messages::defer::DeferMessageContext;
|
||||
use crate::messages::dialog::DialogMessageContext;
|
||||
@@ -7,18 +8,20 @@ use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Debug)]
|
||||
pub struct Dispatcher {
|
||||
environment: Environment,
|
||||
message_queues: Vec<VecDeque<Message>>,
|
||||
pub responses: Vec<FrontendMessage>,
|
||||
pub frontend_update_messages: Vec<Message>,
|
||||
pub message_handlers: DispatcherMessageHandlers,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Debug)]
|
||||
pub struct DispatcherMessageHandlers {
|
||||
animation_message_handler: AnimationMessageHandler,
|
||||
app_window_message_handler: AppWindowMessageHandler,
|
||||
@@ -42,17 +45,27 @@ pub struct DispatcherMessageHandlers {
|
||||
}
|
||||
|
||||
impl DispatcherMessageHandlers {
|
||||
pub fn with_resource_storage(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
fn new(environment: Environment, executor: NodeGraphExecutor, document_store: Arc<dyn document_container::store::DocumentStore>, future_message_handler: FutureMessageHandler) -> Self {
|
||||
Self {
|
||||
resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
Self {
|
||||
portfolio_message_handler: PortfolioMessageHandler::with_executor(executor),
|
||||
..Self::default()
|
||||
animation_message_handler: Default::default(),
|
||||
app_window_message_handler: Default::default(),
|
||||
future_message_handler,
|
||||
broadcast_message_handler: Default::default(),
|
||||
clipboard_message_handler: Default::default(),
|
||||
color_picker_message_handler: Default::default(),
|
||||
debug_message_handler: Default::default(),
|
||||
defer_message_handler: Default::default(),
|
||||
dialog_message_handler: Default::default(),
|
||||
input_preprocessor_message_handler: Default::default(),
|
||||
key_mapping_message_handler: KeyMappingMessageHandler::new(environment),
|
||||
layout_message_handler: Default::default(),
|
||||
menu_bar_message_handler: Default::default(),
|
||||
network_message_handler: Default::default(),
|
||||
portfolio_message_handler: PortfolioMessageHandler::new(executor, document_store),
|
||||
preferences_message_handler: Default::default(),
|
||||
resource_storage_message_handler: Default::default(),
|
||||
tool_message_handler: Default::default(),
|
||||
viewport_message_handler: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,20 +115,21 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
|
||||
let mut s = Self::default();
|
||||
pub fn new(
|
||||
environment: Environment,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
executor: NodeGraphExecutor,
|
||||
future_message_handler: FutureMessageHandler,
|
||||
) -> Self {
|
||||
let mut s = Self {
|
||||
environment,
|
||||
message_queues: Vec::new(),
|
||||
responses: Vec::new(),
|
||||
frontend_update_messages: Vec::new(),
|
||||
message_handlers: DispatcherMessageHandlers::new(environment, executor, document_store, future_message_handler),
|
||||
};
|
||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::new(
|
||||
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
|
||||
Arc::new(document_container::store::MemoryStore::default()),
|
||||
);
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
}
|
||||
|
||||
@@ -144,13 +158,6 @@ impl Dispatcher {
|
||||
pub fn handle_message<T: Into<Message>>(&mut self, message: T, process_after_all_current: bool) {
|
||||
let message = message.into();
|
||||
|
||||
// Drain async results into the queue before processing the new message.
|
||||
let mut async_results = VecDeque::new();
|
||||
self.message_handlers.future_message_handler.drain_results(&mut async_results);
|
||||
if !async_results.is_empty() {
|
||||
Self::schedule_execution(&mut self.message_queues, true, async_results);
|
||||
}
|
||||
|
||||
// If we are not maintaining the buffer, simply add to the current queue
|
||||
Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]);
|
||||
|
||||
@@ -201,7 +208,7 @@ impl Dispatcher {
|
||||
self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::Future(message) => {
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Clipboard(message) => {
|
||||
@@ -237,6 +244,7 @@ impl Dispatcher {
|
||||
message,
|
||||
&mut queue,
|
||||
InputPreprocessorMessageContext {
|
||||
environment: self.environment,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
},
|
||||
);
|
||||
@@ -245,13 +253,22 @@ impl Dispatcher {
|
||||
let input = &self.message_handlers.input_preprocessor_message_handler;
|
||||
let actions = self.collect_actions();
|
||||
|
||||
self.message_handlers
|
||||
.key_mapping_message_handler
|
||||
.process_message(message, &mut queue, KeyMappingMessageContext { input, actions });
|
||||
self.message_handlers.key_mapping_message_handler.process_message(
|
||||
message,
|
||||
&mut queue,
|
||||
KeyMappingMessageContext {
|
||||
environment: self.environment,
|
||||
input,
|
||||
actions,
|
||||
},
|
||||
);
|
||||
}
|
||||
Message::Layout(message) => {
|
||||
let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find);
|
||||
let context = LayoutMessageContext { action_input_mapping };
|
||||
let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find, self.environment);
|
||||
let context = LayoutMessageContext {
|
||||
environment: self.environment,
|
||||
action_input_mapping,
|
||||
};
|
||||
|
||||
self.message_handlers.layout_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
@@ -268,10 +285,12 @@ impl Dispatcher {
|
||||
message,
|
||||
&mut queue,
|
||||
PortfolioMessageContext {
|
||||
environment: self.environment,
|
||||
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
||||
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,
|
||||
@@ -286,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;
|
||||
@@ -377,10 +398,15 @@ impl Dispatcher {
|
||||
Message::Viewport(message) => {
|
||||
self.message_handlers.viewport_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::NoOp => {}
|
||||
// Messages
|
||||
Message::Wake => {
|
||||
queue.add(PortfolioMessage::PollNodeGraphEvaluation);
|
||||
queue.add(FutureMessage::Drain);
|
||||
}
|
||||
Message::Batched { messages } => {
|
||||
messages.into_iter().for_each(|message| self.handle_message(message, false));
|
||||
}
|
||||
Message::NoOp => {}
|
||||
}
|
||||
|
||||
// If there are child messages, append the queue to the list of queues
|
||||
@@ -411,10 +437,6 @@ impl Dispatcher {
|
||||
list
|
||||
}
|
||||
|
||||
pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
self.message_handlers.portfolio_message_handler.poll_node_graph_evaluation(responses)
|
||||
}
|
||||
|
||||
/// Create the tree structure for logging the messages as a tree
|
||||
fn create_indents(queues: &[VecDeque<Message>]) -> String {
|
||||
String::from_iter(queues.iter().enumerate().skip(1).map(|(index, queue)| {
|
||||
|
||||
@@ -11,10 +11,12 @@ mod macros;
|
||||
extern crate log;
|
||||
|
||||
pub mod application;
|
||||
pub mod builder;
|
||||
pub mod consts;
|
||||
pub mod dispatcher;
|
||||
pub mod messages;
|
||||
pub mod node_graph_executor;
|
||||
pub mod task;
|
||||
#[cfg(test)]
|
||||
pub mod test_utils;
|
||||
pub mod utility_traits;
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -86,8 +100,8 @@ pub enum AppWindowPlatform {
|
||||
Linux,
|
||||
}
|
||||
|
||||
impl From<&Environment> for AppWindowPlatform {
|
||||
fn from(environment: &Environment) -> Self {
|
||||
impl From<Environment> for AppWindowPlatform {
|
||||
fn from(environment: Environment) -> Self {
|
||||
match (environment.platform, environment.host) {
|
||||
(Platform::Web, _) => AppWindowPlatform::Web,
|
||||
(Platform::Desktop, Host::Linux) => AppWindowPlatform::Linux,
|
||||
|
||||
@@ -12,8 +12,9 @@ use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
use kurbo::ParamCurve;
|
||||
use std::sync::Arc;
|
||||
@@ -434,18 +435,27 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
// Materialize the copied snapshot so its points and segments can replay with fresh IDs
|
||||
let (mut pasted_vector, mut pasted_paths) = (Vector::default(), List::new());
|
||||
new_vector.apply(&mut pasted_vector, &mut pasted_paths);
|
||||
|
||||
// Create new point IDs and add those into the existing Vector path
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
for index in pasted_vector.anchor_indices(&pasted_paths) {
|
||||
let (Some(point), Some(position)) = (pasted_vector.point_id_at(index as u32), pasted_vector.position(index)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
// Create new segment IDs and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, segment, start, end) in new_vector.segment_iter() {
|
||||
let path_beginnings = pasted_vector.path_beginnings(&pasted_paths);
|
||||
for (segment_id, segment, start, end) in pasted_vector.segment_iter(&pasted_paths) {
|
||||
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
|
||||
warn!("Skipping pasted vector segment with an unknown endpoint");
|
||||
continue;
|
||||
@@ -465,10 +475,19 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let points = [start_point, end_point];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// Every pasted path stays a path of its own, even where it sets out from the end of another
|
||||
if path_beginnings.contains(&segment_id) {
|
||||
let modification_type = VectorModificationType::SetPathBreak {
|
||||
segment: new_segment_id,
|
||||
breaks: true,
|
||||
};
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
for handles in pasted_vector.colinear_pairs(&pasted_paths) {
|
||||
let to_new_handle = |handle: HandleId| -> Option<HandleId> {
|
||||
Some(HandleId {
|
||||
ty: handle.ty,
|
||||
|
||||
@@ -5,7 +5,7 @@ use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::VectorModification;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContentRaw {
|
||||
@@ -20,7 +20,7 @@ pub enum ClipboardContent {
|
||||
Image { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
||||
pub type ClipboardVectorEntry = (LayerNodeIdentifier, VectorModification, DAffine2);
|
||||
|
||||
/// An entry in the `graphite:` clipboard payload.
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState, RenderStatus};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||
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>,
|
||||
@@ -246,6 +259,9 @@ pub enum FrontendMessage {
|
||||
UpdateDocumentArtwork {
|
||||
svg: String,
|
||||
},
|
||||
UpdateRenderStatus {
|
||||
status: RenderStatus,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<RasterizedImage>,
|
||||
},
|
||||
@@ -291,8 +307,8 @@ pub enum FrontendMessage {
|
||||
UpdateNodeGraphNodes {
|
||||
nodes: Vec<FrontendNode>,
|
||||
},
|
||||
UpdateNodeGraphErrorDiagnostic {
|
||||
error: Option<NodeGraphErrorDiagnostic>,
|
||||
UpdateNodeGraphErrorDiagnostics {
|
||||
errors: Vec<NodeGraphErrorDiagnostic>,
|
||||
},
|
||||
UpdateVisibleNodes {
|
||||
nodes: Vec<NodeId>,
|
||||
@@ -379,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))]
|
||||
@@ -42,6 +54,15 @@ pub enum MouseCursorIcon {
|
||||
Rotate,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RenderStatus {
|
||||
#[default]
|
||||
Rendering,
|
||||
Error,
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FileType {
|
||||
|
||||
@@ -11,6 +11,5 @@ pub enum FutureMessage {
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
future: MessageFuture,
|
||||
},
|
||||
/// Sent by a wake callback to nudge an idle event loop into a dispatch tick.
|
||||
Wake,
|
||||
Drain,
|
||||
}
|
||||
@@ -6,19 +6,16 @@ use dyn_any::WasmNotSend;
|
||||
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
|
||||
|
||||
use crate::messages::prelude::*;
|
||||
use crate::task::Spawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + 'static>>;
|
||||
|
||||
/// Invoked by the spawner after a result is sent, to wake the platform event loop.
|
||||
/// Invoked after a result is sent, to wake the platform event loop.
|
||||
pub type Wake = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
fn noop_wake() -> Wake {
|
||||
Arc::new(|| {})
|
||||
}
|
||||
|
||||
/// One-shot async work whose result re-enters the dispatcher as a [`Message`].
|
||||
/// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -62,52 +59,24 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Platform-specific async-task executor.
|
||||
/// Runs `future`, sends the resolved message on `results`, then calls `wake`.
|
||||
pub trait MessageSpawner: Send + Sync {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake);
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageContext {}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageHandler {
|
||||
#[cfg_attr(test, expect(dead_code))]
|
||||
spawner: Arc<dyn MessageSpawner>,
|
||||
spawner: Spawner,
|
||||
wake: Wake,
|
||||
#[cfg_attr(test, expect(dead_code))]
|
||||
results_sender: UnboundedSender<Message>,
|
||||
results_receiver: UnboundedReceiver<Message>,
|
||||
}
|
||||
|
||||
impl FutureMessageHandler {
|
||||
pub fn with_wake(wake: Wake) -> Self {
|
||||
pub fn new(spawner: Spawner, wake: Wake) -> Self {
|
||||
let (results_sender, results_receiver) = unbounded();
|
||||
Self {
|
||||
spawner: default_spawner(),
|
||||
spawner,
|
||||
wake,
|
||||
results_sender,
|
||||
results_receiver,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_wake(&mut self, wake: Wake) {
|
||||
self.wake = wake;
|
||||
}
|
||||
|
||||
/// Pull every resolved async result into `out`.
|
||||
pub fn drain_results(&mut self, out: &mut VecDeque<Message>) {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
out.push_back(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FutureMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self::with_wake(noop_wake())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FutureMessageHandler {
|
||||
@@ -117,87 +86,25 @@ impl std::fmt::Debug for FutureMessageHandler {
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandler {
|
||||
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
|
||||
impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
|
||||
fn process_message(&mut self, message: FutureMessage, responses: &mut VecDeque<Message>, _context: ()) {
|
||||
match message {
|
||||
FutureMessage::Await { future } => {
|
||||
#[cfg(not(test))]
|
||||
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
|
||||
|
||||
// For tests, block on the future to ensure the result is available when validating editor state afterwards.
|
||||
#[cfg(test)]
|
||||
{
|
||||
let message = futures::executor::block_on(future.into_future());
|
||||
_responses.push_back(message);
|
||||
}
|
||||
let results = self.results_sender.clone();
|
||||
let wake = self.wake.clone();
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
}));
|
||||
}
|
||||
FutureMessage::Wake => {
|
||||
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
|
||||
FutureMessage::Drain => {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
responses.push_back(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(FutureMessageDiscriminant;);
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(TokioSpawner::default())
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(WasmSpawner)
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
struct TokioSpawner {
|
||||
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
|
||||
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self { runtime: std::sync::OnceLock::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
fn runtime(&self) -> &tokio::runtime::Runtime {
|
||||
self.runtime.get_or_init(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct async-message tokio runtime")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl MessageSpawner for TokioSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
self.runtime().spawn(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl MessageSpawner for WasmSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,4 @@ mod future_message_handler;
|
||||
#[doc(inline)]
|
||||
pub use future_message::{FutureMessage, FutureMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
|
||||
pub use future_message_handler::{FutureMessageHandler, MessageFuture, Wake};
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::utility_types::keyboard::KeysGroup;
|
||||
use super::utility_types::misc::Mapping;
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -11,7 +11,7 @@ pub struct InputMapperMessageContext<'a> {
|
||||
pub actions: ActionList,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct InputMapperMessageHandler {
|
||||
mapping: Mapping,
|
||||
}
|
||||
@@ -29,11 +29,15 @@ impl MessageHandler<InputMapperMessage, InputMapperMessageContext<'_>> for Input
|
||||
}
|
||||
|
||||
impl InputMapperMessageHandler {
|
||||
pub fn new(mapping: Mapping) -> Self {
|
||||
Self { mapping }
|
||||
}
|
||||
|
||||
pub fn set_mapping(&mut self, mapping: Mapping) {
|
||||
self.mapping = mapping;
|
||||
}
|
||||
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option<KeysGroup> {
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option<KeysGroup> {
|
||||
let all_key_mapping_entries = std::iter::empty()
|
||||
.chain(self.mapping.key_up.iter())
|
||||
.chain(self.mapping.key_down.iter())
|
||||
@@ -49,7 +53,7 @@ impl InputMapperMessageHandler {
|
||||
let found_actions = all_mapping_entries.filter(|entry| entry.action.to_discriminant() == *action_to_find);
|
||||
|
||||
// Get the `Key` for this platform's accelerator key
|
||||
let platform_accel_key = if Editor::environment().is_mac() { Key::Command } else { Key::Control };
|
||||
let platform_accel_key = if environment.is_mac() { Key::Command } else { Key::Control };
|
||||
|
||||
let entry_to_key = |entry: &MappingEntry| {
|
||||
// Get the modifier keys for the entry (and convert them to Key)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates};
|
||||
@@ -13,20 +13,20 @@ use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpd
|
||||
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use glam::DVec2;
|
||||
|
||||
impl From<MappingVariant> for Mapping {
|
||||
fn from(value: MappingVariant) -> Self {
|
||||
match value {
|
||||
MappingVariant::Default => input_mappings(false),
|
||||
MappingVariant::ZoomWithScroll => input_mappings(true),
|
||||
impl Mapping {
|
||||
pub fn new(variant: MappingVariant, environment: Environment) -> Self {
|
||||
match variant {
|
||||
MappingVariant::Default => input_mappings(false, environment),
|
||||
MappingVariant::ZoomWithScroll => input_mappings(true, environment),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mapping {
|
||||
use InputMapperMessage::*;
|
||||
use Key::*;
|
||||
|
||||
let is_mac = Editor::environment().is_mac();
|
||||
let is_mac = environment.is_mac();
|
||||
|
||||
// NOTICE:
|
||||
// If a new mapping you added here isn't working (and perhaps another lower-precedence one is instead), make sure to advertise
|
||||
@@ -59,6 +59,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
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),
|
||||
@@ -89,10 +90,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Up, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Right, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Left, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Left }),
|
||||
//
|
||||
// TransformLayerMessage
|
||||
entry!(KeyDown(Enter); action_dispatch=TransformLayerMessage::ApplyTransformOperation { final_transform: true }),
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext;
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::misc::Mapping;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct KeyMappingMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub input: &'a InputPreprocessorMessageHandler,
|
||||
pub actions: ActionList,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct KeyMappingMessageHandler {
|
||||
mapping_handler: InputMapperMessageHandler,
|
||||
}
|
||||
@@ -16,21 +20,27 @@ pub struct KeyMappingMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<KeyMappingMessage, KeyMappingMessageContext<'_>> for KeyMappingMessageHandler {
|
||||
fn process_message(&mut self, message: KeyMappingMessage, responses: &mut VecDeque<Message>, context: KeyMappingMessageContext) {
|
||||
let KeyMappingMessageContext { input, actions } = context;
|
||||
let KeyMappingMessageContext { environment, input, actions } = context;
|
||||
|
||||
match message {
|
||||
// Sub-messages
|
||||
KeyMappingMessage::Lookup(input_message) => self.mapping_handler.process_message(input_message, responses, InputMapperMessageContext { input, actions }),
|
||||
|
||||
// Messages
|
||||
KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(mapping.into()),
|
||||
KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(Mapping::new(mapping, environment)),
|
||||
}
|
||||
}
|
||||
advertise_actions!();
|
||||
}
|
||||
|
||||
impl KeyMappingMessageHandler {
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option<KeysGroup> {
|
||||
self.mapping_handler.action_input_mapping(action_to_find)
|
||||
pub fn new(environment: Environment) -> Self {
|
||||
Self {
|
||||
mapping_handler: InputMapperMessageHandler::new(Mapping::new(MappingVariant::Default, environment)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option<KeysGroup> {
|
||||
self.mapping_handler.action_input_mapping(action_to_find, environment)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::{Environment, EnvironmentDisplay};
|
||||
use crate::messages::prelude::*;
|
||||
use bitflags::bitflags;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
@@ -243,9 +243,9 @@ pub enum Key {
|
||||
_KeysVariantCount, // This has to be the last element in the enum
|
||||
}
|
||||
|
||||
impl fmt::Display for Key {
|
||||
impl EnvironmentDisplay for Key {
|
||||
// TODO: Relevant key labels should be localized when we get around to implementing localization/internationalization
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
|
||||
fn fmt(&self, f: &mut fmt::Formatter, environment: Environment) -> std::fmt::Result {
|
||||
let key_name = format!("{self:?}");
|
||||
|
||||
// Writing system keys
|
||||
@@ -258,7 +258,7 @@ impl fmt::Display for Key {
|
||||
return write!(f, "{}", key_name.chars().skip(KEY_PREFIX.len()).collect::<String>());
|
||||
}
|
||||
|
||||
let is_mac = Editor::environment().is_mac();
|
||||
let is_mac = environment.is_mac();
|
||||
|
||||
let name = match self {
|
||||
// Writing system keys
|
||||
@@ -345,36 +345,10 @@ pub const NUMBER_OF_KEYS: usize = Key::_KeysVariantCount as usize - 1;
|
||||
// =========
|
||||
|
||||
/// Only `Key`s that exist on a physical keyboard should be used.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KeysGroup(pub Vec<Key>);
|
||||
|
||||
impl fmt::Display for KeysGroup {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
const JOINER_MARK: &str = " ";
|
||||
|
||||
let mut joined = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let key_is_modifier = matches!(*key, Key::Control | Key::Command | Key::Alt | Key::Shift | Key::Meta | Key::Accel);
|
||||
|
||||
if Editor::environment().is_mac() && key_is_modifier {
|
||||
key.to_string()
|
||||
} else {
|
||||
key.to_string() + JOINER_MARK
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
|
||||
// Cut the joining character off the end, if present
|
||||
if joined.ends_with(JOINER_MARK) {
|
||||
joined.truncate(joined.len() - JOINER_MARK.len());
|
||||
}
|
||||
|
||||
write!(f, "{joined}")
|
||||
}
|
||||
}
|
||||
|
||||
// ==========
|
||||
// LabeledKey
|
||||
// ==========
|
||||
@@ -425,13 +399,16 @@ pub enum LabeledKeyOrMouseMotion {
|
||||
MouseMotion(MouseMotion),
|
||||
}
|
||||
|
||||
impl From<Key> for LabeledKeyOrMouseMotion {
|
||||
fn from(key: Key) -> Self {
|
||||
impl LabeledKeyOrMouseMotion {
|
||||
pub fn new(key: Key, environment: Environment) -> Self {
|
||||
match key {
|
||||
Key::MouseLeft => Self::MouseMotion(MouseMotion::Lmb),
|
||||
Key::MouseRight => Self::MouseMotion(MouseMotion::Rmb),
|
||||
Key::MouseMiddle => Self::MouseMotion(MouseMotion::Mmb),
|
||||
_ => Self::Key(LabeledKey { key, label: key.to_string() }),
|
||||
_ => Self::Key(LabeledKey {
|
||||
key,
|
||||
label: key.display(environment).to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -444,9 +421,9 @@ impl From<Key> for LabeledKeyOrMouseMotion {
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct LabeledShortcut(pub Vec<LabeledKeyOrMouseMotion>);
|
||||
|
||||
impl From<KeysGroup> for LabeledShortcut {
|
||||
fn from(keys_group: KeysGroup) -> Self {
|
||||
Self(keys_group.0.into_iter().map(|key| key.into()).collect())
|
||||
impl LabeledShortcut {
|
||||
pub fn new(keys_group: KeysGroup, environment: Environment) -> Self {
|
||||
Self(keys_group.0.into_iter().map(|key| LabeledKeyOrMouseMotion::new(key, environment)).collect())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -163,8 +163,8 @@ macro_rules! action_shortcut {
|
||||
|
||||
macro_rules! action_shortcut_manual {
|
||||
($($keys:expr),*) => {
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut(
|
||||
crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Keys(
|
||||
crate::messages::input_mapper::utility_types::keyboard::KeysGroup(vec![$($keys),*]),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -18,12 +18,6 @@ pub struct Mapping {
|
||||
pub pointer_shake: KeyMappingEntries,
|
||||
}
|
||||
|
||||
impl Default for Mapping {
|
||||
fn default() -> Self {
|
||||
MappingVariant::Default.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn match_input_message(&self, message: InputMapperMessage, keyboard_state: &KeyStates, actions: ActionList) -> Option<Message> {
|
||||
let list = self.associated_entries(&message);
|
||||
@@ -113,19 +107,20 @@ pub struct MappingEntry {
|
||||
pub enum ActionShortcut {
|
||||
#[serde(skip)]
|
||||
Action(MessageDiscriminant),
|
||||
#[serde(skip)]
|
||||
Keys(KeysGroup),
|
||||
#[serde(rename = "shortcut")]
|
||||
Shortcut(LabeledShortcut),
|
||||
}
|
||||
|
||||
impl ActionShortcut {
|
||||
pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
if let Self::Action(action) = self {
|
||||
if let Some(keys) = action_input_mapping(action) {
|
||||
*self = Self::Shortcut(keys.into());
|
||||
} else {
|
||||
*self = Self::Shortcut(KeysGroup::default().into());
|
||||
}
|
||||
}
|
||||
pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
let keys = match self {
|
||||
Self::Action(action) => action_input_mapping(action).unwrap_or_default(),
|
||||
Self::Keys(keys) => std::mem::take(keys),
|
||||
Self::Shortcut(_) => return,
|
||||
};
|
||||
*self = Self::Shortcut(LabeledShortcut::new(keys, environment));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
@@ -8,6 +8,7 @@ use std::time::Duration;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct InputPreprocessorMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
@@ -35,12 +36,12 @@ enum DoubleTapState {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext<'a>> for InputPreprocessorMessageHandler {
|
||||
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext<'a>) {
|
||||
let InputPreprocessorMessageContext { viewport } = context;
|
||||
let InputPreprocessorMessageContext { environment, viewport } = context;
|
||||
|
||||
match message {
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -57,7 +58,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
}
|
||||
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
self.keyboard.set(key as usize);
|
||||
|
||||
if !key_repeat {
|
||||
@@ -80,7 +81,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
responses.add(InputMapperMessage::KeyDown(key));
|
||||
}
|
||||
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
self.keyboard.unset(key as usize);
|
||||
if !key_repeat {
|
||||
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
|
||||
@@ -101,15 +102,18 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
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, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -121,7 +125,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -129,7 +133,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -143,7 +147,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -199,7 +203,7 @@ impl InputPreprocessorMessageHandler {
|
||||
self.mouse = new_state;
|
||||
}
|
||||
|
||||
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, responses: &mut VecDeque<Message>) {
|
||||
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, environment: Environment, responses: &mut VecDeque<Message>) {
|
||||
let is_key_pressed = |key_to_check: ModifierKeys| pressed_modifier_keys.contains(key_to_check);
|
||||
|
||||
// Update the state of the concrete modifier keys based on the source state
|
||||
@@ -208,14 +212,14 @@ impl InputPreprocessorMessageHandler {
|
||||
self.update_modifier_key(Key::Control, is_key_pressed(ModifierKeys::CONTROL), responses);
|
||||
|
||||
// Update the state of either the concrete Meta or the Command keys based on which one is applicable for this platform
|
||||
let meta_or_command = match Editor::environment().is_mac() {
|
||||
let meta_or_command = match environment.is_mac() {
|
||||
true => Key::Command,
|
||||
false => Key::Meta,
|
||||
};
|
||||
self.update_modifier_key(meta_or_command, is_key_pressed(ModifierKeys::META_OR_COMMAND), responses);
|
||||
|
||||
// Update the state of the virtual Accel key (the primary accelerator key) based on the source state of the Control or Command key, whichever is relevant on this platform
|
||||
let accel_virtual_key_state = match Editor::environment().is_mac() {
|
||||
let accel_virtual_key_state = match environment.is_mac() {
|
||||
true => is_key_pressed(ModifierKeys::META_OR_COMMAND),
|
||||
false => is_key_pressed(ModifierKeys::CONTROL),
|
||||
};
|
||||
@@ -238,6 +242,7 @@ impl InputPreprocessorMessageHandler {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::DoubleTapState;
|
||||
use crate::application::DEFAULT_ENVIRONMENT;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
|
||||
@@ -257,6 +262,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -276,6 +282,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -295,6 +302,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -316,6 +324,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -336,6 +345,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -381,6 +391,7 @@ mod test {
|
||||
message,
|
||||
responses,
|
||||
InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::math_expression::{
|
||||
MathExpressionTokens, math_expression_completions, math_expression_error, math_expression_error_ranges, math_expression_number, math_expression_tokens,
|
||||
@@ -12,6 +13,7 @@ use std::collections::HashMap;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct LayoutMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub action_input_mapping: &'a dyn Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
}
|
||||
|
||||
@@ -23,6 +25,7 @@ pub struct LayoutMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHandler {
|
||||
fn process_message(&mut self, message: LayoutMessage, responses: &mut std::collections::VecDeque<Message>, context: LayoutMessageContext) {
|
||||
let environment = context.environment;
|
||||
let action_input_mapping = &context.action_input_mapping;
|
||||
|
||||
match message {
|
||||
@@ -36,7 +39,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
return;
|
||||
};
|
||||
// Resend that diff
|
||||
self.send_diff(vec![diff], layout_target, responses, action_input_mapping);
|
||||
self.send_diff(vec![diff], layout_target, responses, action_input_mapping, environment);
|
||||
}
|
||||
LayoutMessage::ResendAllLayouts => {
|
||||
// Collect non-empty layouts and their indices, then clear the stored copies so diffs compute as full re-sends
|
||||
@@ -49,11 +52,11 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
.collect();
|
||||
|
||||
for (layout_target, layout) in layouts_to_resend {
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
LayoutMessage::SendLayout { layout, layout_target } => {
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment);
|
||||
}
|
||||
LayoutMessage::DestroyLayout { layout_target } => {
|
||||
if let Some(layout) = self.layouts.get_mut(layout_target as usize) {
|
||||
@@ -575,6 +578,7 @@ impl LayoutMessageHandler {
|
||||
mut new_layout: Layout,
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
environment: Environment,
|
||||
) {
|
||||
// Collect CheckboxId mappings from new layout
|
||||
let mut checkbox_map = HashMap::new();
|
||||
@@ -605,12 +609,19 @@ impl LayoutMessageHandler {
|
||||
}];
|
||||
}
|
||||
|
||||
self.send_diff(widget_diffs, layout_target, responses, action_input_mapping);
|
||||
self.send_diff(widget_diffs, layout_target, responses, action_input_mapping, environment);
|
||||
}
|
||||
|
||||
/// Send a diff to the frontend based on the layout target.
|
||||
fn send_diff(&self, mut diff: Vec<WidgetDiff>, layout_target: LayoutTarget, responses: &mut VecDeque<Message>, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping));
|
||||
fn send_diff(
|
||||
&self,
|
||||
mut diff: Vec<WidgetDiff>,
|
||||
layout_target: LayoutTarget,
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
environment: Environment,
|
||||
) {
|
||||
diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping, environment));
|
||||
|
||||
if matches!(layout_target, LayoutTarget::_LayoutTargetLength) {
|
||||
panic!("`_LayoutTargetLength` is not a valid `LayoutTarget` and is used for array indexing");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::application::{Environment, generate_uuid};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
@@ -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.
|
||||
@@ -423,9 +425,15 @@ pub struct NodeSection {
|
||||
/// For a section in the chain feeding another section's input, the wire drawn up to the section above, which its node's output feeds.
|
||||
#[serde(rename = "outputWire")]
|
||||
pub output_wire: Option<SectionWire>,
|
||||
/// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for the layer whose stack feeds the bottom of a chain).
|
||||
/// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for a layer feeding a chain, or feeding or fed by the selected layer).
|
||||
#[serde(rename = "nodeReference")]
|
||||
pub node_reference: bool,
|
||||
/// For a section referring to layers that take the wire from the section below into their content, rather than from their bottom, that wire turning in from the left past its indent.
|
||||
#[serde(rename = "contentWire")]
|
||||
pub content_wire: Option<SectionWire>,
|
||||
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
|
||||
#[serde(rename = "contentWireContinues")]
|
||||
pub content_wire_continues: bool,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose Inspector section this is.
|
||||
@@ -477,6 +485,8 @@ impl LayoutGroup {
|
||||
chain_wire: None,
|
||||
output_wire: None,
|
||||
node_reference: false,
|
||||
content_wire: None,
|
||||
content_wire_continues: false,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -582,6 +592,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: current_chain_wire,
|
||||
output_wire: current_output_wire,
|
||||
node_reference: current_node_reference,
|
||||
content_wire: current_content_wire,
|
||||
content_wire_continues: current_content_wire_continues,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
@@ -596,6 +608,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -613,6 +627,8 @@ impl Diffable for LayoutGroup {
|
||||
|| *current_chain_wire != new_chain_wire
|
||||
|| *current_output_wire != new_output_wire
|
||||
|| *current_node_reference != new_node_reference
|
||||
|| *current_content_wire != new_content_wire
|
||||
|| *current_content_wire_continues != new_content_wire_continues
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
@@ -626,6 +642,8 @@ impl Diffable for LayoutGroup {
|
||||
*current_chain_wire = new_chain_wire;
|
||||
*current_output_wire = new_output_wire;
|
||||
*current_node_reference = new_node_reference;
|
||||
*current_content_wire = new_content_wire;
|
||||
*current_content_wire_continues = new_content_wire_continues;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -641,6 +659,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -996,7 +1016,7 @@ pub enum DiffUpdate {
|
||||
|
||||
impl DiffUpdate {
|
||||
/// Append the keyboard shortcut to the tooltip where applicable
|
||||
pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
// Go through each widget to convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` and append the key combination to the widget tooltip
|
||||
let convert_tooltip = |widget_instance: &mut WidgetInstance| {
|
||||
// Handle all the widgets that have tooltips
|
||||
@@ -1033,7 +1053,7 @@ impl DiffUpdate {
|
||||
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = tooltip_shortcut {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
|
||||
// Handle RadioInput separately because its tooltips are children of the widget
|
||||
@@ -1041,23 +1061,23 @@ impl DiffUpdate {
|
||||
for radio_entry_data in &mut radio_input.entries {
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = radio_entry_data.tooltip_shortcut.as_mut() {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Recursively fill menu list entries with their realized shortcut keys specific to the current bindings and platform
|
||||
fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
for entries in entry_sections {
|
||||
for entry in entries {
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
|
||||
// Recursively call this function on the menu's children
|
||||
apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1065,29 +1085,39 @@ impl DiffUpdate {
|
||||
// Apply shortcut conversions to all widgets that have menu lists
|
||||
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
|
||||
Widget::DropdownInput(dropdown_input) => {
|
||||
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping, environment);
|
||||
dropdown_input.entries_hash = hash_menu_list_entry_sections(&dropdown_input.entries);
|
||||
}
|
||||
Widget::TextButton(text_button) => {
|
||||
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping, environment);
|
||||
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
match self {
|
||||
Self::Layout(layout) => layout.0.iter_mut().flat_map(|layout_group| layout_group.iter_mut()).for_each(|widget_instance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
}),
|
||||
Self::LayoutGroup(layout_group) => layout_group.iter_mut().for_each(|widget_instance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
}),
|
||||
Self::Widget(widget_instance) => {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
let convert = |widget_instance: &mut WidgetInstance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
};
|
||||
|
||||
fn convert_layout_group(layout_group: &mut LayoutGroup, convert: &impl Fn(&mut WidgetInstance)) {
|
||||
match layout_group {
|
||||
LayoutGroup::Column(WidgetColumn { widgets }) | LayoutGroup::Row(WidgetRow { widgets }) => widgets.iter_mut().for_each(|widget_instance| convert_widget(widget_instance, convert)),
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => rows.iter_mut().flatten().flatten().for_each(|widget_instance| convert_widget(widget_instance, convert)),
|
||||
LayoutGroup::NodeSection(NodeSection { layout, .. }) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert)),
|
||||
}
|
||||
}
|
||||
fn convert_widget(widget_instance: &mut WidgetInstance, convert: &impl Fn(&mut WidgetInstance)) {
|
||||
convert(widget_instance);
|
||||
if let Widget::PopoverButton(popover_button) = &mut *widget_instance.widget {
|
||||
popover_button.popover_layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert));
|
||||
}
|
||||
}
|
||||
|
||||
match self {
|
||||
Self::Layout(layout) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, &convert)),
|
||||
Self::LayoutGroup(layout_group) => convert_layout_group(layout_group, &convert),
|
||||
Self::Widget(widget_instance) => convert_widget(widget_instance, &convert),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
@@ -47,6 +47,7 @@ pub enum Message {
|
||||
Viewport(ViewportMessage),
|
||||
|
||||
// Messages
|
||||
Wake,
|
||||
Batched {
|
||||
messages: Box<[Message]>,
|
||||
},
|
||||
|
||||
@@ -20,10 +20,6 @@ pub enum DataPanelMessage {
|
||||
TruncateElementPath {
|
||||
len: usize,
|
||||
},
|
||||
|
||||
ViewVectorTableTab {
|
||||
tab: VectorTableTab,
|
||||
},
|
||||
}
|
||||
|
||||
/// One hop in the breadcrumb path through nested data the Data panel is displaying.
|
||||
@@ -33,11 +29,3 @@ pub enum PathStep {
|
||||
Element(usize),
|
||||
Attribute { row: usize, key: String },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum VectorTableTab {
|
||||
#[default]
|
||||
Points,
|
||||
Segments,
|
||||
Handles,
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use super::VectorTableTab;
|
||||
use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup, LayoutTarget};
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessage, PathStep};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -25,14 +24,14 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
|
||||
SpiralType,
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -51,7 +50,6 @@ pub struct DataPanelMessageHandler {
|
||||
introspected_node_path: Vec<NodeId>,
|
||||
introspected_data: Option<Arc<dyn Any + Send + Sync>>,
|
||||
element_path: Vec<PathStep>,
|
||||
active_vector_table_tab: VectorTableTab,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -67,7 +65,6 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
self.introspected_node_path.clear();
|
||||
self.introspected_data = None;
|
||||
self.element_path.clear();
|
||||
self.active_vector_table_tab = VectorTableTab::default();
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
DataPanelMessage::Refresh => {
|
||||
@@ -85,11 +82,6 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
self.element_path.truncate(len);
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
|
||||
DataPanelMessage::ViewVectorTableTab { tab } => {
|
||||
self.active_vector_table_tab = tab;
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +106,6 @@ impl DataPanelMessageHandler {
|
||||
node_lookup_network_path: Vec::new(),
|
||||
gradient_settings: GradientSettings::default(),
|
||||
breadcrumbs: Vec::new(),
|
||||
vector_table_tab: self.active_vector_table_tab,
|
||||
};
|
||||
|
||||
// Main data visualization
|
||||
@@ -172,7 +163,6 @@ struct LayoutData<'a> {
|
||||
/// rather than in the stop list itself. The enclosing `Item`/`List` sets it to the owning row's attributes.
|
||||
gradient_settings: GradientSettings,
|
||||
breadcrumbs: Vec<String>,
|
||||
vector_table_tab: VectorTableTab,
|
||||
}
|
||||
|
||||
macro_rules! generate_layout_downcast {
|
||||
@@ -655,70 +645,42 @@ impl TableItemLayout for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// The pool is a plain point list with its IDs riding its attributes, so the generic list layout shows it as-is
|
||||
impl TableItemLayout for Vector {
|
||||
fn type_name() -> &'static str {
|
||||
"Vector"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!(
|
||||
"Vector ({} point{}, {} segment{})",
|
||||
self.point_domain.ids().len(),
|
||||
if self.point_domain.ids().len() == 1 { "" } else { "s" },
|
||||
self.segment_domain.ids().len(),
|
||||
if self.segment_domain.ids().len() == 1 { "" } else { "s" }
|
||||
)
|
||||
self.0.identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles]
|
||||
.into_iter()
|
||||
.map(|tab| {
|
||||
RadioEntryData::new(format!("{tab:?}"))
|
||||
.label(format!("{tab:?}"))
|
||||
.on_update(move |_| DataPanelMessage::ViewVectorTableTab { tab }.into())
|
||||
})
|
||||
.collect();
|
||||
let table_tabs = vec![RadioInput::new(table_tab_entries).selected_index(Some(data.vector_table_tab as u32)).widget_instance()];
|
||||
self.0.value_page(data)
|
||||
}
|
||||
}
|
||||
|
||||
let mut table_rows = Vec::new();
|
||||
match data.vector_table_tab {
|
||||
VectorTableTab::Handles => {
|
||||
table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"]));
|
||||
table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| {
|
||||
vec![
|
||||
TextLabel::new(format!("{index}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{a}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{b}")).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Points => {
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format_dvec2(position)).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Segments => {
|
||||
table_rows.push(column_headings(&["", "start_point", "end_point", "handles"]));
|
||||
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
|
||||
let handles = match handles {
|
||||
BezierHandles::Linear => "Linear".to_string(),
|
||||
BezierHandles::Quadratic { handle } => format!("Quadratic — {}", format_dvec2(handle)),
|
||||
BezierHandles::Cubic { handle_start, handle_end } => format!("Cubic — start: {}, end: {}", format_dvec2(handle_start), format_dvec2(handle_end)),
|
||||
};
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Point {start}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Point {end}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(handles).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
// A path is its list of point references, with segment IDs and smooth flags riding its attributes
|
||||
impl TableItemLayout for Path {
|
||||
fn type_name() -> &'static str {
|
||||
"Path"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.0.identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.value_page(data)
|
||||
}
|
||||
}
|
||||
|
||||
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
|
||||
// Only the click target attribute holds a bezpath, so it's named for what it does
|
||||
impl TableItemLayout for BezPath {
|
||||
fn type_name() -> &'static str {
|
||||
"Click Target"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
Self::type_name().to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1082,7 +1044,7 @@ pub fn node_reference_button(
|
||||
network_path: &[NodeId],
|
||||
selection_network_path: &[NodeId],
|
||||
select: impl Fn() -> Message + Send + Sync + 'static,
|
||||
) -> WidgetInstance {
|
||||
) -> TextButton {
|
||||
let is_layer = network_interface.is_layer(&node_id, network_path);
|
||||
let icon = network_interface.node_icon(&node_id, network_path);
|
||||
let name = network_interface.display_name(&node_id, network_path);
|
||||
@@ -1101,7 +1063,6 @@ pub fn node_reference_button(
|
||||
(true, false, _) => "",
|
||||
})
|
||||
.on_update(move |_| select())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl TableItemLayout for NodeId {
|
||||
@@ -1135,7 +1096,7 @@ impl TableItemLayout for NodeId {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into(),
|
||||
]),
|
||||
};
|
||||
vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select)]
|
||||
vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))]
|
||||
@@ -1151,6 +1112,7 @@ macro_rules! known_item_types {
|
||||
List<Artboard>,
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Path>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
@@ -1170,6 +1132,8 @@ macro_rules! known_item_types {
|
||||
bool,
|
||||
String,
|
||||
Vector,
|
||||
Path,
|
||||
BezPath,
|
||||
Raster<CPU>,
|
||||
Raster<GPU>,
|
||||
Graphic,
|
||||
@@ -1230,6 +1194,15 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
|
||||
if let Some(value) = any.downcast_ref::<BlendMode>() {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<PointId>() {
|
||||
return Some(if *value == PointId::UNNAMED { String::new() } else { value.inner().to_string() });
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<SegmentId>() {
|
||||
return Some(if *value == SegmentId::ZERO { String::new() } else { value.inner().to_string() });
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<CurveType>() {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
@@ -266,8 +266,8 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
|
||||
if expected.skip_deduplication != actual.skip_deduplication {
|
||||
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
|
||||
}
|
||||
if expected.context_features != actual.context_features {
|
||||
let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features);
|
||||
if expected.context_dependencies != actual.context_dependencies {
|
||||
let _ = writeln!(out, " context_dependencies: expected={:?} actual={:?}", expected.context_dependencies, actual.context_dependencies);
|
||||
}
|
||||
if expected.original_location != actual.original_location {
|
||||
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
@@ -55,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,
|
||||
@@ -199,6 +212,11 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
/// Renames a layer in the network the node graph is showing, which may be a subgraph.
|
||||
SetLayerNameInGraph {
|
||||
node_id: NodeId,
|
||||
name: String,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
@@ -225,6 +243,9 @@ pub enum DocumentMessage {
|
||||
closure: Option<for<'a> fn(&'a mut SnappingState) -> &'a mut bool>,
|
||||
snapping_state: bool,
|
||||
},
|
||||
SetSnappingAngleStep {
|
||||
degrees: f64,
|
||||
},
|
||||
SetToNodeOrLayer {
|
||||
node_id: NodeId,
|
||||
is_layer: bool,
|
||||
@@ -260,6 +281,10 @@ pub enum DocumentMessage {
|
||||
ToggleLayerChainExpanded {
|
||||
layer_id: NodeId,
|
||||
},
|
||||
/// Hides or shows a node in the network holding the selection, which may be a subgraph.
|
||||
ToggleNodeVisibility {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
ToggleGridVisibility,
|
||||
@@ -283,11 +308,12 @@ pub enum DocumentMessage {
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
UpdateVectorData {
|
||||
vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
},
|
||||
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
|
||||
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||
// `UpdateVectorData` and `UpdateAppearanceAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point.
|
||||
#[serde(skip)]
|
||||
UpdateVectorData {
|
||||
vector_data: HashMap<NodeId, Arc<Item<Vector>>>,
|
||||
},
|
||||
#[serde(skip)]
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -147,8 +147,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_bezpath(bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
let (vector, paths) = Vector::from_bezpath(&bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector, &paths));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
.expect("Path node does not exist")
|
||||
@@ -247,8 +247,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
/// Clear the whole-expanse paint one tool left on a layer so the other can start its own chain there.
|
||||
/// Severing at the attachment detaches the layer from whatever the walk stopped at, which is the only part a node
|
||||
/// the rest of the graph also draws from is subjected to, since such a node is never among those deleted.
|
||||
/// Severing at the attachment detaches the layer from the old chain, which is all that a node the rest of
|
||||
/// the graph also draws from is subjected to, since such a node is never among those deleted.
|
||||
fn clear_paint_chain(&mut self, paint_chain: &ReplaceablePaintChain) {
|
||||
self.network_interface.disconnect_input(&paint_chain.attachment_input, &[]);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
@@ -16,6 +16,7 @@ use graph_craft::document::NodeId;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct NavigationMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub breadcrumb_network_path: &'a [NodeId],
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
@@ -39,6 +40,7 @@ pub struct NavigationMessageHandler {
|
||||
impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for NavigationMessageHandler {
|
||||
fn process_message(&mut self, message: NavigationMessage, responses: &mut VecDeque<Message>, context: NavigationMessageContext) {
|
||||
let NavigationMessageContext {
|
||||
environment,
|
||||
network_interface,
|
||||
breadcrumb_network_path,
|
||||
ipp,
|
||||
@@ -189,7 +191,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x, .. } => {
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling
|
||||
let delta = if use_y_as_x && !Editor::environment().is_mac() {
|
||||
let delta = if use_y_as_x && !environment.is_mac() {
|
||||
(ipp.mouse.scroll_delta.y, 0.).into()
|
||||
} else {
|
||||
ipp.mouse.scroll_delta.as_dvec2()
|
||||
@@ -529,6 +531,11 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
|
||||
impl NavigationMessageHandler {
|
||||
/// Whether a pan, tilt, or zoom drag is in progress.
|
||||
pub fn is_navigating(&self) -> bool {
|
||||
self.navigation_operation != NavigationOperation::None
|
||||
}
|
||||
|
||||
pub fn snapped_tilt(&self, tilt: f64) -> f64 {
|
||||
let increment_radians: f64 = VIEWPORT_ROTATE_SNAP_INTERVAL.to_radians();
|
||||
if matches!(self.navigation_operation, NavigationOperation::Tilt { snap: true, .. }) {
|
||||
|
||||
@@ -1001,14 +1001,13 @@ fn static_input_inspector() -> InputInspector {
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let node_metadata = registry::NODE_METADATA.lock().unwrap();
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| node_metadata.get(proto_node_identifier))
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
@@ -1722,6 +1721,19 @@ mod test {
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
}
|
||||
|
||||
// Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again
|
||||
#[tokio::test]
|
||||
async fn optional_f64_inspector_row_builds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let node_id = editor
|
||||
.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::qr_code::IDENTIFIER))
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
|
||||
editor.handle_message(InspectorMessage::Refresh).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
-2
@@ -42,7 +42,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
fields,
|
||||
description,
|
||||
inspector,
|
||||
context_features,
|
||||
output_fields,
|
||||
..
|
||||
} = metadata;
|
||||
@@ -90,7 +89,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
context_features: ContextDependencies::from(context_features.as_slice()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::utility_types::Direction;
|
||||
use super::utility_types::{Direction, NodeEvaluationError};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -227,6 +227,10 @@ pub enum NodeGraphMessage {
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
/// Moves the selected nodes one grid cell with the arrow keys, as an undo step of its own.
|
||||
NudgeSelectedNodes {
|
||||
direction: Direction,
|
||||
},
|
||||
ShiftSelectedNodes {
|
||||
direction: Direction,
|
||||
rubber_band: bool,
|
||||
@@ -301,6 +305,9 @@ pub enum NodeGraphMessage {
|
||||
#[serde(skip)]
|
||||
node_graph_errors: GraphErrors,
|
||||
},
|
||||
UpdateEvaluationErrors {
|
||||
errors: Vec<NodeEvaluationError>,
|
||||
},
|
||||
UpdateActionButtons,
|
||||
UpdateGraphBarRight,
|
||||
UpdateInSelectedNetwork,
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Modify
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{
|
||||
DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
@@ -118,6 +118,7 @@ pub struct NodeGraphMessageHandler {
|
||||
frontend_nodes: Vec<NodeId>,
|
||||
/// Used to keep track of what wires are sent to the front end so the old ones can be removed
|
||||
frontend_wires: HashSet<(NodeId, usize)>,
|
||||
evaluation_errors: Vec<NodeEvaluationError>,
|
||||
}
|
||||
|
||||
/// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network.
|
||||
@@ -1972,6 +1973,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
nodes.push(*node_id);
|
||||
}
|
||||
}
|
||||
if self.evaluation_errors.iter().any(|error| error.node_path.contains(node_id)) {
|
||||
nodes.push(*node_id);
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(FrontendMessage::UpdateVisibleNodes { nodes });
|
||||
@@ -1986,8 +1990,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes });
|
||||
|
||||
let error = self.node_graph_error(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostic { error });
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
@@ -2038,6 +2042,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::SetInput { input_connector, input } => {
|
||||
network_interface.set_input(&input_connector, input, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::NudgeSelectedNodes { direction } => {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band: false });
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band } => {
|
||||
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
|
||||
|
||||
@@ -2447,6 +2456,16 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::UpdateEvaluationErrors { errors } => {
|
||||
if self.evaluation_errors != errors {
|
||||
self.evaluation_errors = errors;
|
||||
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
responses.add(NodeGraphMessage::UpdateVisibleNodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::UpdateActionButtons => {
|
||||
if selection_network_path == breadcrumb_network_path {
|
||||
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
|
||||
@@ -2701,7 +2720,7 @@ impl NodeGraphMessageHandler {
|
||||
ToggleSelectedAsLayersOrNodes,
|
||||
ToggleSelectedLocked,
|
||||
ToggleSelectedVisibility,
|
||||
ShiftSelectedNodes,
|
||||
NudgeSelectedNodes,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -3057,7 +3076,73 @@ impl NodeGraphMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
vec![layer_section]
|
||||
// The layers this one's output feeds, which a stack used in several places can be many of, and the graph's output none of.
|
||||
// Followed through any nodes between, each layer takes it either from its bottom (as the sibling above in its stack) or into its content (as its parent).
|
||||
let network_path = context.selection_network_path;
|
||||
let outward_connectors = |node_id: NodeId| {
|
||||
context
|
||||
.network_interface
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).cloned())
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (mut siblings, mut parents) = (Vec::new(), Vec::new());
|
||||
let mut pending_connectors = outward_connectors(layer);
|
||||
let mut visited_nodes = HashSet::new();
|
||||
while let Some(connector) = pending_connectors.pop() {
|
||||
let Some(node_id) = connector.node_id() else { continue };
|
||||
|
||||
if context.network_interface.is_layer(&node_id, network_path) {
|
||||
let receivers = if connector.input_index() == 0 { &mut siblings } else { &mut parents };
|
||||
receivers.push(node_id);
|
||||
continue;
|
||||
}
|
||||
|
||||
// A node passes it on only when taking it as its primary input, rather than as a parameter
|
||||
if connector.input_index() == 0 && visited_nodes.insert(node_id) {
|
||||
pending_connectors.extend(outward_connectors(node_id));
|
||||
}
|
||||
}
|
||||
|
||||
// Sorted for a stable button order, since outward wires are unordered
|
||||
siblings.sort_unstable();
|
||||
siblings.dedup();
|
||||
parents.sort_unstable();
|
||||
parents.dedup();
|
||||
|
||||
// The layer feeding this one from below in its stack, unless this is the bottom
|
||||
let layer_below = node_inspector::input_chain(layer, 0, context.network_interface, network_path).and_then(|(_, stack_layer)| stack_layer);
|
||||
|
||||
// Each is only referred to by a button, wired to the layer's section. Parents sit just above, the wire turning into their content,
|
||||
// and siblings above them, the wire continuing up past that turn into their bottom.
|
||||
let mut sections = Vec::new();
|
||||
|
||||
if let Some(siblings_section) = node_inspector::layer_references_section(&siblings, "Select Sibling Layer", context) {
|
||||
sections.push(siblings_section);
|
||||
}
|
||||
if let Some(mut parents_section) = node_inspector::layer_references_section(&parents, "Select Parent Layer", context) {
|
||||
if let LayoutGroup::NodeSection(section) = &mut parents_section {
|
||||
section.content_wire = Some(node_inspector::output_section_wire(layer, context));
|
||||
section.content_wire_continues = !siblings.is_empty();
|
||||
}
|
||||
sections.push(parents_section);
|
||||
}
|
||||
if !sections.is_empty()
|
||||
&& let LayoutGroup::NodeSection(section) = &mut layer_section
|
||||
{
|
||||
section.output_wire = Some(node_inspector::output_section_wire(layer, context));
|
||||
}
|
||||
sections.push(layer_section);
|
||||
if let Some(layer_below) = layer_below
|
||||
&& let Some(mut below_section) = node_inspector::layer_references_section(&[layer_below], "Select Sibling Layer", context)
|
||||
{
|
||||
if let LayoutGroup::NodeSection(section) = &mut below_section {
|
||||
section.output_wire = Some(node_inspector::output_section_wire(layer_below, context));
|
||||
}
|
||||
sections.push(below_section);
|
||||
}
|
||||
|
||||
sections
|
||||
}
|
||||
// If multiple layers and/or nodes are selected, show nothing
|
||||
_ => Vec::new(),
|
||||
@@ -3186,28 +3271,47 @@ impl NodeGraphMessageHandler {
|
||||
Some(subgraph_names)
|
||||
}
|
||||
|
||||
fn node_graph_error(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Option<NodeGraphErrorDiagnostic> {
|
||||
let graph_error = network_interface
|
||||
fn node_graph_errors(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<NodeGraphErrorDiagnostic> {
|
||||
let depth = breadcrumb_network_path.len();
|
||||
let inside = |path: &[NodeId]| path.starts_with(breadcrumb_network_path) && path.len() > depth;
|
||||
let graph_errors: Vec<_> = network_interface
|
||||
.resolved_types
|
||||
.node_graph_errors
|
||||
.iter()
|
||||
.find(|error| error.node_path.starts_with(breadcrumb_network_path) && error.node_path.len() > breadcrumb_network_path.len())?;
|
||||
let error = if graph_error.node_path.len() == breadcrumb_network_path.len() + 1 {
|
||||
format!("{:?}", graph_error.error)
|
||||
} else {
|
||||
"Node graph type error within this node".to_string()
|
||||
.filter(|error| inside(&error.node_path))
|
||||
.map(|error| match error.node_path.len() == depth + 1 {
|
||||
true => (error.node_path[depth], format!("{:?}", error.error)),
|
||||
false => (error.node_path[depth], "Node graph type error within this node".to_string()),
|
||||
})
|
||||
.collect();
|
||||
// Evaluation errors come from the last graph that compiled, so a type error hides them
|
||||
let errors = match graph_errors.is_empty() {
|
||||
true => self
|
||||
.evaluation_errors
|
||||
.iter()
|
||||
.filter(|error| inside(&error.node_path))
|
||||
.map(|error| match error.node_path.len() == depth + 1 {
|
||||
true => (error.node_path[depth], error.message.clone()),
|
||||
false => (error.node_path[depth], "Node graph error within this node".to_string()),
|
||||
})
|
||||
.collect(),
|
||||
false => graph_errors,
|
||||
};
|
||||
let error_node = graph_error.node_path[breadcrumb_network_path.len()];
|
||||
|
||||
let mut position = network_interface.position(&error_node, breadcrumb_network_path)?;
|
||||
// Convert to graph space
|
||||
position *= 24;
|
||||
if network_interface.is_layer(&error_node, breadcrumb_network_path) {
|
||||
position += IVec2::new(12, -12)
|
||||
}
|
||||
let position = position.into();
|
||||
|
||||
Some(NodeGraphErrorDiagnostic { position, error })
|
||||
let mut shown = HashSet::new();
|
||||
errors
|
||||
.into_iter()
|
||||
.filter(|(node, _)| shown.insert(*node))
|
||||
.filter_map(|(node, error)| {
|
||||
let mut position = network_interface.position(&node, breadcrumb_network_path)?;
|
||||
// Convert to graph space
|
||||
position *= 24;
|
||||
if network_interface.is_layer(&node, breadcrumb_network_path) {
|
||||
position += IVec2::new(12, -12)
|
||||
}
|
||||
Some(NodeGraphErrorDiagnostic { position: position.into(), error })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn update_layer_panel(
|
||||
@@ -3406,6 +3510,7 @@ impl Default for NodeGraphMessageHandler {
|
||||
end_index: None,
|
||||
frontend_nodes: Vec::new(),
|
||||
frontend_wires: HashSet::new(),
|
||||
evaluation_errors: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,7 +448,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return inspector_row_from_type(node_id, index, out, options, context),
|
||||
Type::Future(out) => return inspector_row_from_type(node_id, index, out, options, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -3087,15 +3086,6 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn node_no_inspector_content(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
let text = if context.network_interface.is_layer(&node_id, context.selection_network_path) {
|
||||
"Layer has no parameters"
|
||||
} else {
|
||||
"Node has no parameters"
|
||||
};
|
||||
string_inspector(text)
|
||||
}
|
||||
|
||||
pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> LayoutGroup {
|
||||
let mut layout = Vec::new();
|
||||
|
||||
@@ -3184,10 +3174,6 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
}
|
||||
|
||||
if layout.is_empty() {
|
||||
layout = node_no_inspector_content(node_id, context);
|
||||
}
|
||||
|
||||
let display_name = context
|
||||
.network_interface
|
||||
.node_metadata(&node_id, context.selection_network_path)
|
||||
@@ -3238,16 +3224,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
// That layer is only referred to, as in the Data panel, rather than shown with its own parameters and chain
|
||||
if let Some(layer) = stack_layer {
|
||||
let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into()
|
||||
});
|
||||
let name = context.network_interface.display_name(&layer, network_path);
|
||||
let visible = context.network_interface.is_visible(&layer, network_path);
|
||||
|
||||
let mut reference_section = LayoutGroup::section(name, None, "", visible, false, true, layer.0, Layout(vec![LayoutGroup::row(vec![button])]));
|
||||
let feeds_content = input_index == LAYER_SECONDARY_INPUT_INDEX && context.network_interface.is_layer(&node_id, network_path);
|
||||
let tooltip_label = if feeds_content { "Select Child Layer" } else { "Select Layer" };
|
||||
if let Some(layer) = stack_layer
|
||||
&& let Some(mut reference_section) = layer_references_section(&[layer], tooltip_label, context)
|
||||
{
|
||||
if let LayoutGroup::NodeSection(section) = &mut reference_section {
|
||||
section.node_reference = true;
|
||||
section.output_wire = Some(output_section_wire(layer, context));
|
||||
}
|
||||
|
||||
@@ -3262,8 +3244,35 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
section
|
||||
}
|
||||
|
||||
/// A section only referring to layers, as the Data panel does, with a row of buttons that each select one rather than showing its parameters and chain.
|
||||
/// Their tooltip label names how the layers relate to the section they're shown beside.
|
||||
pub(crate) fn layer_references_section(layers: &[NodeId], tooltip_label: &str, context: &NodeInspectorContext) -> Option<LayoutGroup> {
|
||||
let network_path = context.selection_network_path;
|
||||
let &first_layer = layers.first()?;
|
||||
|
||||
let mut buttons = Vec::with_capacity(layers.len() * 2);
|
||||
for &layer in layers {
|
||||
if !buttons.is_empty() {
|
||||
buttons.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
}
|
||||
let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into()
|
||||
});
|
||||
buttons.push(button.tooltip_label(tooltip_label).widget_instance());
|
||||
}
|
||||
|
||||
let name = context.network_interface.display_name(&first_layer, network_path);
|
||||
let visible = context.network_interface.is_visible(&first_layer, network_path);
|
||||
|
||||
let mut section = LayoutGroup::section(name, None, "", visible, false, true, first_layer.0, Layout(vec![LayoutGroup::row(buttons)]));
|
||||
if let LayoutGroup::NodeSection(node_section) = &mut section {
|
||||
node_section.node_reference = true;
|
||||
}
|
||||
Some(section)
|
||||
}
|
||||
|
||||
/// The wire drawn up from a node's section in a chain to the section above, which its output feeds.
|
||||
fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire {
|
||||
pub(crate) fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire {
|
||||
let output_type = context.network_interface.output_type(&OutputConnector::node(node_id, 0), context.selection_network_path);
|
||||
|
||||
SectionWire {
|
||||
@@ -3867,8 +3876,8 @@ mod tests {
|
||||
#[test]
|
||||
fn wire_element_reads_every_spelling_down_to_the_element() {
|
||||
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
|
||||
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
|
||||
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
|
||||
let row = Type::Fn(Box::new(concrete!(())), Box::new(item!(f64)));
|
||||
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(list!(f64)));
|
||||
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
|
||||
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
|
||||
}
|
||||
|
||||
@@ -193,6 +193,12 @@ pub struct NodeGraphErrorDiagnostic {
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeEvaluationError {
|
||||
pub node_path: Vec<NodeId>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendClickTargets {
|
||||
@@ -218,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>,
|
||||
}
|
||||
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user