Compare commits

...
Author SHA1 Message Date
Dennis Kobert 24cbc5671e The metadata file is an append-only log of stamped facts folded on read, so a name, a label or a tag appends one line; the History panel names and tags interactions, with given labels shown in bold and tag chips 2026-09-29 19:58:55 +00:00
Dennis Kobert 9c1019796c Every mounted document retires on the frame tick, in a session or not, so solo steps enter history as they close; the History panel shows each closed transaction waiting for the retirer as a pending row of its own 2026-09-29 19:43:17 +00:00
Dennis Kobert 2dd91c0fcf History panel actions: go back to here, remove this step, bring back and following a branch from its stub; a shared head move to an ancestor as a HeadMove without copies, requested from the host by guests, and the retired undo generalised to dropping any step 2026-09-29 17:37:31 +00:00
Dennis Kobert 860ec5c465 History panel, read-only: the active document's history as interactions along the head's line, expandable to their deltas, with authors from the record, retirement times, derived labels, the head and undone rows, branch counts and the room's work in progress, refreshed each frame it moved; docked as a tab beside Layers from the Window menu 2026-09-29 15:50:58 +00:00
Dennis Kobert d90eacdee6 History phase one: retirements record their wall time as a delta attribute carried onto copies, and a per-document metadata record of users beside the history is persisted, carried in the sync and gossiped on change, so the editor names authors from the record before presence and colours by user id 2026-09-29 14:37:00 +00:00
Dennis Kobert f42a46c513 The cursor icon other peers see names the active shape for the Line, Rectangle and Ellipse tools instead of the Shape tool's polygon 2026-09-28 16:49:58 +00:00
Dennis Kobert fca4d4f9a8 Remote cursors show the tool their peer holds: the cursor packet carries the active tool's icon name, and both document and graph cursors are rendered by one Svelte component with the icon in the label, replacing the canvas overlay for document cursors so a remote move no longer redraws every overlay 2026-09-28 15:48:45 +00:00
Dennis Kobert 2c2926fd9c The native wasm shim proxies PanelType like the other editor types, so the desktop build compiles the focus_panel command 2026-09-28 13:09:53 +00:00
Dennis Kobert 2a2a92e627 Session tokens parse out of share links everywhere, so the CLI takes a pasted link; the panel gets a copy button for the bare token, the desktop app copies the session link natively, and the tab circle uses the editor's tooltip 2026-09-28 12:43:49 +00:00
Dennis Kobert f09a3855a8 The live viewer logs the resources it waits on before compiling and each one it receives, so a resource no peer holds is visible instead of a dark window 2026-09-26 11:41:03 +00:00
Dennis Kobert a476a156b4 The live viewer presents its background before the document is compiled, so the window is mapped on Wayland while it still waits for the sync, and logs when it synced and compiled 2026-09-26 11:25:42 +00:00
Dennis Kobert 3686641f5f The pointer position is recorded over the node graph too: the frontend sends a hover-only message that reaches no tool, so the cursor other peers see follows the mouse over the graph rather than jumping on clicks 2026-09-26 10:24:58 +00:00
Dennis Kobert 2d0c6fc6bc A guest joining by link takes the host's document id on any sync, not only a full one, so its own link names the shared room; the document name is a registry attribute staged on share, fork and rename and adopted by guests; a demo artwork opens with a fresh document id so everyone opening it does not share one room; the join field is a labelled row 2026-09-26 10:01:33 +00:00
Dennis Kobert 64b07445b7 Cursors carry the space they are in, the document or a network of the node graph by its path, so a peer with the graph open sends graph coordinates; receivers draw document cursors on the canvas overlay only while their graph is closed and graph cursors for the network they show through the Svelte graph as viewport points; the tab circle sits between the name and the close button 2026-09-26 09:50:20 +00:00
Dennis Kobert b5fa35aeff The user id is stored as a decimal string in the preferences, since a 64-bit number did not survive the browser's JSON store and the preferences failed to load, leaving every peer anonymous under user id 0 and dropping the name; the Session panel's not-shared state takes a pasted session link or token to join 2026-09-26 09:33:30 +00:00
Dennis Kobert 8b7bc2cd64 Session panel polish: no host or guest wording, the actions sit right under the state line in every state, anonymous peers are named Anonymous <animal> from the user id in italics, a Show cursors preference switch, the tab circle smaller and muted and red when the transport is lost, and a lost transport reconnects every three seconds until the room is back or sharing stops 2026-09-26 09:19:35 +00:00
Dennis Kobert 1b3a446d8a Session panel follow-ups: the File menu loses its share entry, a restored or newly added Session panel docks as a tab beside Properties instead of above it, a workspace saved before the panel existed gets it on load, and the panel refreshes once the working copy has mounted 2026-09-26 08:50:10 +00:00
Dennis Kobert c8be835772 Fork a session: leave the room, give the manifest a fresh document id and host the document as a new session with its own link; a transport drop keeps the document shared so the Session panel shows it disconnected and offers to reconnect, and the end of a connection the document already left or forked away from is ignored by generation 2026-09-26 08:33:26 +00:00
Dennis Kobert f820ed1ade The stored user id reaches the CRDT: the session carries a UserId next to its PeerId, the working copy persists it and follows the preferences on open, RegisterPeer records it and registration is a last-writer-wins write rather than a claim that errors on conflict, and undo of a retired step in a session names the person's latest step across the peer ids they accumulate 2026-09-26 08:20:45 +00:00
Dennis Kobert c9979f148a Presence: a profile packet carries the display name after each hello and on rename, a cursor packet carries the pointer in document space once a frame, both outside the causal broadcast; the name and a user id drawn once live in the preferences and the Session panel edits the name; other peers' cursors draw as overlays with a name label coloured by peer id 2026-09-26 07:59:04 +00:00
Dennis Kobert 9a7bf7a579 Session panel: sharing moves from a dialog to a panel docked next to Properties that shows the session state, the join link, the peers and the share and disconnect actions; a shared document's tab carries a circle that focuses the panel 2026-09-26 07:34:50 +00:00
Dennis Kobert db144ca217 Host handover: when the host leaves the lowest synced guest takes the role over, an unsynced guest steps aside and syncs from the new host, two hosts resolve by id, a returning host is a guest, the host merges a divergent line with a merge delta the room follows, and coarsening orders writes by stamp 2026-09-25 15:20:26 +00:00
Dennis Kobert 1a0b0741c4 Decode declarations the byte store already holds before applying remote changes: a second join in one browser requested nothing from the host and its rebuild found no declarations 2026-09-25 13:05:30 +00:00
Dennis Kobert ccdbc3ff80 Poll a room as packets arrive, not only per frame: the inbox wakes a future, so a host in a hidden tab answers a join at once instead of once a second 2026-09-25 12:49:05 +00:00
Dennis Kobert 48fbe6d2df One contextual session entry: share connects to the document's room and takes the host role only if none greets, disconnect leaves, and a shared document reconnects when reopened 2026-09-25 12:15:06 +00:00
Dennis Kobert cf75b0e99a Log the join handshake steps at info level to time where a guest waits 2026-09-25 11:57:34 +00:00
Dennis Kobert 4080405ef4 Derive the session token from the document id and let a copy rejoin its room with its own history, adopting the host's document id on a full sync 2026-09-25 11:55:50 +00:00
Dennis Kobert fe2f2c00a2 Fit the viewport to the document once a joining guest's interface follows the host's state and the graph has run 2026-09-25 11:41:14 +00:00
Dennis Kobert 435f33547a Coarsen a transaction at retirement to the newest write per field, keeping structural ops and the wires that stand for a referenced node 2026-09-25 11:22:20 +00:00
Dennis Kobert d59abb08e0 Keep the resource bytes a retracted step names alive across garbage collection, so its redo can still be served to peers 2026-09-25 11:15:43 +00:00
Dennis Kobert 4b4be2fffa Undo a retired step in a session by dropping it out of the shared line and moving every peer's head, with guests following the host's line instead of merging 2026-09-25 10:57:49 +00:00
Dennis Kobert 4d00dbae89 Follow the registry on the entities a hot undo or redo named instead of installing the legacy snapshot, send only the head's ancestry to peers, and keep a paused gesture in one transaction 2026-09-25 10:22:24 +00:00
Dennis Kobert e490c4fcc2 Take a hot transaction back on undo so it never becomes history, with placeholders replacing the last deferred write in the registry 2026-09-25 10:00:13 +00:00
Dennis Kobert d2bfda8178 Retire closed transactions per author on a policy instead of everything at the host's gesture, keeping open transactions hot 2026-09-25 08:55:07 +00:00
Dennis Kobert f18becb21b Keep removed resource sources as stamped tombstones under a chain floor, so source ops commute 2026-09-25 08:55:07 +00:00
Dennis Kobert 92cd31b607 Keep an attribute stamped at a map's floor when another map folds in, so a removal's snapshot no longer wipes what the addition wrote 2026-09-24 22:41:07 +00:00
Dennis Kobert b9ce700995 Make every registry op a timestamped write, presence and attribute deletion included, so merges apply once and the refold goes 2026-09-24 22:28:14 +00:00
Dennis Kobert 2893e6086b Retire a prefix of the hot log in the order it was applied 2026-09-24 21:23:15 +00:00
Dennis Kobert 09581fb86f Append retired deltas to the history file on a fast-forward merge instead of rewriting it 2026-09-24 21:17:23 +00:00
Dennis Kobert 75d0bee48d Stage recorded edits every frame in a session so each movement reaches peers 2026-09-24 21:17:23 +00:00
Dennis Kobert b12b692a2d Index history for tips, timestamps and resource hashes, fast-forward chained merges, and fold snapshots in place 2026-09-24 20:07:18 +00:00
Dennis Kobert 710487160c Broadcast the hot ops a recorded batch stages 2026-09-24 18:03:17 +00:00
Dennis Kobert e784ebfeb7 Reconcile remote changes into the interface instead of rebuilding it 2026-09-24 17:32:12 +00:00
Dennis Kobert 3c7bc125ea Record what remote ops touched on the Gdd sync target 2026-09-24 17:32:12 +00:00
Dennis Kobert 1c90c3732c Project single registry entities to the runtime and count refolds that change the working registry 2026-09-24 17:32:12 +00:00
Dennis Kobert 1ea5bf106a Keep a slot's ui attributes across an implementation swap 2026-09-24 17:32:12 +00:00
Dennis Kobert 7bf3452232 Name the seed and peer when a history cannot be replayed 2026-09-24 16:36:57 +00:00
Dennis Kobert 88c0d3a160 Guard that a seed fixes the run, since hashed iteration order once decided edits 2026-09-24 16:36:57 +00:00
Dennis Kobert c04cba26ad Make the simulation deterministic and check both registry zones 2026-09-24 16:36:57 +00:00
Dennis Kobert d34a7edf82 Propagate the refold error out of the sync target 2026-09-24 16:36:57 +00:00
Dennis Kobert 58ab6f0d99 Pin the working-registry divergence the retired-state checks never looked at 2026-09-24 16:36:57 +00:00
Dennis Kobert 650cd76f88 Keep unretired hot ops across a full resync instead of dropping them 2026-09-24 16:36:57 +00:00
Dennis Kobert 06ad3fa181 Pin the witness path that keeps an author's run contiguous 2026-09-24 16:36:57 +00:00
Dennis Kobert b21af5eec0 Follow the retired-beyond rename in the simulation dump 2026-09-24 16:36:57 +00:00
Dennis Kobert 7197cc1bd4 Layer the peer-transport work onto the hardened graph-storage API 2026-09-24 16:36:57 +00:00
117 changed files with 14014 additions and 909 deletions

No files matched your search

Generated
+1706 -49
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -11,6 +11,8 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -98,6 +100,8 @@ 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" }
+1
View File
@@ -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
+1
View File
@@ -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
@@ -115,6 +115,13 @@ 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; the token
// alone is offered separately.
FrontendMessage::TriggerSessionLinkCopy { token } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
content: format!("https://editor.graphite.rs/?session={token}"),
});
}
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
+4 -1
View File
@@ -17,11 +17,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 }
+4
View File
@@ -47,4 +47,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 -1
View File
@@ -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.
@@ -146,15 +146,25 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
// An export is a copy taken out of the room; it does not reconnect on its own.
shared: false,
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
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();
+5
View File
@@ -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"
}
+120 -12
View File
@@ -17,10 +17,10 @@ use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
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;
@@ -28,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;
@@ -55,6 +57,8 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
/// The metadata file is a log of facts appended one per line and folded on read, so nothing is ever rewritten.
pub const METADATA_CODEC: Codec = Codec::JsonLines;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
@@ -68,8 +72,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
/// not carried over, so a clone is a read-only copy for asynchronous writes.
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
@@ -78,12 +82,77 @@ 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: its users and their names, later labels and tags. Kept beside
/// the history in its own file, merged last-writer-wins with every copy met, never folded and never undone.
pub(crate) metadata: HistoryMetadata,
/// The wall clock as the editor last reported it, in milliseconds since the Unix epoch, so retirements can
/// record when they happened. `None` for a copy nothing ticks, the CLI or a test.
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, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
/// store, which is what a standalone handle uses. The editor points this at its application-wide
/// cache, the single store resources are kept in there.
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 bring its runtime mirror into line
/// with the registry without rebuilding it.
#[cfg(feature = "network")]
pub(crate) remote_changes: network::RemoteChanges,
/// When each closed transaction was first seen here, by its marker, so the retirement policy can age
/// it. Not persisted: after a reopen everything pending is old enough.
pub(crate) transactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
/// When this peer last staged an op, so an open transaction the editor never closed can be closed
/// once it has gone 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 is meant to be in its room: set by sharing, cleared by disconnecting, and
/// persisted so a reopened document reconnects on its own.
pub(crate) shared: bool,
}
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
/// one rewrite of each file rather than 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(),
transactions_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
@@ -101,10 +170,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async 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).await
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version).await
}
}
@@ -135,23 +204,32 @@ 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;
let peer = session_state.peer_id;
// A copy written before identities were stored has no user; the peer stands for itself until one is set.
let user = match session_state.user_id {
UserId(0) => UserId(peer.0),
user => user,
};
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -170,19 +248,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(),
transactions_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 async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, 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, ..Default::default() };
let session_state = SessionState {
peer_id: peer,
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 {
@@ -192,6 +287,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(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
})
}
}
+372
View File
@@ -0,0 +1,372 @@
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
//! edits are.
use std::collections::HashSet;
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredHotOps, 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. The editor keeps a runtime
/// mirror of the registry and brings just the touched entities back into line, unless the registry was
/// rederived wholesale, when the touched set no longer bounds what changed.
#[derive(Clone, Debug, Default)]
pub struct RemoteChanges {
pub touched: Touched,
/// The working registry was replaced wholesale by a full sync, so the mirror has to be rebuilt from it.
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 the room every copy of this document shares, host or guest as the room calls for, and
/// remember that the document is shared so a reopen reconnects on its own.
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
}
/// For a connection still undecided after the grace period: take the host role if no host is there. 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 retires every closed transaction first, so what peers finished is in
/// history before the retirer goes away.
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: a reopen
/// reconnects on its own, and the Session panel offers to reconnect now.
pub fn disconnect(&mut self) {
let closed = self.session.closed_transactions();
if let Err(error) = self.retire_transactions(&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(&self, known: &[Rev]) -> Vec<Delta> {
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
}
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 that has not arrived here yet is handed back for a later retry, so only
// what actually applied reaches the hot frame log.
let mut deferred = Vec::new();
for hot_op in ops {
// Recorded whether or not it applies: a failed apply can still have resurrected 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 shared by definition, so it sits behind the published frontier too: a
// guest must no more silently rewind the host's history than the host may rewind its own.
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
// A batch that extended canonical history at the end, with any merge delta joining it there, extends
// the file the same way. 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);
}
// The absorbed deltas and the merge joining them are the batch; a sort that moved earlier deltas
// after them rewrites the file.
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) -> RetiredHotOps {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
self.pending_persist.hot_log = true;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
SyncTarget::retracted_marks(&self.session)
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
let touched = self.session.absorb_retracted_marks(remote);
if !touched.is_empty() {
self.remote_changes.touched.extend(touched);
self.pending_persist.hot_log = true;
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(())
}
}
+382 -58
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, TimeStamp, UserId, 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
@@ -36,6 +36,16 @@ impl<L: Layout> Gdd<L> {
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
/// The person using this device, from the editor's preferences. A change registers the peer again 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()
}
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &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,42 @@ 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_ops(ops)?;
self.persist_staged(&hot_ops)?;
Ok(hot_ops)
}
/// Every staged hot op takes this path, whether it came from a recorded batch, a whole-document diff or
/// a raw op: 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::EndTransaction)) {
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 +154,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 immediately retire exactly them into durable history as one unit.
/// Appends each hot frame first, so a crash before retirement still recovers the work. Returns the
/// retired `Rev`s. A no-op when nothing was staged, and the ops stay hot on a peer that does not retire.
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 +196,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: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
@@ -182,7 +207,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)?;
@@ -191,14 +216,67 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
fn persist_session_state(&mut self) -> Result<(), Error> {
/// What people state about the history: users and their names, later labels and tags.
pub fn metadata(&self) -> &HistoryMetadata {
&self.metadata
}
/// State a fact about a user, `wall_ms` being now on the wall clock: put on record, persisted, and told
/// to the room when it changed anything. Returns whether it did.
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)
}
/// State a fact about a rev, the interaction it closes in the History panel's terms: a label or a tag. Put on
/// record, appended to the file, and told to the room when it changed anything. Returns whether it did.
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(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
next_hot_sequence: self.session.next_hot_sequence(),
shared: self.shared,
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -210,7 +288,7 @@ impl<L: Layout> Gdd<L> {
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
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.registry())?;
Ok(())
}
@@ -239,45 +317,291 @@ 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 transactions have to be waiting before they retire. Later retirement fuses more
/// of a gesture's ops into one delta and keeps more of what an undo can still rewind silently.
pub const RETIRE_AFTER_TRANSACTIONS: usize = 10;
/// How long a closed transaction sits before it may retire, so every peer has seen all of it.
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
/// How long anything waits at most: a quiet session still retires, and a transaction 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 transaction, if it has one, with a marker that reaches the room like any
/// other hot op. The editor calls this at each undo-step boundary.
pub fn end_transaction(&mut self) -> Result<(), Error> {
let staged = self.session.end_transaction()?;
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 transaction while it is still hot: the ops leave the hot log here and, once
/// the retraction reaches them, on every peer, and they never retire. Returns whether there was a hot
/// transaction to take back; `false` means the step already retired and undo has to move the cursor.
/// What the ops named lands in the remote changes, so a mirror brings those entities into line with
/// whatever others wrote to them meanwhile.
pub fn retract_transaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(document_graph_storage::Retraction { ids, touched, ops }) = self.session.retract_transaction()? 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 in a session, the one [`Session::latest_own_interaction`]
/// names. The retirer drops it out of the shared line itself and tells the room, and what the step
/// named lands in the remote changes for the mirror to follow; anyone else asks the retirer, and the
/// head move comes back through the poll like any remote change. `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 any retired interaction out of the line, by the retirer directly or on request, the later steps minted
/// again on its parent; see [`Session::drop_interaction`]. What it named lands in the remote changes for the
/// mirror to follow. Works alone too, where this peer is its own retirer.
#[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: it comes back as a copy on top
/// of the line, by the retirer, directly or on request.
#[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 transaction, noting what they name as a change for the
/// mirror to follow: the redo of a step taken back 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 transaction the policy says is due at `now_ms`, on any monotonic millisecond clock the
/// caller keeps: closed transactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS),
/// once [`RETIRE_AFTER_TRANSACTIONS`](Self::RETIRE_AFTER_TRANSACTIONS) of them are waiting or the oldest
/// has waited [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). An open transaction never retires, whoever
/// its author is. Called once a frame by the editor with whether it is between steps; a peer that does
/// not retire only closes its own transaction here, once it has gone quiet for the minimum age.
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
// The editor's clock is the wall clock; retirements record it as the time a step happened.
self.wall_clock_ms = Some(now_ms);
// A gesture the editor never closed, or one interrupted by a reopen, closes on its own once quiet,
// but only while the editor is between steps: a pause inside a gesture must not split it, since undo
// takes a whole transaction back.
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_transaction()?;
self.own_last_staged_ms = None;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
let closed = self.session.closed_transactions();
let mut seen = std::mem::take(&mut self.transactions_seen);
let mut due = Vec::new();
let mut oldest_age: f64 = 0.0;
for transaction in &closed {
let Some(&marker) = transaction.ops.last() else { continue };
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
if age >= Self::RETIRE_MIN_AGE_MS && (transaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
due.push(transaction.clone());
oldest_age = oldest_age.max(age);
}
}
seen.retain(|marker, _| closed.iter().any(|transaction| transaction.ops.last() == Some(marker)));
self.transactions_seen = seen;
if due.len() >= Self::RETIRE_AFTER_TRANSACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
self.retire_transactions(&due)
} else {
Ok(Vec::new())
}
}
/// Close this peer's open transaction and retire every closed transaction, whoever its author is,
/// leaving other authors' open ones hot. The undo path takes this before moving the cursor, 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_transaction()?;
self.own_last_staged_ms = None;
let closed = self.session.closed_transactions();
self.retire_transactions(&closed)
}
/// Retire the given closed transactions, each as one interaction, in one history append and one
/// broadcast. A no-op for a peer that leaves retirement to the session host.
pub fn retire_transactions(&mut self, transactions: &[document_graph_storage::ClosedTransaction]) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() || transactions.is_empty() {
return Ok(Vec::new());
}
let mut revs = Vec::new();
let mut retired_hot_ops = Vec::new();
for transaction in transactions {
revs.extend(self.session.retire_transaction(transaction)?);
retired_hot_ops.extend(transaction.ops.iter().copied());
}
self.finish_retirement(&revs, &retired_hot_ops)?;
Ok(revs)
}
/// Working-copy checkpoint over a timestamp: promote every hot op stamped at or before `up_to` into
/// retired deltas, whatever its author and whether or not its transaction is closed. For callers
/// that own the whole log; a session retires by [`retire_transactions`](Self::retire_transactions).
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 with them and goes out with 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);
}
// In a session these deltas are about to reach peers, so the published frontier moves with them.
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
// the persists below so the frontier 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 session host and keep their hot ops until the host's 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(())
}
}
+36
View File
@@ -91,6 +91,36 @@ impl<L: Layout> Gdd<L> {
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
/// Point resource lookups at an external store instead of the working copy, for an embedder that
/// already keeps 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 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 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 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> {
@@ -104,6 +134,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(Arc<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 {
+8 -1
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,6 +15,10 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, from the editor's preferences: what the peer registers as in the CRDT,
/// so undo and authorship follow the person across the peer ids they accumulate. `0` until one is known.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
@@ -44,4 +48,7 @@ pub struct SessionState {
/// decodes these fields in declaration order.
#[serde(default)]
pub next_hot_sequence: HotSequence,
/// Whether the document was in its room when it was last persisted, so a reopen reconnects by itself.
#[serde(default)]
pub shared: bool,
}
+114
View File
@@ -0,0 +1,114 @@
// The record kept beside the history: what people state about the document's users, 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())
.await
.expect("create")
}
/// Let the room settle: greetings, the sync handshake and whatever was broadcast, however many rounds it takes.
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));
}
});
}
+31 -23
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, 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()).await {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
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())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -99,7 +99,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -116,7 +116,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -144,7 +144,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -192,7 +192,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -224,7 +224,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())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -254,7 +254,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())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -281,7 +281,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())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -306,7 +306,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -338,7 +338,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -369,7 +369,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())
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -395,7 +395,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -425,7 +425,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -492,7 +492,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -535,7 +535,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -590,7 +590,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())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -613,7 +613,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -634,11 +634,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
});
}
@@ -649,7 +657,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -703,7 +711,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())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -0,0 +1,48 @@
// 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. The recorded-batch path once appended its hot frames and
/// stopped there, so an edit made through the interface was persisted and never sent.
#[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())
.await
.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);
// Greeting the guest is what lets the host send to it; the hello itself is then 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");
});
}
+25 -4
View File
@@ -8,21 +8,42 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so a write older than the deletion is recognised as older whichever
/// order the two land in; readers see a tombstone as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// Attribute maps. Each entity carries an `attributes_timestamp` next to its map: when the map was last
/// written whole, by an addition or a whole-list input write. A key absent from the map is deleted as of
/// that stamp, so a write older than it is dropped, and a tombstone older than it is redundant.
pub type Attributes = BTreeMap<String, Value>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &Value)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
@@ -44,7 +65,7 @@ pub trait AttributesWrite {
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
self.insert(key.to_string(), Value::new(value, timestamp));
}
}
@@ -66,6 +87,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
self.get(key).filter(|v| !v.deleted).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -69,4 +69,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.
pub const INTERACTION_END: &str = "interaction_end";
/// When the delta entered history, in wall-clock milliseconds since the Unix epoch as its retirer saw them.
/// For showing when a step happened; order always comes from the graph, never from this.
pub const RETIRED_AT: &str = "retired_at";
}
+20 -19
View File
@@ -78,6 +78,11 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if its retirer recorded it.
pub fn retired_at(&self) -> Option<u64> {
self.attributes.get(attr::delta::RETIRED_AT).and_then(|recorded| recorded.value.as_u64())
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
pub fn recomputed_id(&self) -> Rev {
@@ -206,6 +211,9 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing; retirement takes an author's ops through
/// one of these as one unit and drops the marker itself. See [`Session::closed_transactions`](crate::Session::closed_transactions).
EndTransaction,
// Allow for future delta types without a model change
Other(serde_json::Value),
}
@@ -220,28 +228,21 @@ pub struct AttributeDelta {
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
/// Lands a single-key write. `floor` is when the map was last written whole: a key the map does not
/// hold is deleted as of then, so a write older than it is dropped. A deletion leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes, floor: TimeStamp) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if !force && timestamp <= decided {
return;
}
let entry = match value {
Some(value) => Value::new(value, timestamp),
None => Value::deleted(timestamp),
};
attributes.insert(key, entry);
}
+11 -6
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
for (key, _) in from.live_sources() {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
for (key, to_source) in to.live_sources() {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,16 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
let held = |attributes: &crate::Attributes, key: &str| attributes.get(key).filter(|value| !value.deleted).map(|value| value.value.clone());
for (key, _) in crate::attributes::live(from) {
if held(to, key).is_none() {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
for (key, to_value) in crate::attributes::live(to) {
if held(from, key).is_none_or(|from_value| from_value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -287,6 +288,7 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -344,6 +346,7 @@ mod tests {
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -354,6 +357,7 @@ mod tests {
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
);
@@ -379,6 +383,7 @@ mod tests {
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
);
File diff suppressed because it is too large. Load diff
+26 -3
View File
@@ -218,11 +218,13 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -336,7 +338,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -414,6 +424,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -446,10 +457,14 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -813,7 +828,15 @@ impl<'m> ScopedConversion<'m> {
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
}
+71 -6
View File
@@ -10,14 +10,25 @@
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp};
/// The indexes are maintained by every mutator, so the questions the per-frame and per-interaction
/// paths ask (is this timestamp retired, what are the tips, which hashes does history name) are probes
/// rather than scans of a history that only ever grows.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// The timestamps the deltas were authored at.
timestamps: HashSet<TimeStamp>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +38,16 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
for delta in deltas {
history.push(delta);
}
history
}
/// Where `rev` sits in the file order, if it is here.
pub fn position(&self, rev: Rev) -> Option<usize> {
self.index.get(&rev).copied()
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -41,7 +60,31 @@ impl History {
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.deltas.iter().any(|delta| delta.timestamp == timestamp)
self.timestamps.contains(&timestamp)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
/// Whether the deltas from `from` on extend the canonical order as they stand: a chain, each the
/// first's child in turn, hanging off the last delta before them. Such a tail is what every
/// retirement in a hosted session appends, and needs no re-sort.
///
/// The sort emits, among the deltas whose parents are all out, the lowest rev. A chain on the last
/// delta is alone in that set at every step, so it sorts where it was appended. A tail whose root
/// hangs off an earlier delta competes with that delta's later siblings and may sort before them.
pub fn extends_canonically(&self, from: usize) -> bool {
let Some(tail) = self.deltas.get(from..) else { return true };
let mut previous = from.checked_sub(1).map(|position| self.deltas[position].id);
for delta in tail {
if delta.parent != previous || matches!(delta.kind, RegistryDelta::Merge { .. }) {
return false;
}
previous = Some(delta.id);
}
true
}
pub fn len(&self) -> usize {
@@ -56,10 +99,23 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
self.timestamps.insert(delta.timestamp);
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -69,6 +125,11 @@ impl History {
self.deltas.iter()
}
/// The delta at `position` in topological order.
pub 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).
///
@@ -149,6 +210,11 @@ impl History {
next_sample_distance *= 2;
}
}
// The root always: two copies of one document share it however far their lines have diverged, so
// a peer answering the sample can tell a divergent copy from a stranger and merge rather than replace.
if samples.last() != Some(&current) {
samples.push(current);
}
samples
}
@@ -162,8 +228,7 @@ impl History {
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
@@ -0,0 +1,283 @@
//! What people say about a document's history, kept beside it rather than in it: who its users are, what
//! its steps are called and which are tagged. None of it is folded into the document, so moving the head
//! never changes it and stating it never rewrites a delta. Every statement is a [`MetadataFact`] with a
//! wall-clock stamp, the newer of two about the same thing winning, which makes the record a state that
//! 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 a rename appends one line and 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: the interaction it closes, in the History panel's terms.
#[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 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 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. Nothing changes when the same value already stands, whatever its stamp;
/// otherwise the fact is stamped no earlier than the one it replaces, so a clock behind a peer's still
/// gets its say. Returns the fact as stated, for appending to the file and telling the room.
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 one fact as stated elsewhere: it lands unless an equal or newer stamp stands for the same thing.
/// Returns whether it landed.
pub 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);
}
}
+2
View File
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
+7 -1
View File
@@ -5,11 +5,13 @@ pub mod crdt;
pub mod delta;
pub mod document;
pub mod history;
pub mod history_metadata;
pub mod ids;
pub mod model;
pub mod registry;
pub mod resources;
pub mod session;
pub mod touched;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -22,11 +24,13 @@ 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 registry::*;
pub use resources::*;
pub use session::*;
pub use touched::Touched;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -36,10 +40,12 @@ 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;
}
+57 -10
View File
@@ -4,6 +4,19 @@ use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// When the node was last added, so a concurrent addition of the same id and a removal resolve by
/// last-writer-wins rather than by arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which is what decides its network between concurrent additions
/// of one id; every other field carries its own timestamp.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so a whole-list write and a per-slot write resolve the
/// same whichever lands first: the list follows the newer of the two, and a slot the older list also
/// held keeps whichever of its values is newer.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
@@ -11,6 +24,9 @@ pub struct Node {
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -51,33 +67,38 @@ impl Node {
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
let slot = InputSlot {
input: NodeInput::Value {
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
};
let slot = InputSlot::unset(TimeStamp::ORIGIN);
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![slot; inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
/// Dead content for a node nothing has added yet, so a write arriving ahead of the addition has
/// somewhere to land. Every field is at the origin, so the addition's values win when it comes.
pub(crate) fn placeholder() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network: crate::ROOT_NETWORK,
}
}
@@ -90,6 +111,26 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -121,10 +162,16 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// When the network was last added; see [`Node::presence`].
#[serde(default)]
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
+63 -8
View File
@@ -1,7 +1,14 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// is a function of the set of ops applied and not of their order. An entity that was removed keeps a
/// tombstone here with the removal's timestamp: an addition or a write stamped earlier is recognised as
/// older and dropped whichever order it arrives in, and a write stamped later revives the entity from
/// the tombstone. The live maps hold only what exists, so a reader never sees a tombstone.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -9,13 +16,61 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
/// Which person each device is: a per-device `PeerId` to a per-human `UserId`, registered by a device's
/// first contribution via `RegistryDelta::RegisterPeer` and again whenever its user changes. Last writer
/// wins on the stamp like every other field, so undo and history authorship scope by person across the
/// peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content as of the removal, for reviving it, and when it was removed, for
/// deciding whether a later-arriving op is older or newer than the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet: the content only holds writes that arrived ahead of the addition,
/// and the entity stays dead until one folds in. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
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.
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))
}
/// Whether both registries removed the same entities at the same times. The removal marks decide
/// how ops still to arrive land, so two registries that agree on their values but not on these
/// will not stay agreed.
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.at == mark.at && 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
@@ -85,10 +140,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.len() != b.len() {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
return false;
}
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -100,8 +155,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+122 -30
View File
@@ -18,6 +18,21 @@ pub struct SourceKey {
pub struct SourceValue {
pub source: serde_json::Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an addition older than the removal is recognised
/// as older whichever order the two land in; readers see a tombstone as absent.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -26,8 +41,13 @@ pub struct SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// When the entry was last added; see [`Node::presence`](crate::Node).
pub presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry: a key the chain does not hold
/// is deleted as of then, the way [`Attributes`](crate::Attributes) work.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -39,12 +59,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self { sources, hash, hash_timestamp })
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
@@ -68,52 +104,106 @@ impl ResourceEntry {
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The source body and timestamp stored under `key`, if any.
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map(|index| &self.sources[index].1)
.filter(|value| !value.deleted)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
/// The live sources in precedence order, tombstones skipped.
pub fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
}
_ => false,
/// Writes the chain whole at `at`: every source is written then and every other key is deleted as of
/// then, which the floor records without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
for (_, value) in &mut self.sources {
value.timestamp = at;
}
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => {
if value.timestamp >= self.sources_timestamp {
self.sources.insert(index, (key, value));
}
}
}
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
@@ -130,7 +220,7 @@ impl ResourceEntry {
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.sources.iter().any(|(_, value)| {
self.live_sources().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
@@ -141,7 +231,7 @@ impl ResourceEntry {
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -250,6 +340,7 @@ mod tests {
SourceValue {
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
@@ -280,6 +371,7 @@ mod tests {
SourceValue {
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
+634 -146
View File
@@ -2,7 +2,7 @@
use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -30,25 +30,17 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
/// a working copy wants [`with_identity`](Self::with_identity).
pub fn with_peer(peer: PeerId) -> Self {
Self::with_identity(peer, UserId(peer.0))
}
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
/// and what undo and history authorship scope by.
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
Self {
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
retired: RetiredHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
},
document: Document::empty(peer, user),
remote_tips: HashMap::new(),
runtime_base: None,
}
@@ -58,6 +50,30 @@ impl Session {
self.document.peer
}
pub fn user(&self) -> UserId {
self.document.user
}
/// Change the person behind this peer. The next staged batch registers the peer again, and the newer
/// registration wins everywhere.
pub fn set_user(&mut self, user: UserId) {
self.document.user = user;
}
/// The person a peer is registered to, if its registration has landed here.
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
if peer == self.document.peer {
return Some(self.document.user);
}
self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user)
}
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
pub fn is_mine(&self, peer: PeerId) -> bool {
self.user_of(peer) == Some(self.document.user)
}
pub fn registry(&self) -> &Registry {
&self.document.working_registry
}
@@ -164,8 +180,9 @@ impl Session {
return Ok(Vec::new());
}
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
let user = UserId(self.document.peer.0);
let registered = self.document.working_registry.peer_users.get(&self.document.peer).map(|registration| registration.user);
if registered != Some(self.document.user) {
let user = self.document.user;
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
}
@@ -215,8 +232,6 @@ impl Session {
self.document.redo_stack.clear();
}
// The reverse must read the pre-op value of a target that may have been concurrently removed.
self.document.ensure_referenced_exist(target, &op)?;
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
@@ -244,7 +259,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -257,16 +272,11 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
retired: RetiredHotOps::default(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
runtime_base: None,
@@ -275,8 +285,8 @@ impl Session {
/// Rebuild the registry from scratch by applying every delta in causal order.
/// `deltas` must be in causal order (every parent before its children).
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_peer(peer);
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -297,25 +307,258 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// The hot ops a `retire(up_to)` call would drain. Sent with the deltas for peers to drop exactly
/// these; the cutoff alone doesn't transfer, a lagging op can arrive below it afterwards.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Drop hot ops another peer has retired without retiring them locally. Refolds like
/// [`absorb_retired_marks`](Self::absorb_retired_marks).
/// Drop hot ops another peer has retired without retiring them locally. The registries need nothing:
/// each op's effect is a function of its timestamp, so the working registry holds the same fold with
/// or without the hot copy of an op whose delta has landed.
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Result<(), CrdtError> {
let before = self.document.hot_log.len();
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
let retired_ids: HashSet<HotOpId> = retired.iter().copied().collect();
self.document.hot_log.retain(|hot_op| !retired_ids.contains(&hot_op.id()));
// How a peer that did not retire these learns they are in history now.
self.document.mark_retired(retired.iter().copied());
if before != self.document.hot_log.len() {
self.refold_registries()?;
Ok(())
}
/// Take back this peer's latest transaction while it is still hot: its ops since the previous marker,
/// closed or not. They leave the log here and, once the retraction reaches them, everywhere, and they
/// never retire, so an accidental gesture and its undo leave no step in history. `None` when there is
/// nothing hot to take back, or when the transaction has already retired somewhere this peer knows
/// of, which makes it an undo of a retired step instead. Returns the ids to send and what they named.
pub fn retract_transaction(&mut self) -> Result<Option<Retraction>, CrdtError> {
let peer = self.document.peer;
let mut own: Vec<&HotOp> = self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp.peer == peer).collect();
own.sort_by_key(|hot_op| hot_op.sequence);
// The latest transaction: everything after the previous marker, through a trailing marker if any.
let closed_before = match own.last() {
Some(last) if matches!(last.op, RegistryDelta::EndTransaction) => own.len() - 1,
Some(_) => own.len(),
None => return Ok(None),
};
let start = own[..closed_before]
.iter()
.rposition(|hot_op| matches!(hot_op.op, RegistryDelta::EndTransaction))
.map_or(0, |position| position + 1);
if own[start..].iter().all(|hot_op| matches!(hot_op.op, RegistryDelta::EndTransaction)) {
return Ok(None);
}
let ids: Vec<HotOpId> = own[start..].iter().map(|hot_op| hot_op.id()).collect();
if ids.iter().any(|&id| self.document.retired.covers(id)) {
return Ok(None);
}
self.runtime_base = None;
let (touched, taken) = self.document.retract_hot_ops(&ids);
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::EndTransaction)).collect();
Ok(Some(Retraction { ids, touched, ops }))
}
/// Take back hot ops another peer retracted. See [`retract_transaction`](Self::retract_transaction).
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
self.runtime_base = None;
self.document.retract_hot_ops(ids).0
}
/// The last delta of this person's latest retired interaction on the line, if any: what an undo of a
/// retired step in a session names. Any peer of the same user counts, so a fresh copy undoes what its
/// user did from another device or before a rejoin under a new peer id.
pub fn latest_own_interaction(&self) -> Option<Rev> {
let mut current = self.document.head?;
loop {
let delta = self.document.history.get(current)?;
if delta.is_interaction_end() && self.is_mine(delta.author) {
return Some(current);
}
current = delta.parent?;
}
}
/// Undo a retired interaction in a session: drop it out of the shared line. The snapshot refolds to the
/// interaction's parent, the head moves to the interaction's parent, and the later steps
/// are minted again as copies on that parent, same author, stamp and kind, so every peer that follows
/// the move holds identical revs. The interaction and the originals stay as an abandoned branch. Since
/// every op commutes, the result is the fold of the line without the interaction: a field one of the
/// later steps wrote keeps that later value. Returns the move to broadcast and what the dropped ops
/// named. Only the retirer does this; a guest asks it to.
pub fn drop_interaction(&mut self, undone: Rev) -> Result<(HeadMove, Touched), CrdtError> {
let from = self.document.head;
let base = self.interaction_start_parent(undone).ok_or(CrdtError::NotUndoable(undone))?;
// The line from the head down to the interaction's parent, newest first.
let mut walked = Vec::new();
let mut current = from;
while current != Some(base) {
let rev = current.ok_or(CrdtError::NotFoundInHistory(undone))?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
return Err(CrdtError::NotUndoable(undone));
}
current = delta.parent;
walked.push(delta);
}
let position = walked.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
// The snapshot has to be the fold of the line without the interaction. Walking back over the stored
// reverses would leave every field at the stamp of the op reverted, and the copies landing again with
// those same stamps would tie and lose, so the fold is taken from history at the new head instead.
self.document.head = Some(base);
self.document.retired_snapshot = self.snapshot_from_history()?;
let mut touched = Touched::default();
for delta in &walked[position..] {
touched.record(&delta.kind);
}
Ok(())
let mut copies = Vec::new();
for original in walked[..position].iter().rev() {
let revs = self.commit_ops_authored_at([(original.kind.clone(), Some(original.timestamp))], true)?;
// A copy keeps what was said about the original: its interaction end, and when it was retired.
if let Some(&rev) = revs.last() {
self.carry_attributes(original, rev);
}
copies.extend(revs.iter().filter_map(|&rev| self.document.history.get(rev).cloned()));
}
// Two branches now: the file order is the canonical one, which every peer computes alike.
self.document.history.canonical_sort();
self.document.rebuild_working();
self.runtime_base = None;
Ok((
HeadMove {
from,
head: self.document.head,
copies,
},
touched,
))
}
/// Move the shared head to an ancestor in a session: the line from the head down to `target` stays as an
/// abandoned branch, nothing is minted, and the snapshot is refolded at the target for the reason
/// [`drop_interaction`](Self::drop_interaction) gives. Returns the move to broadcast and what the steps left
/// behind named. Only the retirer does this; a guest asks it to.
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
let from = self.document.head;
if from == Some(target) {
return Err(CrdtError::NothingToUndo);
}
let mut touched = Touched::default();
let mut current = from;
while current != Some(target) {
let rev = current.ok_or(CrdtError::NotFoundInHistory(target))?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?;
touched.record(&delta.kind);
current = delta.parent;
}
self.document.head = Some(target);
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.redo_stack.clear();
self.document.rebuild_working();
self.runtime_base = None;
Ok((
HeadMove {
from,
head: Some(target),
copies: Vec::new(),
},
touched,
))
}
/// Follow another peer's cursor move: refold the snapshot to where the copies start, take the copies on,
/// and put the head where the mover put it. Returns what the walked-over ops named. The move only
/// applies from the head it started at; anywhere else this peer has diverged and needs a resync.
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
if self.document.head != moved.from {
return Err(CrdtError::CursorMismatch {
expected: moved.from,
found: self.document.head,
});
}
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
let mut walked = Vec::new();
let mut current = self.document.head;
while current != base {
let rev = current.ok_or(CrdtError::NothingToUndo)?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
current = delta.parent;
walked.push(delta);
}
let mut touched = Touched::default();
for delta in &walked {
touched.record(&delta.kind);
}
// The fold of the line without what was dropped, for the same reason `drop_interaction` takes it from
// history rather than walking back.
self.document.head = base;
self.document.retired_snapshot = self.snapshot_from_history()?;
for copy in &moved.copies {
if let Some(parent) = copy.parent
&& !self.document.history.contains(parent)
{
return Err(CrdtError::NotFoundInHistory(parent));
}
self.document.apply_op_with(RegistryTarget::Snapshot, copy.kind.clone(), copy.timestamp, ApplyMode::Idempotent)?;
self.document.history.push(copy.clone());
self.document.head = Some(copy.id);
}
if self.document.head != moved.head {
return Err(CrdtError::CursorMismatch {
expected: moved.head,
found: self.document.head,
});
}
self.document.redo_stack.clear();
self.document.history.canonical_sort();
self.document.rebuild_working();
self.runtime_base = None;
Ok(touched)
}
/// Redo a dropped interaction in a session: mint its ops again on top of the line, as one interaction.
/// Its writes carry their original stamps, so a field someone wrote since keeps the newer value.
/// Returns the new revs, for an ordinary retirement-style broadcast.
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
let base = self.interaction_start_parent(dropped).ok_or(CrdtError::NotUndoable(dropped))?;
let mut originals = Vec::new();
let mut current = Some(dropped);
while current != Some(base) {
let rev = current.ok_or(CrdtError::NothingToRedo)?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
current = delta.parent;
originals.push(delta);
}
originals.reverse();
let ops: Vec<_> = originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))).collect();
let revs = self.commit_ops_authored_at(ops, true)?;
// The copies keep what was said about the originals, when they were retired among it.
if revs.len() == originals.len() {
for (original, &rev) in originals.iter().zip(&revs) {
self.carry_attributes(original, rev);
}
}
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
}
self.document.history.canonical_sort();
self.document.rebuild_working();
self.runtime_base = None;
Ok(revs)
}
/// Which hot ops were taken back, for a peer catching up.
pub fn retracted_marks(&self) -> &RetiredHotOps {
&self.document.retracted
}
/// Take on a peer's retractions: whatever they cover that this log still holds is taken back here too.
pub fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Touched {
let held: Vec<HotOpId> = self.document.hot_log.iter().map(HotOp::id).filter(|&id| remote.covers(id)).collect();
self.document.retracted.absorb(remote);
if held.is_empty() {
return Touched::default();
}
self.retract_hot_ops(&held)
}
/// Which hot ops history already covers, for a peer catching up. See [`RetiredHotOps`].
@@ -323,12 +566,9 @@ impl Session {
&self.document.retired
}
/// See [`RetiredHotOps::absorb`]. A drop owes a refold, since the working registry holds the op's
/// effect in hot-log order where the snapshot holds it in canonical order.
/// See [`RetiredHotOps::absorb`].
pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), CrdtError> {
if self.document.absorb_retired(remote) {
self.refold_registries()?;
}
self.document.absorb_retired(remote);
Ok(())
}
@@ -347,44 +587,82 @@ impl Session {
/// takes the last removal in canonical order, and with the whole history in view that can be one past
/// the replay position, whose snapshot places the entity in a network the replay has not created yet.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
// The oracle for tests and the simulation. The live registries are never rebuilt from history:
// every op lands the same whatever order it arrives in, so applying each once is the fold.
let reachable = self.document.history.ancestors(self.document.head);
let mut folded = self.clone();
folded.document.retired_snapshot = Registry::default();
folded.document.history = History::new();
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
folded.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
folded.document.history.push(delta.clone());
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
}
Ok(folded.document.retired_snapshot)
Ok(scratch.working_registry)
}
/// Rebuild both registries from canonical history, then re-layer the hot tail. A full replay; callers
/// check it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
// Cleared only on the way out. The deltas are in history either way, and a failure here leaves the
// registries derived from an older one until something retries.
self.document.refold_owed = true;
self.document.retired_snapshot = self.snapshot_from_history()?;
pub fn history_len(&self) -> usize {
self.document.history.len()
}
// One left unapplicable is kept, not dropped: a later delta or hot op can still supply its referent.
self.document.working_registry = self.document.retired_snapshot.clone();
let mut failure = None;
for hot_op in std::mem::take(&mut self.document.hot_log) {
if let Err(error) = self.document.replay_hot_op(hot_op.clone()) {
self.document.hot_log.push(hot_op);
failure = failure.or(Some(error));
/// Take a retirer's deltas on and put the head where the retirer's is, minting nothing: a guest in a
/// session follows the host's line rather than merging with it. A batch that extends this head applies
/// in place; anything else, a line the host moved while this peer was away, refolds the snapshot to the
/// new head, and the old tip stays as an abandoned branch. `head` defaults to the batch's last delta.
pub fn follow(&mut self, incoming: Vec<Delta>, head: Option<Rev>) -> Result<MergeOutcome, CrdtError> {
let before = self.document.head;
let length_before = self.document.history.len();
let head = head.or_else(|| incoming.last().map(|delta| delta.id)).or(before);
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
for parent in delta.all_parents() {
if !self.document.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
self.document.history.push(delta);
}
if head == before && self.document.history.len() == length_before {
return Ok(MergeOutcome::NoOp);
}
if let Some(error) = failure {
return Err(error);
}
// The new head extends this one when walking its parents back over the batch reaches this head.
let mut chain = Vec::new();
let mut current = head;
let extends = loop {
if current == before {
break true;
}
let Some(rev) = current else { break false };
let Some(delta) = self.document.history.get(rev) else { break false };
if self.document.history.position(rev).is_some_and(|position| position < length_before) {
break false;
}
// A merge joins a line this chain does not walk, one this peer may hold as a branch it walked away
// from, so the snapshot has to be folded from the new head's whole ancestry.
if delta.all_parents().count() > 1 {
break false;
}
chain.push(delta.clone());
current = delta.parent;
};
self.document.refold_owed = false;
Ok(())
if extends {
for delta in chain.iter().rev() {
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
}
self.document.head = head;
} else {
self.document.head = head;
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
self.runtime_base = None;
}
if !self.document.history.extends_canonically(length_before) {
self.document.history.canonical_sort();
}
self.document.redo_stack.clear();
Ok(head.map_or(MergeOutcome::NoOp, MergeOutcome::FastForward))
}
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
@@ -393,15 +671,13 @@ impl Session {
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
let length_before = self.document.history.len();
// Each delta enters history before the next is applied, so a later delta in the batch that
// targets something an earlier one removed can resurrect it.
// Each delta lands on both registries once. Every field, presence included, is last-writer-wins on
// the delta's timestamp, so the order the batch arrives in does not decide anything.
let mut absorbed_ids = HashSet::new();
let mut arrival_order = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
arrival_order.push(delta.id);
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
// Working is snapshot plus hot tail, so a delta lands on both; cloning would promote hot ops.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
@@ -409,25 +685,28 @@ impl Session {
self.document.history.push(delta);
}
if absorbed_ids.is_empty() {
// Nothing new, but a refold left owed by an earlier failure is still the only way the registries
// catch up with the history they are derived from.
if self.document.refold_owed {
self.refold_registries()?;
}
return Ok(MergeOutcome::NoOp);
}
self.document.history.canonical_sort();
// The loop folds in arrival order, and concurrent ops do not all commute: a remove and a change to
// the same target resolve by whichever lands second.
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
// A batch that chains off the last delta is already in canonical order, which is every retirement
// a host sends, and costs nothing to place. Anything else is sorted into place, over all of history.
// The order matters to the history file and to `Rev` determinism only; the registries do not care.
let extends = self.document.history.extends_canonically(length_before);
if !extends {
self.document.history.canonical_sort();
}
let history = &self.document.history;
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
let parents: Vec<Rev> = if extends && self.document.head == last_before {
// The chain hangs off `head`, so `head` is its ancestor and the chain's end is the one tip.
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
} else {
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
};
let outcome = match parents.as_slice() {
[tip] => MergeOutcome::FastForward(*tip),
@@ -442,49 +721,126 @@ impl Session {
};
self.document.head = outcome.head();
// After `head`, since the fold is over its ancestry.
if !folded_in_canonical_order || self.document.refold_owed {
self.refold_registries()?;
// A merge joins a line whose deltas may already sit in history as a branch this peer walked away
// from, and applying the batch once did not bring their effects into the snapshot; a batch sorted in
// ahead of the tail likewise. The fold of the new head's ancestry is the snapshot either way.
if !extends || matches!(outcome, MergeOutcome::Merged(_)) {
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
self.runtime_base = None;
}
Ok(outcome)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, each keeping the timestamp it was
/// authored at.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
// Hot-log order is causal, so the deltas commit in an order their references survive.
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
/// Closes this peer's open transaction with a [`RegistryDelta::EndTransaction`] marker, so the retirer
/// can take the ops before it as one unit. Returns what was staged, the marker last: a peer whose
/// registration left the line, on a dropped step say, registers again ahead of it, and that op has
/// to reach the room too or its run has a gap. Empty when nothing is open: an author's transaction is
/// open once it has an op past its last marker.
pub fn end_transaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
let peer = self.document.peer;
let open = self
.document
.hot_log
.iter()
.rev()
.find(|hot_op| hot_op.timestamp.peer == peer)
.is_some_and(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction));
if !open {
return Ok(Vec::new());
}
self.stage_ops([RegistryDelta::EndTransaction])
}
// Retiring by timestamp reorders against the hot-log order the working registry applied: past a
// skipped op, everything drained was applied here before it.
let mut skipped = false;
let mut reordered = false;
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
reordered |= skipped;
drained.push(hot_op);
} else {
skipped = true;
remaining.push(hot_op);
/// Every author's closed transactions in the hot log, the earliest closed first. An author's ops past
/// its last marker are its open transaction and never appear here, whoever the author is, so a gesture
/// in progress stays hot while a later one from someone else retires: every op commutes, so the order
/// transactions retire in does not bear on the registry.
pub fn closed_transactions(&self) -> Vec<ClosedTransaction> {
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = HashMap::new();
for hot_op in &self.document.hot_log {
by_author.entry(hot_op.timestamp.peer).or_default().push(hot_op);
}
let mut closed = Vec::new();
for (author, mut ops) in by_author {
ops.sort_by_key(|hot_op| hot_op.sequence);
let mut expected = self.document.retired.retired_up_to.get(&author).copied().unwrap_or(HotSequence::NONE).next();
let mut current = Vec::new();
let mut contiguous = true;
for hot_op in ops {
// An op retired past a gap is not in the log and not missing either.
while expected < hot_op.sequence && self.document.retired.covers(HotOpId { peer: author, sequence: expected }) {
expected = expected.next();
}
contiguous &= hot_op.sequence == expected;
expected = hot_op.sequence.next();
current.push(hot_op.id());
if matches!(hot_op.op, RegistryDelta::EndTransaction) {
closed.push(ClosedTransaction {
author,
ops: std::mem::take(&mut current),
closed_at: hot_op.timestamp,
contiguous,
});
contiguous = true;
}
}
}
self.document.hot_log = remaining;
self.document.mark_retired(drained.iter().map(HotOp::id));
closed.sort_by_key(|transaction| transaction.closed_at);
closed
}
let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?;
// Structural ops have no timestamp to arbitrate, so the reorder changes the outcome.
if reordered {
self.refold_registries()?;
/// Retire one closed transaction as one interaction, coarsened: of the writes to one field, only the
/// newest becomes a delta, since every field is last-writer-wins and the earlier ones have no effect
/// on the fold; structural ops and every write that is the transaction's newest to its field stay.
/// The marker commits nothing, the last delta is marked as the interaction's end, and every op of the
/// transaction is marked retired, dropped ones included. Returns the new revs.
pub fn retire_transaction(&mut self, transaction: &ClosedTransaction) -> Result<Vec<Rev>, CrdtError> {
let revs = self.retire_hot_ops_with(&transaction.ops, true)?;
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
}
Ok(revs)
}
/// The hot ops stamped at or before `up_to`, which is what [`retire`](Self::retire) drains. Sent with
/// the deltas for peers to drop exactly these; the cutoff alone doesn't transfer, a lagging op can
/// arrive below it afterwards.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
/// authored at. Markers commit nothing. Ops not in the log are ignored.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
self.retire_hot_ops_with(ids, false)
}
fn retire_hot_ops_with(&mut self, ids: &[HotOpId], coarsened: bool) -> Result<Vec<Rev>, CrdtError> {
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
self.document.hot_log = kept;
self.document.mark_retired(drained.iter().map(HotOp::id));
let drained = if coarsened { coarsen(drained) } else { drained };
let ops = drained
.into_iter()
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
self.commit_ops_authored_at(ops, true)
}
/// Promote every hot op stamped at or before `up_to`, whatever its author and whether or not its
/// transaction is closed. For callers that own the whole log, tests mostly; a session retires by
/// [`retire_transaction`](Self::retire_transaction).
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let ids = self.hot_ops_up_to(up_to);
self.retire_hot_ops(&ids)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
pub fn mark_interaction_end(&mut self, rev: Rev) {
@@ -492,6 +848,24 @@ impl Session {
self.document.history.mark_interaction_end(rev, timestamp);
}
/// Record when these retired deltas entered history, in wall-clock milliseconds as the retirer saw them,
/// as an attribute outside their revs: for showing when a step happened, never for ordering.
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
let timestamp = self.document.clock.tick();
for &rev in revs {
self.document
.history
.annotate(rev, crate::attributes::attr::delta::RETIRED_AT, serde_json::Value::from(wall_ms), timestamp);
}
}
/// Give a minted copy every attribute of the delta it stands for, each with the stamp it had.
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
for (key, value) in crate::attributes::live(&original.attributes) {
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
}
}
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
@@ -601,9 +975,9 @@ impl Session {
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_peer(peer);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
@@ -621,9 +995,12 @@ impl Session {
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
}
/// Retired deltas not reachable from `known`, in replay order.
/// Retired deltas on `head`'s ancestry that are not reachable from `known`, in replay order. A branch
/// the cursor walked away from stays here: it is this peer's to redo, and a peer that merged it would
/// bring the undone step back. Merging thus joins heads, never every tip.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
self.document.history.deltas_unknown_to(known)
let reachable = self.document.history.ancestors(self.document.head);
self.document.history.deltas_unknown_to(known).into_iter().filter(|delta| reachable.contains(&delta.id)).collect()
}
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
@@ -645,15 +1022,7 @@ impl Session {
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
_ => {}
}
}
hashes.extend(self.document.history.resource_hashes());
hashes
}
@@ -719,7 +1088,7 @@ impl Session {
}
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
/// test can observe a failure (e.g. `NotFoundInHistory`).
#[cfg(test)]
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
self.commit_ops(std::iter::once(op), false).map(|_| ())
@@ -911,27 +1280,146 @@ pub enum CrdtError {
TargetNodeDoesNotExist(NodeId),
#[error("Network {0} does not exist")]
NetworkDoesNotExist(NetworkId),
#[error("Resource {0:?} does not exist")]
ResourceDoesNotExist(ResourceId),
#[error("Input index {0} out of bounds")]
InputIndexOutOfBounds(usize),
#[error("Export slot index {0} out of bounds")]
ExportSlotOutOfBounds(u32),
#[error("Delta {0} not found in history")]
NotFoundInHistory(Rev),
#[error("No history entry resurrects node {0}")]
NodeNotInHistory(NodeId),
#[error("No history entry resurrects network {0}")]
NetworkNotInHistory(NetworkId),
#[error("Nothing to undo")]
NothingToUndo,
#[error("Nothing to redo")]
NothingToRedo,
#[error("Interaction {0} cannot be dropped: it is the base or spans a merge")]
NotUndoable(Rev),
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
#[error("Node {0} already exists")]
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
NetworkAlreadyExists(NetworkId),
/// PeerId is already registered to a different UserId.
#[error("Peer {0:?} is already registered to a different user")]
PeerRegistrationConflict(PeerId),
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
/// Which field of the registry a write lands on, for coarsening.
#[derive(Clone, PartialEq, Eq, Hash)]
enum FieldKey {
NodeInput(NodeId, u32),
NodeInputAttribute(NodeId, u32, String),
NodeAttribute(NodeId, String),
NodeImplementation(NodeId),
NodeInputs(NodeId),
NetworkExport(NetworkId, u32),
NetworkAttribute(NetworkId, String),
ResourceHash(ResourceId),
Source(ResourceId, crate::SourceKey),
DocumentAttribute(String),
}
/// The field a write lands on, `None` for an op that is not a plain field write.
fn field_of(op: &RegistryDelta) -> Option<FieldKey> {
Some(match op {
RegistryDelta::ChangeNodeInput { id, index, .. } => FieldKey::NodeInput(*id, *index),
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => FieldKey::NodeInputAttribute(*id, *index, delta.key.clone()),
RegistryDelta::ChangeNodeAttribute { id, delta } => FieldKey::NodeAttribute(*id, delta.key.clone()),
RegistryDelta::SetNodeImplementation { id, .. } => FieldKey::NodeImplementation(*id),
RegistryDelta::SetNodeInputs { id, .. } => FieldKey::NodeInputs(*id),
RegistryDelta::SetNetworkExport { id, index, .. } => FieldKey::NetworkExport(*id, *index),
RegistryDelta::ChangeNetworkAttribute { id, delta } => FieldKey::NetworkAttribute(*id, delta.key.clone()),
RegistryDelta::SetResourceHash { id, .. } => FieldKey::ResourceHash(*id),
RegistryDelta::AddSource { id, key, .. } | RegistryDelta::RemoveSource { id, key } => FieldKey::Source(*id, *key),
RegistryDelta::ChangeDocumentAttribute { delta } => FieldKey::DocumentAttribute(delta.key.clone()),
_ => return None,
})
}
/// What a write refers to beyond its own field: a node an input is wired to, or a network an
/// implementation points at. A reference is evidence the target exists at the write's stamp, so a write
/// that carries one only drops when the write superseding it carries the same.
fn references_of(op: &RegistryDelta) -> Vec<u64> {
let of_input = |input: &crate::NodeInput| match input {
crate::NodeInput::Node { id, .. } => Some(id.0),
_ => None,
};
match op {
RegistryDelta::ChangeNodeInput { new_input, .. } => of_input(new_input).into_iter().collect(),
RegistryDelta::SetNodeInputs { inputs, .. } => inputs.iter().filter_map(|slot| of_input(&slot.input)).collect(),
RegistryDelta::SetNetworkExport { export, .. } => export.as_ref().and_then(of_input).into_iter().collect(),
RegistryDelta::SetNodeImplementation {
implementation: Implementation::Network(network),
..
} => vec![network.0],
_ => Vec::new(),
}
}
/// Coarsens one transaction's ops, in application order: a write to a field that a later write in the
/// same transaction also lands on has no effect on the fold and is dropped, unless it refers to
/// something the later write does not. A whole-list input write supersedes every earlier input write on
/// its node. Structural ops stay.
fn coarsen(mut ops: Vec<HotOp>) -> Vec<HotOp> {
// The newest write is the newest by stamp, which is the author's order. The hot log holds an author's
// ops in arrival order, and a re-announcement after a lapsed link delivers later ones first; taking the
// log's order for time would keep an older write and retire a value the working registry never showed.
ops.sort_by_key(|hot_op| hot_op.timestamp);
let mut keep = vec![true; ops.len()];
let mut latest: HashMap<FieldKey, usize> = HashMap::new();
for (index, hot_op) in ops.iter().enumerate() {
let Some(field) = field_of(&hot_op.op) else { continue };
let references = references_of(&hot_op.op);
let supersedes = |earlier: &HotOp| references_of(&earlier.op).iter().all(|reference| references.contains(reference));
if let FieldKey::NodeInputs(id) = field {
latest.retain(|key, &mut earlier| {
let same_node = matches!(key, FieldKey::NodeInput(node, _) | FieldKey::NodeInputAttribute(node, _, _) | FieldKey::NodeInputs(node) if *node == id);
if same_node && supersedes(&ops[earlier]) {
keep[earlier] = false;
return false;
}
true
});
} else if let Some(&earlier) = latest.get(&field)
&& supersedes(&ops[earlier])
{
keep[earlier] = false;
}
latest.insert(field, index);
}
ops.into_iter().zip(keep).filter_map(|(hot_op, keep)| keep.then_some(hot_op)).collect()
}
/// An author's closed transaction sitting in the hot log, as [`Session::closed_transactions`] lists them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClosedTransaction {
pub author: PeerId,
/// Every op of the transaction in the author's order, the closing marker last.
pub ops: Vec<HotOpId>,
/// When the author closed it: the marker's stamp.
pub closed_at: TimeStamp,
/// Whether every op from the author's retired frontier through the marker is here. One with a gap is
/// waiting on a re-announcement; retiring it anyway commits what arrived.
pub contiguous: bool,
}
/// What [`Session::retract_transaction`] took back.
#[derive(Clone, Debug)]
pub struct Retraction {
/// The ids to send, so every peer drops the same ops.
pub ids: Vec<HotOpId>,
/// What the ops named, for a mirror to bring back into line.
pub touched: Touched,
/// The ops themselves, marker aside, for a redo to stage afresh.
pub ops: Vec<RegistryDelta>,
}
/// A shared cursor move, as [`Session::drop_interaction`] produces it and [`Session::apply_head_move`]
/// follows it: the head it started from, the head it ends at, and the steps minted again in between.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HeadMove {
pub from: Option<Rev>,
pub head: Option<Rev>,
pub copies: Vec<Delta>,
}
@@ -0,0 +1,608 @@
use std::collections::HashSet;
use crate::{AttributeDelta, Delta, History, MergeOutcome, Network, NetworkId, NodeId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session, UserId};
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(serde_json::json!(value)),
},
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// The tips as a scan finds them, for checking the maintained set against.
fn scanned_tips(history: &History) -> Vec<Rev> {
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
fn branched_pair() -> (Session, Session) {
let mut a = Session::with_peer(PeerId(1));
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut b = a.clone();
b.document.peer = PeerId(2);
b.document.clock = crate::LamportClock::new(PeerId(2));
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
(a, b)
}
#[test]
fn the_tip_set_follows_pushes_merges_and_sorts() {
let (mut a, b) = branched_pair();
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
a.merge(b.cloned_deltas()).expect("merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history), "after a merge joining two branches");
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
a.commit_op_for_test(set_attribute("after", 3)).expect("edit after the merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
// A reload builds the same indexes from the ordered deltas.
let reloaded = History::from_ordered(a.cloned_deltas());
assert_eq!(reloaded.tips(), a.document.history.tips());
for delta in a.history() {
assert!(reloaded.contains_timestamp(delta.timestamp));
}
}
#[test]
fn history_names_the_resource_hashes_it_carries() {
let hash = ResourceHash::from(b"bytes".as_slice());
let id = ResourceId::new();
let mut session = Session::with_peer(PeerId(1));
session
.commit_op_for_test(RegistryDelta::AddResource {
id,
entry: ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN),
})
.expect("add");
assert!(session.document.history.resource_hashes().contains(&hash));
let entry = session.retired_registry().resources[&id].clone();
session.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot: entry }).expect("remove");
assert!(session.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
}
/// A retirement from the host chains off the guest's last delta, so it is placed without a sort and
/// without walking ancestry, and the result is exactly what the sort would have produced.
#[test]
fn a_chain_off_the_last_delta_fast_forwards_without_sorting() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut guest = host.clone();
guest.document.peer = PeerId(2);
host.commit_op_for_test(set_attribute("x", 1)).expect("x");
host.commit_op_for_test(add_network(5)).expect("network");
host.commit_op_for_test(set_attribute("y", 2)).expect("y");
let incoming: Vec<Delta> = host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect();
assert!(guest.document.history.extends_canonically(guest.history_len()), "an empty tail extends trivially");
let outcome = guest.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if Some(rev) == host.head_rev()), "{outcome:?}");
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
let mut sorted = guest.document.history.clone();
sorted.canonical_sort();
assert_eq!(
sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(),
guest.history().map(|delta| delta.id).collect::<Vec<_>>(),
"the appended order was already canonical"
);
assert!(guest.retired_registry().value_equal(host.retired_registry()));
}
#[test]
fn a_batch_off_an_earlier_delta_is_sorted_into_place() {
let (mut a, b) = branched_pair();
let before = a.history_len();
let incoming: Vec<Delta> = b.cloned_deltas().into_iter().filter(|delta| a.delta(delta.id).is_none()).collect();
a.merge(incoming).expect("merge");
assert!(!a.document.history.extends_canonically(before), "b's delta hangs off the base, not off a's last delta");
let mut sorted = a.document.history.clone();
sorted.canonical_sort();
assert_eq!(sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(), a.history().map(|delta| delta.id).collect::<Vec<_>>());
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
}
/// Retirement takes the ops under the cutoff whatever order the log applied them in: every op commutes,
/// so the snapshot folds to the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's op stamped late sits first in the log, ahead of an op stamped earlier: the log is in
// arrival order, and stamps are the authors' clocks, not the arrival order.
let late = crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let own = crate::HotOp {
op: set_attribute("x", 1),
timestamp: crate::TimeStamp { counter: 20, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A transaction closes with a marker its author stages, and only closed transactions retire: an author's
/// ops past its last marker stay hot however old they are, while a later transaction from someone else
/// retires around them.
#[test]
fn only_closed_transactions_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),
};
assert!(host.end_transaction().expect("nothing to close").is_empty(), "no op of this peer is open");
// The guest opens a transaction and leaves it open, stamped earlier than everything the host does.
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_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_transaction().expect("close").pop().expect("the host's transaction was open");
assert!(matches!(marker.op, RegistryDelta::EndTransaction));
assert!(host.end_transaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1, "the guest's open transaction 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_transaction(&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 transaction is one interaction");
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 transaction retires after the host's although it is stamped before it.
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert_eq!(closed[0].author, PeerId(2));
host.retire_transaction(&closed[0]).expect("retire");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
assert!(host.document.history.extends_canonically(0), "retirement order is the parent chain, so history stays append-only");
}
/// A transaction 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 a_transaction_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),
};
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker, op 2 still in flight");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert!(!closed[0].contiguous);
host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
let closed = host.closed_transactions();
assert!(closed[0].contiguous);
assert_eq!(closed[0].ops.len(), 3);
}
/// Taking a hot transaction back 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_transaction_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(serde_json::json!(1)),
},
},
timestamp: crate::TimeStamp { counter: 40, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.stage_ops([RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(3),
delta: AttributeDelta {
key: "host".into(),
value: Some(serde_json::json!(1)),
},
}])
.expect("host op");
host.apply_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_transaction().expect("retract").expect("the host's transaction 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 transaction 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_transaction().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,
};
host.replay_hot_op(late).expect("dropped, not an error");
assert_eq!(host.hot_log().len(), 1);
assert!(host.closed_transactions().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
.apply_hot_op(crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
sequence: own[1].sequence,
})
.expect("the host's op reached the guest");
assert!(guest.registry().networks.contains_key(&NetworkId(9)));
let touched = guest.absorb_retracted_marks(host.retracted_marks());
assert!(touched.networks.contains(&NetworkId(9)));
assert!(!guest.registry().networks.contains_key(&NetworkId(9)));
assert!(guest.hot_log().is_empty());
}
/// A step the cursor walked away from is not sent to a peer, and a merge never joins it: the peer gets the
/// branch the cursor is on, and the undone step's effect stays gone.
#[test]
fn an_undone_branch_is_kept_to_itself() {
let mut author = Session::with_peer(PeerId(1));
author.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = author.head_rev().expect("base rev");
author.mark_interaction_end(base);
let mut peer = author.clone();
peer.document.peer = PeerId(2);
author.commit_op_for_test(set_attribute("undone", 1)).expect("the step to undo");
let undone = author.head_rev().expect("rev");
author.mark_interaction_end(undone);
author.undo().expect("undo");
assert_eq!(author.head_rev(), Some(base));
author.commit_op_for_test(set_attribute("kept", 2)).expect("a new branch");
let kept = author.head_rev().expect("rev");
let sent: Vec<Rev> = author.deltas_unknown_to(peer.known_revs()).into_iter().map(|delta| delta.id).collect();
assert_eq!(sent, vec![kept], "only the branch the cursor is on goes out, not the undone step");
assert!(author.delta(undone).is_some(), "the undone step stays in the author's DAG for a history panel");
let incoming: Vec<Delta> = sent.iter().filter_map(|&rev| author.delta(rev).cloned()).collect();
let outcome = peer.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if rev == kept), "{outcome:?}");
assert!(peer.retired_registry().attributes.get("kept").is_some_and(|value| !value.deleted));
assert!(!peer.retired_registry().attributes.contains_key("undone"), "the undone step never reached the peer");
}
/// Undoing a retired step in a session drops it out of the shared line: the later steps are minted again
/// on its parent, the head moves, every peer that follows the move holds the same history and registry,
/// a field a later step wrote keeps that value, and the dropped step comes back on redo as a copy on top.
#[test]
fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
// The guest's step, retired by the host: it writes its own key and one the host writes after it. A
// guest of its own, clock included, so its ops carry its authorship.
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let guest_ops = [set_attribute("guest", 1), set_attribute("shared", 1)];
let hot = guest.stage_ops(guest_ops).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the guest's ops reach the host");
}
let guest_ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&guest_ids).expect("retire");
let undone = *revs.last().expect("the guest's step");
host.mark_interaction_end(undone);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
guest.discard_hot_ops(&guest_ids).expect("discard");
// A later step by the host writes the shared key.
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
let later = host.head_rev().expect("rev");
host.mark_interaction_end(later);
host.stamp_retired_at(&[later], 1_234);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.latest_own_interaction(), Some(undone));
let (moved, touched) = host.drop_interaction(undone).expect("drop");
assert_eq!(moved.from, Some(later));
assert_eq!(moved.copies.len(), 1, "the later step is minted again");
assert_eq!(moved.copies[0].parent, Some(base), "the copy hangs off the dropped step's parent");
assert!(moved.copies[0].is_interaction_end(), "the copy keeps its interaction end");
assert_eq!(moved.copies[0].retired_at(), Some(1_234), "the copy keeps when the original was retired");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("guest").is_none_or(|value| value.deleted), "the dropped step's write is gone");
assert_eq!(
snapshot.attributes.get("shared").map(|value| &value.value),
Some(&serde_json::json!(2)),
"the later step's write stands"
);
assert!(host.delta(undone).is_some() && host.delta(later).is_some(), "the abandoned branch stays for a history panel");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
assert!(
matches!(guest.apply_head_move(&moved), Err(crate::CrdtError::CursorMismatch { .. })),
"a move only applies from where it started"
);
// Redo: the dropped step returns as a copy on top, its older stamp losing the shared key.
let restored = host.restore_interaction(undone).expect("restore");
assert_eq!(restored.len(), 3, "RegisterPeer and the two writes come back");
assert!(host.retired_registry().attributes.get("guest").is_some_and(|value| value.value == serde_json::json!(1)));
assert_eq!(host.retired_registry().attributes.get("shared").map(|value| &value.value), Some(&serde_json::json!(2)));
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge the copies");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
}
/// An author's ops can reach the retirer out of order, the later ones first through a re-announcement
/// after a lapsed link. Coarsening keeps the newest write by stamp, not by position in the log, so the
/// retired delta carries the value every working registry shows.
#[test]
fn a_transaction_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_transaction().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_transactions();
assert_eq!(closed.len(), 1);
host.retire_transaction(&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");
}
/// A transaction 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 a_transaction_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: 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_transaction().expect("close");
raw.end_transaction().expect("close");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
let coarsened = host.retire_transaction(&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()));
}
/// A merge delta joins a line this peer holds as a branch it walked away from. Following it as a plain
/// extension of the line would leave that branch's effects out of the snapshot, so the snapshot is
/// folded from the joined head's whole ancestry instead, and matches the host's.
#[test]
fn following_a_merge_refolds_the_branch_it_joins() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(1)).expect("root");
let mut guest = Session::with_peer(PeerId(2));
let root: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(root, host.head_rev()).expect("follow the root");
// The guest retires a step of its own while apart, then follows the host's line, which leaves it behind.
guest.commit_op_for_test(add_network(2)).expect("own step");
let own: Vec<crate::Delta> = guest.history().filter(|delta| delta.author == PeerId(2)).cloned().collect();
host.commit_op_for_test(add_network(3)).expect("host step");
let line: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(line, host.head_rev()).expect("follow the host");
assert!(!guest.retired_registry().networks.contains_key(&NetworkId(2)), "the guest's own step is off the line");
// The host merges the guest's step and the guest follows to the joined head.
host.merge(own).expect("merge");
let merged: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(merged, host.head_rev()).expect("follow the merge");
let fold = guest.snapshot_from_history().expect("fold");
assert_eq!(guest.retired_registry(), &fold, "the snapshot is the fold of the joined head's ancestry");
assert!(guest.retired_registry().networks.contains_key(&NetworkId(2)), "the branch is back on the line");
assert_eq!(guest.retired_registry(), host.retired_registry());
assert!(guest.registry().value_equal(guest.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes: the next batch registers again, and the newer registration wins.
device.set_user(UserId(20));
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut reversed = Session::with_peer(PeerId(2));
let deltas: Vec<Delta> = device.cloned_deltas().into_iter().rev().collect();
reversed.merge(deltas).expect("merge");
assert_eq!(reversed.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(reversed.user_of(PeerId(2)), Some(UserId(2)), "a peer without a stored identity stands for itself");
}
/// Undo of a retired step in a session names the person's latest step, not the device's: a fresh copy of
/// the document under a new peer id still undoes what its user did from the old one, and nobody else's.
#[test]
fn undo_in_a_session_finds_the_users_step_from_another_peer() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
let mut old_device = Session::load(PeerId(2), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let hot = old_device.stage_ops([set_attribute("mine", 1)]).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the step reaches the host");
}
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&ids).expect("retire");
let step = *revs.last().expect("the step");
host.mark_interaction_end(step);
let new_device = Session::load(PeerId(3), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(new_device.latest_own_interaction(), Some(step), "the same person under a new peer id owns the step");
assert!(new_device.is_mine(PeerId(2)));
let stranger = Session::load(PeerId(4), UserId(8), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(stranger.latest_own_interaction(), None, "someone else has nothing of theirs to undo");
assert!(!stranger.is_mine(PeerId(2)));
}
#[test]
fn moving_the_head_back_leaves_the_line_since_as_a_branch_everyone_follows() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("first");
let first = host.head_rev().expect("rev");
host.mark_interaction_end(first);
host.commit_op_for_test(set_attribute("b", 2)).expect("second");
let second = host.head_rev().expect("rev");
host.mark_interaction_end(second);
host.commit_op_for_test(set_attribute("c", 3)).expect("third");
let third = host.head_rev().expect("rev");
host.mark_interaction_end(third);
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let (moved, touched) = host.move_head_to(first).expect("move");
assert_eq!(moved.from, Some(third));
assert_eq!(moved.head, Some(first));
assert!(moved.copies.is_empty(), "nothing is minted: the line since is left behind");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the second step's write is gone");
assert!(snapshot.attributes.get("c").is_none_or(|value| value.deleted), "the third step's write is gone");
assert_eq!(snapshot.attributes.get("a").map(|value| &value.value), Some(&serde_json::json!(1)));
assert!(host.delta(second).is_some() && host.delta(third).is_some(), "the steps left behind stay as a branch");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), Some(first));
assert!(guest.retired_registry().value_equal(host.retired_registry()), "the follower folds to the same state");
}
+299 -88
View File
@@ -218,9 +218,8 @@ fn merge_fast_forwards_a_prefix_history() {
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
}
/// 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).
/// A write to a network removed on a merged-in branch revives it: the removal keeps the network as a
/// tombstone, and the write is newer than the removal.
#[test]
fn resurrection_reaches_across_a_merge() {
let network_id = NetworkId(7);
@@ -247,15 +246,15 @@ fn resurrection_reaches_across_a_merge() {
// 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).
// A SetNetworkExport on 7 is newer than its removal, so it brings 7 back from its tombstone.
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");
.expect("a write newer than the removal revives the network");
assert!(session_a.retired_registry().networks.contains_key(&network_id));
}
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
@@ -288,7 +287,11 @@ fn first_contribution_registers_the_peer() {
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
assert_eq!(
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
Some(crate::UserId(7)),
"peer mapped to its UserId"
);
// A second, distinct contribution must not re-register.
let mut other_network = tiny_network();
@@ -309,7 +312,7 @@ fn first_contribution_registers_the_peer() {
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
}
/// A SetExport against a removed network must restore the network from history rather than error.
/// A SetExport newer than a network.s removal revives the network from its tombstone rather than error.
#[test]
fn set_export_resurrects_absent_network() {
let mut document = fresh_document(PeerId(1));
@@ -343,7 +346,7 @@ fn set_export_resurrects_absent_network() {
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
}
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
/// An addition into a removed network is evidence the network exists, so it brings the network back.
#[test]
fn add_node_resurrects_owning_network() {
use crate::Node;
@@ -377,9 +380,8 @@ fn add_node_resurrects_owning_network() {
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
}
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
/// the same node) must not error on the second apply. Today the second revert hits
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
/// The same revival arriving twice, from two peers reverting one removal, lands once: the second copy
/// is not newer than what the first wrote.
#[test]
fn concurrent_resurrection_via_revert_is_idempotent() {
use crate::Node;
@@ -400,38 +402,17 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
let revive = RegistryDelta::AddNode {
id: node_id,
node: Node { network: network_id, ..Node::dummy() },
};
let at = document.clock.tick();
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
}
/// History-based resurrection must work when the matching delta is the *root* commit. The history
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
/// it), so a node removed by the very first commit could not be restored.
#[test]
fn restore_node_from_root_commit() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(42);
let node = Node::dummy();
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
document.working_registry.node_instances.insert(node_id, node.clone());
document.retired_snapshot.node_instances.insert(node_id, node.clone());
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
document
.restore_node_from_history(RegistryTarget::Working, node_id)
.expect("resurrection from the root commit should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
let second = document.apply_op_idempotent(revive, at);
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
assert!(document.working_registry.node_instances.contains_key(&node_id));
}
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
@@ -464,6 +445,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 {
crate::attributes::live(attributes).any(|(held, _)| held == key)
}
fn ts(counter: u64, peer: u64) -> TimeStamp {
TimeStamp { counter, peer: PeerId(peer) }
}
@@ -588,7 +574,10 @@ fn remove_source_reverse_restores_prior() {
}
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
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();
@@ -648,7 +637,16 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
fn entry_with_source(priority: f64, peer: u64, body: serde_json::Value, hash: Option<ResourceHash>) -> ResourceEntry {
ResourceEntry {
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
presence: ts(1, peer),
sources: vec![(
source_key(priority, peer),
SourceValue {
source: body,
timestamp: ts(1, peer),
deleted: false,
},
)],
sources_timestamp: TimeStamp::ORIGIN,
hash,
hash_timestamp: ts(1, peer),
}
@@ -699,6 +697,7 @@ fn compute_deltas_diffs_resources_and_round_trips() {
SourceValue {
source: serde_json::json!("url"),
timestamp: ts(1, 1),
deleted: false,
},
);
to.insert(kept, kept_entry);
@@ -724,6 +723,8 @@ fn compute_deltas_diffs_resources_and_round_trips() {
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
let mut document = fresh_document(PeerId(1));
document.working_registry = registry_with_resources(from);
// A clock is past every stamp in the registry it edits, as a session.s persisted clock is.
document.clock.observe(ts(1, 1));
for op in deltas {
let timestamp = document.clock.tick();
document.apply_op(op, timestamp).expect("apply resource delta");
@@ -858,13 +859,18 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
input: crate::NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: input_attributes,
attributes_timestamp: TimeStamp::ORIGIN,
}];
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: implementation.clone(),
implementation_timestamp: Default::default(),
inputs,
attributes,
attributes_timestamp: Default::default(),
network: ROOT_NETWORK,
}
};
@@ -1042,16 +1048,13 @@ fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
// Unretired live work sitting on top, on a key no retired delta touches.
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
assert!(session.registry().attributes.contains_key("hot"), "the hot op must be in the working registry");
assert!(!session.retired_registry().attributes.contains_key("hot"), "and must not be in the snapshot");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must be in the working registry");
assert!(!holds(&session.retired_registry().attributes, "hot"), "and must not be in the snapshot");
session.undo().expect("undo");
assert!(!session.retired_registry().attributes.contains_key("second"), "undo must rewind the retired snapshot");
assert!(
!session.retired_registry().attributes.contains_key("hot"),
"undo promoted an unretired hot op into the retired snapshot"
);
assert!(!holds(&session.retired_registry().attributes, "second"), "undo must rewind the retired snapshot");
assert!(!holds(&session.retired_registry().attributes, "hot"), "undo promoted an unretired hot op into the retired snapshot");
}
/// Redo puts the interaction back on both zones, so the pair does not drift the other way.
@@ -1068,12 +1071,9 @@ fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
session.undo().expect("undo");
session.redo().expect("redo");
assert!(session.retired_registry().attributes.contains_key("second"), "redo must restore the retired delta");
assert!(
!session.retired_registry().attributes.contains_key("hot"),
"redo promoted an unretired hot op into the retired snapshot"
);
assert!(session.registry().attributes.contains_key("hot"), "the hot op must survive an undo/redo round trip");
assert!(holds(&session.retired_registry().attributes, "second"), "redo must restore the retired delta");
assert!(!holds(&session.retired_registry().attributes, "hot"), "redo promoted an unretired hot op into the retired snapshot");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must survive an undo/redo round trip");
}
/// Silent undo emits nothing, so it is only legal while a commit is unpublished. Once peers hold it, a
@@ -1107,20 +1107,19 @@ fn snapshot_from_history_ignores_undone_deltas() {
commit_retired(&mut session, set_document_attribute("second", 2));
session.undo().expect("undo");
assert!(!session.retired_registry().attributes.contains_key("second"), "undo rewound the snapshot");
assert!(!holds(&session.retired_registry().attributes, "second"), "undo rewound the snapshot");
let folded = session.snapshot_from_history().expect("fold");
assert!(folded.attributes.contains_key("first"), "history still holds the kept interaction");
assert!(!folded.attributes.contains_key("second"), "a fold restored an undone delta");
assert!(holds(&folded.attributes, "first"), "history still holds the kept interaction");
assert!(!holds(&folded.attributes, "second"), "a fold restored an undone delta");
}
/// Resurrection takes the last removal of the entity in canonical order. When the deltas first landed
/// that was the latest one so far, but a fold over finished history also sees the removals after the
/// replay position, and one of those can carry the node in a network the replay has not created yet
/// (simulation seed 3588534).
/// A node removed, revived by a reference and removed again with a snapshot placing it elsewhere folds
/// to the same snapshot whether the deltas land one by one or all at once (simulation seed 3588534,
/// which once caught a revival reading the wrong removal).
#[test]
fn snapshot_from_history_resurrects_from_the_replay_position() {
fn snapshot_from_history_reproduces_a_revival_between_two_removals() {
let node_id = NodeId(3);
let first_network = NetworkId(1);
let later_network = NetworkId(3);
@@ -1173,32 +1172,11 @@ fn snapshot_from_history_resurrects_from_the_replay_position() {
},
);
let folded = session.snapshot_from_history().expect("a fold must resurrect from what the replay has seen, not from a later removal");
let folded = session.snapshot_from_history().expect("fold");
assert_eq!(&folded, session.retired_registry(), "the fold must reproduce the snapshot the deltas built as they landed");
}
/// A failed refold leaves the registries on an older history, and the deltas are already absorbed, so
/// re-merging them is a no-op. Without a retry the registries never catch up.
#[test]
fn an_owed_refold_is_retried_by_a_merge_that_absorbs_nothing() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
// Stand in for a refold that failed partway: history moved on, the snapshot did not.
session.document.retired_snapshot = crate::Registry::default();
session.document.refold_owed = true;
let outcome = session.merge(Vec::new()).expect("a merge absorbing nothing still settles the refold");
assert_eq!(outcome, crate::MergeOutcome::NoOp);
assert!(!session.document.refold_owed, "the refold must not stay owed");
assert!(
session.retired_registry().attributes.contains_key("first"),
"the retried refold must bring the snapshot back to its history"
);
}
/// The newtype is `#[serde(transparent)]`, so persisted state and the wire carry a bare number and the
/// field's encoding is unchanged.
#[test]
@@ -1319,3 +1297,236 @@ fn retiring_a_straggler_leaves_the_discarded_value_behind() {
let replayed = host.snapshot_from_history().expect("refold");
assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value");
}
/// Every field of the registry is last-writer-wins on a timestamp, whether an entity exists included, so
/// a set of ops folds to one registry whatever order it lands in. Random sets of structural and field
/// ops, attribute deletions included, over a few ids so additions, removals and writes collide, folded
/// in random orders with an op naming an entity not yet seen retried after the rest.
#[test]
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
use crate::Priority;
use crate::{Implementation, ResourceEntry, SourceKey};
use graphene_resource::ResourceId;
struct Lcg(u64);
impl Lcg {
fn below(&mut self, bound: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % bound
}
}
fn random_op(rng: &mut Lcg, at: TimeStamp) -> RegistryDelta {
let node_id = NodeId(1 + rng.below(4));
let network_id = NetworkId(1 + rng.below(3));
let resource_id = ResourceId::from(1 + rng.below(2));
let input = |rng: &mut Lcg| match rng.below(3) {
0 => crate::NodeInput::Node {
id: NodeId(1 + rng.below(4)),
index: 0,
},
_ => crate::NodeInput::Value {
value: serde_json::json!(rng.below(100)),
exposed: false,
},
};
match rng.below(18) {
0 => RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
1 => RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: Network::default(),
},
2 | 3 => RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
},
// A real snapshot is a fold of ops the remover saw, so two snapshots agreeing on a stamp agree on the
// value; a fabricated one has to be constant for that to hold.
4 => RegistryDelta::RemoveNode {
id: node_id,
snapshot: Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2),
},
5 | 6 => RegistryDelta::ChangeNodeInput {
id: node_id,
index: rng.below(2) as u32,
new_input: input(rng),
},
7 => RegistryDelta::SetNodeInputs {
id: node_id,
inputs: (0..1 + rng.below(3))
.map(|_| InputSlot {
input: input(rng),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
attributes_timestamp: TimeStamp::ORIGIN,
})
.collect(),
},
8 => RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: ["name", "lock"][rng.below(2) as usize].into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
15 => RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: rng.below(2) as u32,
delta: crate::AttributeDelta {
key: "label".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
16 => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: crate::AttributeDelta {
key: "name".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
9 => RegistryDelta::SetNodeImplementation {
id: node_id,
implementation: match rng.below(2) {
0 => Implementation::Network(network_id),
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
},
},
10 => RegistryDelta::SetNetworkExport {
id: network_id,
index: rng.below(2) as u32,
export: match rng.below(2) {
0 => None,
_ => Some(input(rng)),
},
},
11 => RegistryDelta::AddResource {
id: resource_id,
entry: ResourceEntry::default(),
},
12 => RegistryDelta::RemoveResource {
id: resource_id,
snapshot: ResourceEntry::default(),
},
13 => RegistryDelta::SetResourceHash {
id: resource_id,
hash: Some(graphene_resource::ResourceHash::from([rng.below(2) as u8; 32])),
},
_ => RegistryDelta::AddSource {
id: resource_id,
key: SourceKey {
priority: Priority::new(rng.below(2) as f64).expect("finite"),
peer: at.peer,
},
source: serde_json::json!(rng.below(100)),
},
}
}
/// Folds the ops in the order given, retrying the ones that name an entity not yet seen until no
/// retry lands, and returns the working registry.
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
let mut document = fresh_document(PeerId(9));
let mut pending: Vec<&(RegistryDelta, TimeStamp)> = ops.iter().collect();
loop {
let before = pending.len();
pending.retain(|(op, at)| document.apply_op_idempotent(op.clone(), *at).is_err());
if pending.is_empty() || pending.len() == before {
return document.working_registry;
}
}
}
for seed in 0..300u64 {
let mut rng = Lcg(seed);
let ops: Vec<(RegistryDelta, TimeStamp)> = (0..8 + rng.below(24))
.map(|i| {
let at = TimeStamp {
counter: 1 + i,
peer: PeerId(1 + rng.below(3)),
};
(random_op(&mut rng, at), at)
})
.collect();
let reference = fold(&ops);
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 folded = fold(&shuffled);
assert_eq!(
folded,
reference,
"seed {seed}: the ops {:?} folded differently in the order {:?}",
ops.iter().map(|(_, at)| at.counter).collect::<Vec<_>>(),
shuffled.iter().map(|(_, at)| at.counter).collect::<Vec<_>>()
);
}
}
}
/// A removal's snapshot is a copy of the node, stamped exactly as the addition stamped it. Folding it in
/// must keep what the addition wrote: an entry stamped at a map's floor was written by the same op that
/// set the floor, not before it. Caught in the editor as a revived node missing `reflection_metadata`.
#[test]
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
use crate::{AttributesRead, AttributesWrite};
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(4);
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
node.attributes.set("ui::name", serde_json::json!("Layer"), TimeStamp::ORIGIN);
node.inputs[0].attributes.set("reflection_metadata", serde_json::json!("meta"), TimeStamp::ORIGIN);
commit_op(
&mut document,
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
);
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
let added = document.working_registry.node_instances[&node_id].clone();
// A removal and a concurrent, newer write to the node: the write revives it from the tombstone.
let removed_at = document.clock.tick();
document
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added.clone() }, removed_at)
.expect("removal");
let written_at = document.clock.tick();
document
.apply_op_idempotent(
RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: "ui::lock".into(),
value: Some(serde_json::json!(true)),
},
},
written_at,
)
.expect("write");
let revived = &document.working_registry.node_instances[&node_id];
assert_eq!(
revived.attributes.get_typed::<String>("ui::name").as_deref(),
Some("Layer"),
"the node attribute the addition wrote survives"
);
assert_eq!(
revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(),
Some("meta"),
"the slot attribute the addition wrote survives"
);
// The same snapshot folding into the live node, from a removal too old to land, changes nothing.
let mut untouched = document.clone();
untouched
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added }, removed_at)
.expect("a replayed removal");
assert_eq!(untouched.working_registry, document.working_registry);
}
@@ -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 on its own must be what the whole-document conversion holds for it, metadata
/// included, since a mirror patched from projections has to match a mirror 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(_))));
}
@@ -758,20 +758,28 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+162 -24
View File
@@ -51,19 +51,10 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// Nodes are grouped by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
let context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -82,7 +73,7 @@ impl Registry {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in &entry.sources {
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
@@ -104,6 +95,155 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, which storage keeps as an attribute so a
/// conversion back lands the node under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).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, the way a whole-document
/// conversion writes them.
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 entities of the registry to their runtime form, for a caller keeping a runtime
/// mirror in step with the registry rather than rebuilding it. Owner relationships 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());
let document_node = convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?;
Ok(ProjectedNode {
network_path,
local_id,
node: document_node,
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 the nodes still in it
// 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
@@ -166,7 +306,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
@@ -174,8 +314,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -232,8 +372,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
})
.collect()
}
@@ -271,8 +410,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
@@ -292,8 +430,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
let input_data: HashMap<String, serde_json::Value> = crate::attributes::live(attributes)
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -335,7 +472,9 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// A reference to a node removed concurrently keeps the id it had, the way the editor holds a
// dangling input; only a node never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -346,9 +485,8 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: RuntimeNodeId(local_id),
node_id: runtime_node_id(*node_id, referenced),
output_index: *output_index as usize,
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Which entities a run of ops named, for a runtime mirror of the registry to bring back into line
//! without being rebuilt from the whole registry.
//!
//! The set is over-approximate on purpose: an op is recorded whether or not it changed anything, so a
//! late-writer-wins loser, an idempotent replay and a failed apply all land here. What the op did to the
//! registry is settled by comparing the entity's stored and mirrored forms afterwards, which is cheaper
//! than having every apply arm report its outcome and stays correct when an op resurrects 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
/// resurrect 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::EndTransaction | 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(),
attributes_timestamp: crate::TimeStamp::ORIGIN,
});
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)]));
}
}
+21
View File
@@ -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
+124
View File
@@ -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).await
}
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();
}
}
+34
View File
@@ -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
+19
View File
@@ -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";
+175
View File
@@ -0,0 +1,175 @@
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
//! queue until `step` delivers it, so interleavings across peers are driven by the seed 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, leaving every other peer's queues untouched. Random
/// stepping cannot target a receiver, so this is how a test puts 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 only knows the peers whose connect events it has polled, so it
/// can't send to a peer before it had the chance to greet 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
}
}
+161
View File
@@ -0,0 +1,161 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, 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,
/// Connected to the document's room without knowing yet whether a host is there: a host's hello makes
/// this peer a guest, and a room with no host makes it the host after a grace period.
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 that produced it 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 new connection. `epoch` and `seq` anchor the receiver's counter for this
/// sender, since broadcasts made before the connection 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),
/// A guest asks the host to undo (`restore: false`) or redo (`restore: true`) one of its retired
/// interactions, named by its last delta. The host answers the room with a `HeadMove` or new deltas.
UndoRequest {
rev: Rev,
restore: bool,
},
/// A guest asks the host to move the shared head to `rev`, an ancestor of it, 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>,
},
/// Who the sender is, for display. Sent to a peer after the hello and to everyone when it changes; the
/// newest wins. Presence like this is never history, so it stays outside the causal broadcast.
Profile {
name: String,
},
/// Where the sender's pointer is, `None` when it left the viewport. Sent at most once a frame and identified
/// by the link it arrives on, so it carries nothing but the position and the space it is in.
Cursor {
position: Option<CursorPosition>,
},
/// A peer's statements about the history, users and their names among it. Outside the causal order: the
/// record merges the same whatever order it arrives in.
Metadata(HistoryMetadata),
}
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
/// delivery vector at snapshot time, which the guest adopts 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 the history being handed over already covers, so the requester can recognize one
/// it is holding rather than re-entering it as live work.
pub retired: RetiredHotOps,
/// Which hot ops their authors took back, so the requester drops any it still holds.
#[serde(default)]
pub retracted: RetiredHotOps,
/// The document's identity, so a peer that started from an empty document adopts it and can reconnect
/// to the same room by opening its own copy later.
#[serde(default)]
pub document_id: Option<u64>,
/// What the host has on record about the history's users, 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 to have been taken back, re-announced on a membership change the way hot
/// ops are, so a peer that joined while a retraction was in flight still hears of it.
RetractedMarks(RetiredHotOps),
/// 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: where, and in which of the editor's spaces, 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,
/// The icon name of the tool the peer holds, 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 of the network at this path of node ids, from the document network down.
Graph { network: Vec<u64> },
}
File diff suppressed because it is too large. Load diff
+332
View File
@@ -0,0 +1,332 @@
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 a receiver finds
/// the packet boundary without a length prefix.
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
// leave no trace on the wire rather than arriving empty.
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 reliable and ordered per peer, so chunks
/// arrive in the order they were sent and 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, or `None` while more are still to come.
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 ever 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. A hidden browser tab gets about one frame a second, which made a
/// host answer each step of a join a second late while the data channel itself delivered on time.
#[derive(Clone, Debug)]
pub struct Incoming {
inbox: Arc<Mutex<Inbox>>,
}
impl Incoming {
/// Resolves to `true` once a packet is waiting, and to `false` once the room's loop has ended and
/// nothing more can arrive, so the caller knows not to wait again.
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. Packets are split into `[flag][bytes]` chunks; the reliable
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
/// 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 as they happen and wake whoever waits on it. The forwarder ends with
// the socket loop, which drops its senders when it returns; 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 {
// A send only fails once the socket loop has ended, which the loop's own 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,
/// so a poll driven by it runs on packets rather than on frames.
#[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 whatever packets come back 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 at all, so it needs a frame of its own or it would
/// leave 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()]);
}
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
/// splits, and both rebuild byte for byte.
#[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 would be
/// 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 that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
/// the next peer to reuse that id sends.
#[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);
}
}
+199
View File
@@ -0,0 +1,199 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, 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 identity of the document this target holds, if it has one; a session token is derived from it.
fn document_id(&self) -> Option<u64> {
None
}
/// Take on the host's document identity after a full sync, so this copy is the same document from now on.
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;
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
/// Highest hot-op counter retired per author.
fn retired_marks(&self) -> RetiredHotOps;
/// Which hot ops were taken back by their authors. See [`Session::retracted_marks`].
fn retracted_marks(&self) -> RetiredHotOps;
/// Take on a peer's retirement marks, dropping any hot op they show as already retired.
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// Take on a peer's retractions, dropping what they cover from the hot log.
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// What people state about the history, users and their names among it, kept beside it and merged
/// last-writer-wins. Empty for a target that keeps none.
fn metadata(&self) -> HistoryMetadata {
HistoryMetadata::default()
}
/// Take on a peer's statements about the history. Returns whether any of them 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: a buffered op may already be reflected by the sync.
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
/// them as later ops fill the gaps.
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
/// Take the host's deltas on and follow its head, `head` being where the host is after them (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, and where its line diverged from this one, join the two heads
/// with a merge delta rather than follow it. Returns what the room has yet to see, the deltas absorbed
/// and the merge, for the host to broadcast so every guest follows to the joined head.
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 can do it once for a batch rather than once per packet.
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(&self, known: &[Rev]) -> Vec<Delta> {
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
// Kept across the replace: a sequence this peer already spent must not come round again, or an
// op of its own would be taken for one already retired.
let spent = self.next_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 the broadcast that carried them is consumed by
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
// so it is handed back to be retried rather than dropped.
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) -> RetiredHotOps {
Session::retired_marks(self).clone()
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retired_marks(self, remote)?;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
Session::retracted_marks(self).clone()
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retracted_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)
}
}
+103
View File
@@ -0,0 +1,103 @@
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: the editor's join field, the CLI, a URL scheme.
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 one document shares: derived from the document's id, so a copy edited
/// apart reconnects to the same room as the others by opening the same file, with no link to pass
/// around. Document ids are random 64-bit values, so the room is no more guessable than the id; the
/// mixing only spreads the id 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;
/// Every copy of a document derives the same token, and different documents different ones.
#[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));
}
}
+23
View File
@@ -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 acknowledgements and buffering.
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
View File
@@ -19,6 +19,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
+3
View File
@@ -255,6 +255,7 @@ impl Dispatcher {
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,
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,
@@ -269,6 +270,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.properties_panel_open = layout.is_panel_present(PanelType::Properties);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
@@ -5,7 +5,7 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
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};
@@ -150,6 +150,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,
},
@@ -200,6 +204,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>,
@@ -17,6 +17,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))]
@@ -5,13 +5,46 @@ 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 that covers the canvas, the node graph say: only the position is recorded, for
/// presence and the like, and no tool hears of it.
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,
},
}
@@ -66,6 +66,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.translate_mouse_event(pointer_state, true, responses);
}
InputPreprocessorMessage::PointerHover { editor_mouse_state } => {
self.mouse.position = editor_mouse_state.to_pointer_state(viewport).position;
}
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
@@ -70,6 +70,8 @@ define_layout_target!(
NodeGraphControlBar,
/// The body of the Properties panel containing many collapsable sections.
PropertiesPanel,
/// 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.
@@ -20,6 +20,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 properties_panel_open: bool,
pub focus_document: bool,
@@ -679,6 +681,16 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Session")
.label("Session")
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("History")
.label("History")
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
.disabled(self.focus_document),
],
])
.widget_instance(),
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry};
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 meanwhile.
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();
@@ -112,9 +132,128 @@ impl DocumentHistory {
self.needs_whole_document_stage = true;
}
/// 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 transaction at an undo-step boundary (a new `StartTransaction`), so the
/// per-`CommitTransaction` staging since the last boundary is one unit for retirement and undo, aligned
/// with the legacy step. Retirement itself follows the working copy's policy. No-op while unmounted.
pub fn end_storage_transaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.end_transaction() {
log::error!("Closing the storage transaction failed: {error}");
}
}
/// Undo the latest storage transaction while it is still hot by taking it back, so it leaves every hot
/// log and never becomes a history step. `false` when the step already retired. No-op while unmounted.
pub fn retract_storage_transaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
let storage = self.storage.as_mut()?;
match storage.retract_transaction() {
Ok(retracted) => retracted,
Err(error) => {
log::error!("Taking the storage transaction back failed: {error}");
None
}
}
}
/// Stage ops a retraction took back, as a fresh transaction: the redo of a step taken back. What they
/// name lands in the remote changes, for the interface to follow.
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, so garbage collection keeps them for a redo:
/// once taken back, nothing in the registry or history refers to them any more.
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 is one storage undid on its own, taken back or dropped, so the caller can
/// decide how to redo before it moves the legacy stacks.
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 transaction and retire every closed one into durable Gdd history, so the
/// interaction being undone is in history. Called before undo/redo and after the first commit of a
/// newly mounted document. 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() {
@@ -124,8 +263,8 @@ 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
/// transaction by [`end_storage_transaction`](Self::end_storage_transaction) at undo-step boundaries.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
@@ -135,8 +274,20 @@ impl DocumentHistory {
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
if !self.stage_graph(deltas, interface, registry, byte_store) {
return;
}
self.persist_view_state(interface, view_settings, legacy_document);
}
/// The graph half of [`stage_snapshot`](Self::stage_snapshot), without the view state. A session
/// does this every frame, so a peer sees each movement of a drag as its own hot op rather than
/// whatever the autosave timer happened to catch; retirement coarsens them later. Returns whether the
/// working copy is mounted and 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),
@@ -154,14 +305,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, legacy_document);
}
/// Converts the whole document and stages the difference from what the working copy holds.
@@ -246,15 +396,65 @@ 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` (logged) 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 are already in the byte store from an earlier
/// session, so it is never requested from a peer and has to be decoded from what is on hand.
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 (images, 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`
@@ -54,6 +54,18 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
/// From the History panel: move the shared head to an earlier interaction, the steps since staying as a branch.
HistoryMoveHead {
rev: document_graph_storage::Rev,
},
/// From the History panel: drop one retired interaction out of the line, the later ones minted again on its parent.
HistoryRemoveStep {
rev: document_graph_storage::Rev,
},
/// From the History panel: mint a dropped or abandoned interaction again on top of the line.
HistoryRestoreStep {
rev: document_graph_storage::Rev,
},
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
@@ -1,4 +1,5 @@
use super::document_diff::diff_networks;
use super::document_history::UndoNote;
use super::node_graph::document_node_definitions;
use super::utility_types::error::EditorError;
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
@@ -23,7 +24,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
@@ -33,8 +34,11 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_graph_storage::Declarations;
/// The document attribute holding the document's name, so a session shares it and a rename reaches every peer.
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::resource::{ResourceId, ResourceStorage};
use graph_craft::application_io::wgpu_available;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
@@ -149,6 +153,11 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// What peers changed in the working registry that the interface does not show yet. Applied once every
/// declaration it needs is cached. Local edits stage meanwhile: they are constructed against the
/// registry rather than diffed from the interface, so nothing here reads as reverting them.
#[serde(skip)]
pub(crate) pending_remote: document_format::network::RemoteChanges,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -200,6 +209,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
pending_remote: Default::default(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -409,6 +419,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::HistoryMoveHead { rev } => self.apply_history_action(|history| history.move_head_to(rev), responses),
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(|history| history.drop_step(rev), responses),
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(|history| history.redo_retired_step(rev), responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -943,6 +956,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.path = None;
self.set_save_state(false);
self.set_auto_save_state(false);
self.stage_name_attribute();
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
@@ -1349,7 +1363,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => {
self.retire_storage_interaction();
self.end_storage_transaction();
self.network_interface.start_transaction();
self.history.push_undo(self.network_interface.clone());
@@ -1809,7 +1823,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
impl DocumentMessageHandler {
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
pub fn from_storage(
interface: NodeNetworkInterface,
storage: document_format::GddV1,
declarations: Declarations,
byte_store: Arc<dyn ResourceStorage>,
name: String,
path: Option<std::path::PathBuf>,
) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -1818,11 +1839,7 @@ impl DocumentMessageHandler {
};
document.apply_stored_document_settings(storage.view_settings());
match storage.registry().to_resource_registry() {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(storage, declarations);
document.set_storage(storage, declarations, byte_store);
document
}
@@ -2009,6 +2026,51 @@ impl DocumentMessageHandler {
/// Path to the subnetwork that the user's selection is currently scoped to.
/// Empty when the selection lives in the root document network.
/// The network the node graph shows, from the document network down.
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
&self.breadcrumb_network_path
}
/// Write the document's name into its registry as a document attribute, so peers in a session see it and a
/// rename reaches them; a no-op without a working copy or when the registry already holds this name.
pub fn stage_name_attribute(&mut self) {
let name = self.name.clone();
let Some(gdd) = self.storage_mut() else { return };
if gdd
.registry()
.attributes
.get(DOCUMENT_NAME_ATTRIBUTE)
.is_some_and(|value| !value.deleted && value.value.as_str() == Some(name.as_str()))
{
return;
}
let delta = document_graph_storage::AttributeDelta {
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
value: Some(serde_json::Value::String(name)),
};
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
log::error!("Staging the document name failed: {error}");
}
}
/// Take the name the registry holds, after peers changed it. Returns whether the name changed.
pub fn adopt_name_from_storage(&mut self) -> bool {
let Some(name) = self
.storage()
.and_then(|gdd| gdd.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE))
.filter(|value| !value.deleted)
.and_then(|value| value.value.as_str())
.map(str::to_string)
else {
return false;
};
if name == self.name {
return false;
}
self.name = name;
true
}
pub fn selection_network_path(&self) -> &[NodeId] {
&self.selection_network_path
}
@@ -2024,8 +2086,15 @@ impl DocumentMessageHandler {
}
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
storage.set_byte_store(byte_store);
self.history.set_storage(storage, declarations);
self.refresh_resource_registry();
}
/// Close the open storage transaction at an undo-step boundary.
pub(crate) fn end_storage_transaction(&mut self) {
self.history.end_storage_transaction();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2054,7 +2123,9 @@ impl DocumentMessageHandler {
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
// The interface is behind the registry by what peers changed, so the two are only expected to
// agree once that is applied.
if validate && self.pending_remote.is_empty() {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
@@ -2119,6 +2190,103 @@ impl DocumentMessageHandler {
}
}
/// Rebuild the runtime resource registry from storage, which holds each resource's id, content hash
/// and sources. The preprocessor resolves a node's `Resource` input through it, so an interface
/// swapped in from storage needs it refreshed alongside. Keeps the current registry on failure.
fn refresh_resource_registry(&mut self) {
let Some(storage) = self.history.storage() else { return };
match storage.registry().to_resource_registry() {
Ok(resource_registry) => self.resources.registry = resource_registry,
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
}
}
/// Stages what the interface recorded since the last drain, so a session sends each movement in the
/// frame it was made rather than at the next commit or autosave. Nothing else a commit does is done here.
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
let deltas = self.network_interface.take_deltas();
if deltas.is_empty() {
return;
}
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
}
/// Brings the interface into line with what peers changed in the registry. Returns whether nothing is
/// left pending: a declaration still on its way keeps the changes for a later call.
///
/// The touched entities are reconciled in place. Only a registry rederived wholesale, or a reconcile
/// that fails for some other reason, costs a rebuild of the whole interface.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
let changes = std::mem::take(&mut self.pending_remote);
if changes.is_empty() {
return true;
}
if !changes.rebuilt
&& let Some(gdd) = self.history.storage()
{
let peer = gdd.session().peer();
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
Ok(reconciled) => {
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
return true;
}
Err(ReconcileError::DeclarationMissing(id)) => {
log::debug!("Remote changes wait for declaration {id}");
self.pending_remote = changes;
return false;
}
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
}
}
if let Some(rebuilt) = self.history.rebuild_interface() {
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
}
true
}
/// What a rebuild does for the whole interface, for the networks a reconcile changed: drops what the
/// changed nodes feed and re-derives the layer structure.
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
for path in &reconciled.networks {
if self.network_interface.document_network().nested_network(path).is_none() {
continue;
}
self.network_interface.unload_stack_dependents(path);
self.network_interface.unload_import_export_ports(path);
self.network_interface.unload_modify_import_export(path);
self.network_interface.unload_all_nodes_bounding_box(path);
self.network_interface.unload_outward_wires(path);
self.network_interface.unload_all_nodes_click_targets(path);
}
self.network_interface.load_structure();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
if resources_changed {
self.refresh_resource_registry();
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
pub(crate) fn cache_declaration_bytes(&mut self, hash: graph_craft::application_io::resource::ResourceHash, bytes: &[u8]) {
self.history.cache_declaration_bytes(hash, bytes);
}
/// Declaration resources the working copy names whose bytes are on hand but not yet decoded.
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<graph_craft::application_io::resource::ResourceHash> {
self.history.undecoded_declaration_hashes()
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
@@ -2130,6 +2298,11 @@ impl DocumentMessageHandler {
}
self.network_interface = rebuilt;
self.pending_remote = Default::default();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
self.refresh_resource_registry();
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
@@ -2432,16 +2605,80 @@ impl DocumentMessageHandler {
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// A step still hot is taken back and never becomes history. The legacy snapshot is not installed: it
// predates whatever peers wrote in the meantime, so the interface keeps what it holds and follows the
// registry on just the entities the step named. Only a retired step moves the cursor.
if self.history.has_undo_step()
&& let Some(ops) = self.history.retract_storage_transaction()
{
if let Some(snapshot) = self.history.pop_undo() {
self.history.push_redo(snapshot);
}
self.history.note_undo(UndoNote::Retracted(ops));
self.follow_storage_changes(responses);
return;
}
// In a session a retired step is public: it is dropped out of the shared line, by the retirer or on
// request, and the room follows the head. Nothing else in a session may install a legacy snapshot.
if self.is_in_session() {
if self.history.has_undo_step()
&& let Some(rev) = self.history.undo_retired_step()
{
if let Some(snapshot) = self.history.pop_undo() {
self.history.push_redo(snapshot);
}
self.history.note_undo(UndoNote::Dropped(rev));
self.follow_storage_changes(responses);
}
return;
}
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
} else {
false
};
if legacy_applied {
self.history.note_undo(UndoNote::Cursor);
}
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
}
/// An action from the History panel: storage performs it and records what it named, the interface follows on
/// just those entities, and the legacy snapshots go since they describe states off the line the head is on now.
fn apply_history_action(&mut self, action: impl FnOnce(&mut super::document_history::DocumentHistory), responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
responses.add(EventMessage::ToolAbort);
self.history.retire_storage_interaction();
action(&mut self.history);
self.history.clear_legacy();
self.follow_storage_changes(responses);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
/// Bring the interface into line with what storage just changed under it, a step taken back or staged
/// again, by reconciling the entities those ops named, the way remote changes are applied. Anything a
/// peer wrote meanwhile stays as the interface holds it.
fn follow_storage_changes(&mut self, responses: &mut VecDeque<Message>) {
if let Some(gdd) = self.history.storage_mut() {
let changes = gdd.take_remote_changes();
self.pending_remote.extend(changes);
}
self.apply_remote_changes(responses);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
}
fn is_in_session(&self) -> bool {
self.storage().is_some_and(|gdd| gdd.role().is_some())
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
// Set the previous network navigation metadata to the current navigation metadata
@@ -2474,13 +2711,33 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// A step that was taken back is staged afresh from the ops themselves: they are gone from every hot log,
// so redo is a new edit, and the interface follows the registry on what they name, as for the undo.
if self.history.has_redo_step() && self.history.next_redo_is_storage_driven() {
if let Some(snapshot) = self.history.pop_redo() {
self.history.push_undo(snapshot);
}
match self.history.take_undo_note() {
UndoNote::Retracted(ops) => self.history.restage_ops(ops),
UndoNote::Dropped(rev) => self.history.redo_retired_step(rev),
UndoNote::Cursor => {}
}
self.follow_storage_changes(responses);
return;
}
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
} else {
false
};
if legacy_applied {
self.history.take_undo_note();
}
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
}
@@ -3809,6 +4066,11 @@ impl DocumentMessageHandler {
self.resources.collect_garbage(&used_resources);
}
/// Resource bytes only a step taken back on undo still names; see [`DocumentHistory::retracted_resource_hashes`].
pub fn retracted_resource_hashes(&self) -> impl Iterator<Item = graph_craft::application_io::resource::ResourceHash> + '_ {
self.history.retracted_resource_hashes()
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
@@ -208,3 +208,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>,
}
@@ -4,11 +4,13 @@
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
use crate::messages::resource_storage::ResourcesHandle;
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId};
use document_graph_storage::{NodeMetadataSource, PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use std::sync::Arc;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -156,9 +158,9 @@ async fn edit_after_open_commits_cleanly() {
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let source_network = source.network_interface.document_network().clone();
@@ -176,7 +178,7 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(reopened, declarations);
document.set_storage(reopened, declarations, byte_store.storage());
document.finalize_storage_load();
}
@@ -210,7 +212,7 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -263,7 +265,7 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -387,7 +389,7 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -437,7 +439,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let document = editor.active_document();
@@ -674,12 +676,13 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
byte_store
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
@@ -713,8 +716,10 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
// Second autosave: again verifies the round-trip, and the edit, once its transaction is closed and
// retired, must produce new retired history. Retirement follows a policy rather than the commit.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
history_after_edit > history_after_open,
@@ -897,3 +902,42 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
"the transform input should shift down intact, but became {transform:?}"
);
}
/// Undoing a step that is still hot takes it back rather than moving the cursor: the hot log empties,
/// history gains nothing, and the interface follows the registry. Redo stages the same ops afresh.
#[tokio::test]
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_base = editor.active_document().storage().unwrap().session().history().count();
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(64., 64., 192., 192.).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(after_edit, before_edit);
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
let storage = editor.active_document().storage().unwrap();
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
// The step's declaration bytes are named by nothing in storage now, so garbage collection would drop
// them and a redo could not be served to peers; the step held for redo keeps them alive.
assert!(
editor.active_document().retracted_resource_hashes().next().is_some(),
"the retracted step names its declaration resource"
);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
let storage = editor.active_document().storage().unwrap();
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
assert_eq!(storage.session().history().count(), history_base);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::PeerId;
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
@@ -56,7 +56,7 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -14,6 +14,7 @@ mod layout;
mod memo_network;
mod mutations;
mod queries;
mod reconcile;
mod resolved_types;
pub mod storage_metadata;
mod store;
@@ -25,6 +26,7 @@ mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*;
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
/// never made back to whoever sent it. Writing through the store and then dropping what the store
/// recorded keeps the two parallel trees written by one place, which is the property the store
/// exists for, without the echo.
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
let recorded = self.deltas.len();
self.mirror(delta);
@@ -233,6 +233,7 @@ impl EditorDelta {
input: context.resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
attributes_timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
@@ -381,15 +382,35 @@ fn construct_structural_additions(
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id).is_some() {
true => {
match batch.node(id) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes, and a whole-slot assignment would
// otherwise drop the names and descriptions this peer holds for the slots that survive it.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
slot.attributes.extend(
previous
.attributes
.iter()
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
.map(|(key, value)| (key.clone(), value.clone())),
);
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -612,3 +612,249 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
"the node's own metadata should not be restated by a swap that did not write it"
);
}
/// What a peer receives must bring its interface to what the editing peer holds: the recorded deltas are
/// constructed into storage ops, applied to the peer's registry, and the touched entities reconciled
/// into a clone of the interface taken before the edit. Anything the reconcile expresses wrongly, or
/// not at all, shows here as a difference from the edited interface, and the reconciled interface has
/// to convert back to the registry it was reconciled from.
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
// Both interfaces address nodes the way storage does, so they compare directly.
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
// The peer's registry holds what a conversion of the interface holds before the edit.
let mut mirror = editor.active_document().network_interface.clone();
let baseline = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
};
let mut peer = Session::with_peer(PeerId(8));
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
let mut declarations = baseline.declarations;
edit(&mut editor);
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
let constructed = {
let document = editor.active_document();
construct_batch(
&recorded,
&baseline.registry,
&document.resources.registry,
&StorageMetadataView::new(&document.network_interface),
PEER,
)
.expect("construction")
};
declarations.extend(constructed.declarations.decoded);
let mut touched = Touched::default();
for op in &constructed.ops {
touched.record(op);
}
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
let edited = &editor.active_document().network_interface;
assert!(
mirror.document_network() == edited.document_network(),
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
recorded.len(),
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
);
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
assert!(
reconciled_metadata == edited_metadata,
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
recorded.len(),
json_diff(&edited_metadata, &reconciled_metadata, "")
);
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
.expect("the reconciled interface converts")
.registry;
assert!(
peer.registry().value_equal(&converted),
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
compute_deltas(&converted, peer.registry())
);
}
/// The paths at which two JSON values differ, one per line, so a metadata mismatch names the field.
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
use serde_json::Value;
match (expected, actual) {
(Value::Object(expected), Value::Object(actual)) => {
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
keys.into_iter()
.map(|key| match (expected.get(key), actual.get(key)) {
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
(None, None) => String::new(),
})
.collect()
}
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
.iter()
.zip(actual)
.enumerate()
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
.collect(),
_ if expected == actual => String::new(),
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
}
}
#[tokio::test]
async fn reconciling_metadata_edits_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_arity_change_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), template, &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_group_removal_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
panic!("the group should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
})
.await;
}
#[tokio::test]
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let inner = interface
.nested_network(&[group])
.expect("the group's network")
.nodes
.iter()
.find(|(_, node)| node.inputs.iter().any(|input| input.as_value().is_some()))
.map(|(id, _)| *id)
.expect("a node with a value input inside the group");
let index = interface
.nested_network(&[group])
.and_then(|network| network.nodes.get(&inner))
.and_then(|node| node.inputs.iter().position(|input| input.as_value().is_some()))
.expect("the value input");
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
})
.await;
}
/// A touched node the registry holds unchanged, which is what a late-writer-wins loser leaves behind,
/// must not disturb the interface.
#[tokio::test]
async fn reconciling_an_untouched_node_changes_nothing() {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let baseline = convert(&editor);
let declarations = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
.declarations
};
let mut touched = Touched::default();
touched.nodes.extend(baseline.node_instances.keys().copied());
touched.networks.extend(baseline.networks.keys().copied());
let before = editor.active_document().network_interface.clone();
let reconciled = editor
.active_document_mut()
.network_interface
.reconcile_remote(&baseline, &declarations, &touched, PEER)
.expect("reconcile");
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
assert_eq!(editor.active_document().network_interface, before);
}
@@ -0,0 +1,387 @@
//! Brings the interface into line with the working registry for the entities peers touched, so a remote
//! batch costs deltas for what changed rather than a rebuild of the whole interface.
//!
//! Each touched node is projected to its runtime form and compared with what the interface holds. The
//! difference is applied as the same `EditorDelta`s a local edit records, through `apply`, which mirrors
//! without recording, so nothing here is offered back to the peer that sent it. A node held on one side
//! only is added or removed whole. What a comparison cannot express as a field write, a changed
//! implementation or scope injection, replaces the node.
//!
//! The touched set is an over-approximation: a late-writer-wins loser or an op that failed to apply
//! names an entity that did not change, and the comparison finds nothing to emit for it.
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::to_runtime::ConversionError;
use document_graph_storage::{Declarations, NodeId as StorageNodeId, ROOT_NETWORK, Registry, RuntimeProjection, Touched};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::runtime_delta::RuntimeDelta;
use super::storage_metadata::{InterfaceRebuildError, node_metadata_from_projection};
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
#[derive(Debug, thiserror::Error)]
pub enum ReconcileError {
/// A declaration the touched nodes need is not cached yet. Nothing was applied; retry once it lands.
#[error("waiting for proto-node declaration {0}")]
DeclarationMissing(document_graph_storage::ResourceId),
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
NetworkMissing(Vec<NodeId>),
#[error(transparent)]
Conversion(ConversionError),
#[error(transparent)]
Metadata(#[from] InterfaceRebuildError),
}
impl From<ConversionError> for ReconcileError {
fn from(error: ConversionError) -> Self {
match error {
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
other => Self::Conversion(other),
}
}
}
/// What a reconcile changed, for the caller to unload what those changes feed.
#[derive(Debug, Default)]
pub struct Reconciled {
/// The networks a delta was applied in.
pub networks: BTreeSet<Vec<NodeId>>,
}
/// Where the interface holds each node storage knows, keyed by the identity storage addresses it by.
type StorageIndex = HashMap<StorageNodeId, (Vec<NodeId>, NodeId)>;
impl NodeNetworkInterface {
/// Applies to the interface whatever the registry holds differently for the touched entities.
///
/// Can fail part-way through, leaving some of them reconciled. That is safe to retry with the same
/// touched set, since a reconciled node compares equal and emits nothing, which is what the caller
/// does when a declaration is still on its way; on any other error it rebuilds from the whole registry.
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
let projection = registry.runtime_projection(declarations);
let index = self.pin_storage_identities(peer);
// A touched network is reconciled through the node implementing it, whose comparison covers the
// network's exports and metadata. The root has no such node.
let mut ids = touched.nodes.clone();
let mut root = false;
for &network in &touched.networks {
match projection.owner(network) {
Some(owner) => {
ids.insert(owner);
}
None => root |= network == ROOT_NETWORK,
}
}
// A node the runtime cannot reach and the interface does not hold has nothing to reconcile.
let mut items: Vec<(Vec<NodeId>, NodeId, StorageNodeId)> = ids
.into_iter()
.filter_map(|id| {
let (path, local_id) = projection.node_address(id).or_else(|| index.get(&id).cloned())?;
Some((path, local_id, id))
})
.collect();
// A network's path is a prefix of the paths inside it, so this puts each node after the one
// implementing its network, and a nested node finds its network in place.
items.sort();
let mut reconciled = Reconciled::default();
for (path, local_id, id) in items {
self.reconcile_node(&projection, &index, &path, local_id, id, &mut reconciled)?;
}
if root {
let target = projection.network_entry(ROOT_NETWORK)?;
let current_exports = self.document_network().exports.clone();
let current = &self.document_network_metadata().persistent_metadata;
let mut deltas = Vec::new();
export_deltas(&[], &current_exports, &target.exports, &mut deltas);
network_metadata_deltas(
&[],
current.reference.as_deref(),
&current.pinned_node_order,
target.metadata.reference.as_deref(),
&target.metadata.pinned_order,
&mut deltas,
);
self.apply_reconciled(&[], deltas, &mut reconciled);
}
Ok(reconciled)
}
fn reconcile_node(
&mut self,
projection: &RuntimeProjection,
index: &StorageIndex,
path: &[NodeId],
local_id: NodeId,
id: StorageNodeId,
reconciled: &mut Reconciled,
) -> Result<(), ReconcileError> {
// The interface holds the node somewhere else: under another id, or in a network it has since
// left. That copy goes before the one the registry describes is put in place.
if let Some((held_path, held_id)) = index.get(&id)
&& (held_path.as_slice() != path || *held_id != local_id)
&& self.holds_node(held_path, *held_id)
{
self.apply_reconciled(held_path, vec![remove_node(held_path, *held_id)], reconciled);
}
let stored = projection.node_address(id).is_some();
let held = self.holds_node(path, local_id);
match (stored, held) {
(false, false) => {}
(false, true) => self.apply_reconciled(path, vec![remove_node(path, local_id)], reconciled),
(true, false) => {
if !self.holds_network(path) {
return Err(ReconcileError::NetworkMissing(path.to_vec()));
}
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
let nested = matches!(node.implementation, DocumentNodeImplementation::Network(_));
let deltas = vec![
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(node),
}),
EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(metadata),
},
];
self.apply_reconciled(path, deltas, reconciled);
if nested {
reconciled.networks.insert(nested_path(path, local_id));
}
}
(true, true) => {
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
self.diff_node(path, local_id, node, metadata, reconciled);
}
}
Ok(())
}
/// Emits what differs between the node the interface holds at `path` / `local_id` and `target`, which
/// the registry describes. A network node's contents are left to their own reconciliation: only its
/// exports and its network's metadata are compared here.
fn diff_node(&mut self, path: &[NodeId], local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
let Some(current) = self.document_network().nested_network(path).and_then(|network| network.nodes.get(&local_id)) else {
return;
};
let Some(current_metadata) = self
.document_network_metadata()
.nested_metadata(path)
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
.map(|node| &node.persistent_metadata)
else {
return;
};
let mut deltas = Vec::new();
let mut nested_changed = false;
let at = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
network_path: path.to_vec(),
node_id: local_id,
change,
};
// What no field write expresses replaces the node whole, and its metadata with it.
if !same_implementation(&current.implementation, &target.implementation) || current.skip_deduplication != target.skip_deduplication {
nested_changed = matches!(target.implementation, DocumentNodeImplementation::Network(_)) || matches!(current.implementation, DocumentNodeImplementation::Network(_));
deltas.push(EditorDelta::Graph(RuntimeDelta::ReplaceNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(target),
}));
deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(target_metadata),
});
} else {
// The slots first, so the metadata array that indexes them lands on a list of the right length.
if current.inputs.len() != target.inputs.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
network_path: path.to_vec(),
node_id: local_id,
inputs: target.inputs.clone(),
}));
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
} else {
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
if held != wanted {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: path.to_vec(),
node_id: local_id,
input_index,
input: wanted.clone(),
}));
}
}
if current_metadata.input_metadata != target_metadata.input_metadata {
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
}
}
// Export slot writes rename the encapsulating node's outputs as a side effect, so the names are
// restated after them whenever the slot count moved.
let mut restate_output_names = false;
if let (DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) = (&current.implementation, &target.implementation) {
let nested = nested_path(path, local_id);
let before = deltas.len();
export_deltas(&nested, &held.exports, &wanted.exports, &mut deltas);
restate_output_names = held.exports.len() != wanted.exports.len();
let (held_reference, held_order) = current_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
let (wanted_reference, wanted_order) = target_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
network_metadata_deltas(&nested, held_reference, held_order, wanted_reference, wanted_order, &mut deltas);
nested_changed = deltas.len() != before;
}
if current.visible != target.visible {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: path.to_vec(),
node_id: local_id,
visible: target.visible,
}));
}
if current.call_argument != target.call_argument {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
network_path: path.to_vec(),
node_id: local_id,
call_argument: target.call_argument.clone(),
}));
}
if current.context_features != target.context_features {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path: path.to_vec(),
node_id: local_id,
context_features: target.context_features,
}));
}
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(at(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
}
if current_metadata.display_name != target_metadata.display_name {
deltas.push(at(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
}
if current_metadata.locked != target_metadata.locked {
deltas.push(at(NodeMetadataChange::Locked(target_metadata.locked)));
}
if current_metadata.pinned != target_metadata.pinned {
deltas.push(at(NodeMetadataChange::Pinned(target_metadata.pinned)));
}
if restate_output_names || current_metadata.output_names != target_metadata.output_names {
deltas.push(at(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
}
}
if deltas.is_empty() {
return;
}
self.apply_reconciled(path, deltas, reconciled);
if nested_changed {
reconciled.networks.insert(nested_path(path, local_id));
}
}
fn apply_reconciled(&mut self, path: &[NodeId], deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
if deltas.is_empty() {
return;
}
for delta in &deltas {
self.apply(delta);
}
reconciled.networks.insert(path.to_vec());
}
fn holds_node(&self, path: &[NodeId], local_id: NodeId) -> bool {
self.document_network().nested_network(path).is_some_and(|network| network.nodes.contains_key(&local_id))
&& self
.document_network_metadata()
.nested_metadata(path)
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
}
fn holds_network(&self, path: &[NodeId]) -> bool {
self.document_network().nested_network(path).is_some() && self.document_network_metadata().nested_metadata(path).is_some()
}
}
fn remove_node(path: &[NodeId], local_id: NodeId) -> EditorDelta {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: path.to_vec(),
node_id: local_id,
})
}
fn nested_path(path: &[NodeId], local_id: NodeId) -> Vec<NodeId> {
[path, &[local_id]].concat()
}
/// Whether a field-by-field comparison can bring `current` to `target`, which it cannot across a
/// change of what the node computes.
fn same_implementation(current: &DocumentNodeImplementation, target: &DocumentNodeImplementation) -> bool {
match (current, target) {
(DocumentNodeImplementation::ProtoNode(held), DocumentNodeImplementation::ProtoNode(wanted)) => held == wanted,
(DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) => held.scope_injections == wanted.scope_injections,
_ => false,
}
}
/// The slot writes taking `current` to `target`: a write per slot that differs, then a removal at the
/// end for each slot too many, which the mirror applies as removals of that index in turn.
fn export_deltas(network_path: &[NodeId], current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
for (export_index, input) in target.iter().enumerate() {
if current.get(export_index) != Some(input) {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index,
input: Some(input.clone()),
}));
}
}
for _ in target.len()..current.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: target.len(),
input: None,
}));
}
}
fn network_metadata_deltas(network_path: &[NodeId], current_reference: Option<&str>, current_order: &[NodeId], target_reference: Option<&str>, target_order: &[NodeId], deltas: &mut Vec<EditorDelta>) {
if current_reference != target_reference {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::Reference(target_reference.map(str::to_string)),
});
}
if current_order != target_order {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::PinnedOrder(target_order.to_vec()),
});
}
}
@@ -188,6 +188,47 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
/// The runtime node and the persistent metadata for it and everything nested under it, from a
/// single-node projection of the registry. Built through the same entry patching as a whole rebuild, on
/// a tree holding just this node, so a reconciled node matches what a rebuild would hold for it.
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
let document_graph_storage::ProjectedNode {
network_path: prefix,
local_id,
node,
node_entries,
network_entries,
} = projected;
// The entries carry absolute paths; the scratch tree is rooted at the node's own network.
let rebase = |path: Vec<NodeId>| path.get(prefix.len()..).map(<[NodeId]>::to_vec).unwrap_or_default();
let node_entries = node_entries
.into_iter()
.map(|entry| NodeMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let network_entries = network_entries
.into_iter()
.map(|entry| NetworkMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let mut scratch = NodeNetwork::default();
scratch.nodes.insert(local_id, node);
let mut metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&scratch, &mut metadata);
apply_entries_into_tree(&scratch, &mut metadata, node_entries)?;
apply_network_entries_into_tree(&mut metadata, network_entries);
let persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
let node = scratch.nodes.remove(&local_id).expect("inserted above");
Ok((node, persistent))
}
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, document_graph_storage::NetworkId> {
@@ -303,7 +303,6 @@ impl NodeMut<'_> {
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
@@ -315,7 +314,6 @@ impl NodeMut<'_> {
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
@@ -374,7 +372,6 @@ impl NodeMut<'_> {
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
@@ -383,7 +380,6 @@ impl NodeMut<'_> {
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
@@ -329,6 +329,49 @@ impl NodeNetworkInterface {
self.deltas.clear();
}
/// Pins every node to the identity storage addresses it by, returning where each is held.
///
/// A node the interface built from storage is already pinned; one created here is addressed by a
/// hash of its location until now, which is what a conversion derives for it anyway. Pinning changes
/// no document content, so nothing is recorded: the identity is a fact about the node, not an edit.
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (Vec<NodeId>, NodeId)> {
let mut index = HashMap::new();
let mut unpinned = Vec::new();
{
let view = super::storage_metadata::StorageMetadataView::new(self);
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
let mut stack = vec![(Vec::new(), &*self.network_metadata)];
while let Some((path, metadata)) = stack.pop() {
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
let storage_id = match node.persistent_metadata.storage_id {
Some(pinned) => document_graph_storage::NodeId(pinned),
None => {
let derived = resolver.node_id(&path, local_id);
unpinned.push((path.clone(), local_id, derived));
derived
}
};
index.insert(storage_id, (path.clone(), local_id));
if let Some(nested) = &node.persistent_metadata.network_metadata {
stack.push(([path.as_slice(), &[local_id]].concat(), nested));
}
}
}
}
for (path, local_id, storage_id) in unpinned {
if let Some(node) = self
.network_metadata
.get_mut()
.nested_metadata_mut(&path)
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
{
node.persistent_metadata.storage_id = Some(storage_id.0);
}
}
index
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
@@ -52,33 +52,39 @@ async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<
pub(super) async fn build_or_open_working_copy(
path: Option<&std::path::Path>,
peer: document_graph_storage::PeerId,
user: document_graph_storage::UserId,
document_uuid: u64,
version: String,
) -> Result<(GddV1, bool), DocumentFormatError> {
let (container, exists) = build_per_document_container(path).await?;
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
let mut gdd = GddV1::open_in(container, GddV1Layout).await?;
// The person at this device may have changed since the copy was written; the copy follows the preferences.
gdd.set_user(user)?;
gdd
} else {
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
GddV1::create_in(container, GddV1Layout, peer, user, document_uuid, version.clone(), version).await?
};
Ok((gdd, exists))
}
/// `FutureMessage` that opens a `.gdd` archive into a document, delivered via
/// [`PortfolioMessage::GddDocumentLoaded`]. See [`build_document_from_gdd`] for the build itself.
#[allow(clippy::too_many_arguments)]
pub(super) async fn open_gdd_document(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<std::path::PathBuf>,
content: Vec<u8>,
fresh_identity: bool,
store_handle: ResourcesHandle,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id, validate).await;
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id, fresh_identity, validate).await;
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
@@ -90,7 +96,14 @@ pub(super) async fn open_gdd_document(
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
/// Returns `None` only if neither the build nor the legacy fallback worked.
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
async fn build_document_from_gdd(
path: Option<&std::path::Path>,
content: &[u8],
store_handle: &ResourcesHandle,
document_id: DocumentId,
fresh_identity: bool,
validate: bool,
) -> Option<DocumentMessageHandler> {
let (container, _exists) = match build_per_document_container(path).await {
Ok(result) => result,
Err(error) => {
@@ -99,13 +112,17 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
}
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
let mut gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
}
};
// The session room is derived from the manifest's id, so a copy of a distributed file gets its own.
if fresh_identity && let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = crate::application::generate_uuid()) {
log::error!("Opening .gdd for {document_id:?}: failed to give the copy its own id: {error}");
}
// Extract archived resource bytes into the global cache so declarations + runtime resolve.
match gdd.resource_hashes().await {
@@ -164,7 +181,7 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None));
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, store_handle.storage(), String::new(), None));
}
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
@@ -238,6 +238,7 @@ mod tests {
resources: None,
path: None,
is_saved: true,
session: None,
};
handler.record_failure(DocumentId(id), info, "content".to_string());
}
@@ -0,0 +1,26 @@
use crate::messages::prelude::*;
#[impl_message(Message, PortfolioMessage, History)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum HistoryMessage {
/// Send the History panel's content for the active document, whether or not anything changed.
Refresh,
/// Once per frame while the panel is open: send the content again if the history moved since the last send.
Tick,
/// Show or hide the deltas of one interaction, named by the rev that closes it.
Expand { id: String, expanded: bool },
/// Show older interactions than the ones on hand.
LoadMore,
/// Move the head to the interaction: back along the line, or forward again over undone ones.
GoBack { id: String },
/// Drop one interaction out of the line, the later ones staying.
RemoveStep { id: String },
/// Bring an undone or abandoned interaction back.
BringBack { id: String },
/// Show the line of the branch whose tip is `id`, or the head's line again with `None`.
Follow { id: Option<String> },
/// Give the interaction a name of its own, or take it away with an empty one.
Rename { id: String, label: String },
/// Put a tag on the interaction, or take it off.
Tag { id: String, tag: String, on: bool },
}
@@ -0,0 +1,524 @@
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
use crate::messages::portfolio::sync::now_ms;
use crate::messages::prelude::*;
use document_format::GddV1;
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, UserId, rev_attr};
use peer_transport::RemotePeer;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
#[derive(ExtractField)]
pub struct HistoryMessageContext<'a> {
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
pub active_document_id: Option<DocumentId>,
/// Whether the History panel is showing; nothing is computed while it is not.
pub panel_open: bool,
}
/// Feeds the History panel with the active document's history as interactions along a line, sent again
/// whenever it moved, and turns the panel's actions into moves of the document's head.
#[derive(Debug, Default, ExtractField)]
pub struct HistoryMessageHandler {
/// Whether the per-frame tick is subscribed.
ticking: bool,
/// Interactions shown with their deltas, by closing rev.
expanded: HashSet<Rev>,
/// How many interactions of the line to send; grows on request.
limit: usize,
/// The tip of the branch shown instead of the head's line.
following: Option<Rev>,
/// What the last send described, so a frame with no movement sends nothing.
last_sent: Option<u64>,
}
/// Interactions sent at first, and added per request for older ones.
const PAGE: usize = 100;
#[message_handler_data]
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
match message {
HistoryMessage::Refresh => {
if !self.ticking {
self.ticking = true;
responses.add(BroadcastMessage::SubscribeEvent {
on: EventMessage::AnimationFrame,
send: Box::new(HistoryMessage::Tick.into()),
});
}
self.send(&context, responses, true);
}
HistoryMessage::Tick => {
if context.panel_open {
self.send(&context, responses, false);
}
}
HistoryMessage::Expand { id, expanded } => {
if let Some(rev) = parse_rev(&id) {
match expanded {
true => self.expanded.insert(rev),
false => self.expanded.remove(&rev),
};
}
self.send(&context, responses, true);
}
HistoryMessage::LoadMore => {
self.limit = self.limit.max(PAGE) + PAGE;
self.send(&context, responses, true);
}
HistoryMessage::Follow { id } => {
self.following = id.as_deref().and_then(parse_rev);
self.send(&context, responses, true);
}
HistoryMessage::GoBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
let session = gdd.session();
match place(session, rev) {
// Above the head: forward again over the undone interactions, one redo each.
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
// On the head's line: in a session one shared move for everyone; alone, the cursor walks back one
// interaction at a time so the editor's own undo stays in step.
Some(Place::Line(0)) => {}
Some(Place::Line(steps)) => match gdd.role().is_some() {
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
},
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
}
}
HistoryMessage::RemoveStep { id } => {
if let Some(rev) = parse_rev(&id) {
responses.add(DocumentMessage::HistoryRemoveStep { rev });
}
}
HistoryMessage::BringBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(_)) => {}
// Off the line: minted again on top of it.
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
}
}
HistoryMessage::Rename { id, label } => {
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record_rev_attribute(rev, rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
log::warn!("Naming the step failed: {error}");
}
self.send(&context, responses, true);
}
HistoryMessage::Tag { id, tag, on } => {
let tag = tag.trim();
if tag.is_empty() {
return;
}
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record_rev_attribute(rev, &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
log::warn!("Tagging the step failed: {error}");
}
self.send(&context, responses, true);
}
}
}
advertise_actions!(HistoryMessageDiscriminant;);
}
impl HistoryMessageHandler {
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
let Some(gdd) = active_storage(context) else {
if force {
self.last_sent = None;
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
}
return;
};
// A branch whose tip this copy no longer holds is nothing to follow.
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
self.following = None;
}
let limit = self.limit.max(PAGE);
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
if !force && self.last_sent == Some(fingerprint) {
return;
}
self.last_sent = Some(fingerprint);
let state = panel_state(gdd, limit, &self.expanded, self.following);
responses.add(FrontendMessage::UpdateHistoryPanel { state });
}
}
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
}
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
}
fn parse_rev(id: &str) -> Option<Rev> {
id.parse::<u128>().ok().and_then(Rev::new)
}
/// Where an interaction sits relative to the head.
enum Place {
/// On the head's line, this many interactions back; zero is the head itself.
Line(usize),
/// Above the head on the undone line, this many redos forward.
Undone(usize),
}
fn place(session: &Session, rev: Rev) -> Option<Place> {
let head = session.head_rev();
let (kept, _) = line(session, head, None, usize::MAX);
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
return Some(Place::Line(steps));
}
let checkpoint = *session.redo_stack().last()?;
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
let groups = interactions(&undone);
let index = groups.iter().position(|group| group[0].id == rev)?;
Some(Place::Undone(groups.len() - index))
}
/// Everything the panel's content depends on, hashed: cheap to take every frame.
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
let session = gdd.session();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
document_id.hash(&mut hasher);
session.history_len().hash(&mut hasher);
session.head_rev().hash(&mut hasher);
session.redo_stack().hash(&mut hasher);
session.hot_log().len().hash(&mut hasher);
gdd.role().is_some().hash(&mut hasher);
for record in &gdd.metadata().users {
record.user.hash(&mut hasher);
if let Some(name) = gdd.metadata().user_name(record.user) {
name.hash(&mut hasher);
}
}
for remote in gdd.peers() {
remote.user.hash(&mut hasher);
remote.name.hash(&mut hasher);
}
for record in &gdd.metadata().revs {
record.rev.hash(&mut hasher);
for (key, fact) in &record.attributes {
key.hash(&mut hasher);
fact.stamp.hash(&mut hasher);
}
}
limit.hash(&mut hasher);
expanded.len().hash(&mut hasher);
following.hash(&mut hasher);
hasher.finish()
}
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
let session = gdd.session();
let people = People {
session,
metadata: gdd.metadata(),
peers: gdd.peers(),
};
// Where branches leave the lines shown: every delta's children, minus the lines themselves.
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in session.history() {
for parent in delta.all_parents() {
children.entry(parent).or_default().push(delta.id);
}
}
let head = session.head_rev();
let (head_line, _) = line(session, head, None, usize::MAX);
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
// Taken back and not yet redone: from the redo stack's top down to the head, shown above it. Not while
// following a branch, whose line is shown whole instead.
let undone = match (following, session.redo_stack().last()) {
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
_ => Vec::new(),
};
let (shown, more) = match following {
Some(tip) => line(session, Some(tip), None, limit),
None => (
head_line
.iter()
.take_while({
let mut ends = 0;
move |delta| {
if delta.is_interaction_end() {
ends += 1;
}
ends <= limit
}
})
.cloned()
.collect::<Vec<_>>(),
interactions(&head_line).len() > limit,
),
};
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
let view = View {
children: &children,
on_line: &on_line,
head_line: &head_line_revs,
head,
people: &people,
expanded,
session,
metadata: gdd.metadata(),
};
let mut rows = Vec::new();
for group in interactions(&undone) {
rows.push(view.row(&group, true));
}
for group in interactions(&shown) {
rows.push(view.row(&group, false));
}
// What has not entered history yet: every author's open transaction first, then each closed transaction
// waiting for the retirer as a step of its own, the newest first like the rows below.
let hot_log = session.hot_log();
let closed = session.closed_transactions();
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|transaction| transaction.ops.iter().copied()).collect();
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
Some((_, ops)) => ops.push(&hot_op.op),
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
}
}
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
for transaction in closed.iter().rev() {
let ids: HashSet<HotOpId> = transaction.ops.iter().copied().collect();
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
progress.push(progress_row(&people, transaction.author, &ops, false));
}
HistoryPanelState {
rows,
progress,
more,
following: following.map(|tip| tip.to_string()),
session: gdd.role().is_some(),
}
}
/// The deltas from `from` back along first parents to `until` exclusive, or the root, newest first.
/// Stops after `limit` interaction ends and says so.
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
let mut deltas = Vec::new();
let mut ends = 0;
let mut current = from;
while let Some(rev) = current
&& Some(rev) != until
{
let Some(delta) = session.delta(rev) else { break };
if delta.is_interaction_end() {
if ends == limit {
return (deltas, true);
}
ends += 1;
}
deltas.push(delta.clone());
current = delta.parent;
}
(deltas, false)
}
/// Group a line, newest first, into interactions: each starts at an interaction end and runs back to the
/// delta after the previous end. A line whose newest delta is not an end, work retired mid-interaction,
/// opens a group of its own.
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
let mut groups: Vec<Vec<&Delta>> = Vec::new();
for delta in deltas {
match groups.last_mut() {
Some(group) if !delta.is_interaction_end() => group.push(delta),
_ => groups.push(vec![delta]),
}
}
groups
}
/// What one send of the panel is computed against.
struct View<'a> {
children: &'a HashMap<Rev, Vec<Rev>>,
on_line: &'a HashSet<Rev>,
head_line: &'a HashSet<Rev>,
head: Option<Rev>,
people: &'a People<'a>,
expanded: &'a HashSet<Rev>,
session: &'a Session,
metadata: &'a HistoryMetadata,
}
impl View<'_> {
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
let closing = group[0];
let person = self.people.person(closing.author);
let branches = group
.iter()
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
.filter(|child| !self.on_line.contains(child))
.map(|&child| self.branch(child))
.collect();
let is_expanded = self.expanded.contains(&closing.id);
let details = match is_expanded {
true => group
.iter()
.map(|delta| {
let author = self.people.person(delta.author);
HistoryDeltaRow {
id: delta.id.to_string(),
label: describe(&delta.kind),
author: author.name,
color: author.color,
time: delta.retired_at().map(|ms| ms as f64),
}
})
.collect(),
false => Vec::new(),
};
let given = self.metadata.rev_label(closing.id);
HistoryRow {
id: closing.id.to_string(),
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
named: given.is_some(),
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
deltas: group.len(),
branches,
undone,
abandoned: !undone && !self.head_line.contains(&closing.id),
head: Some(closing.id) == self.head,
expanded: is_expanded,
details,
}
}
/// The branch that starts at `first`: its tip, following first children, and what its newest interaction did.
fn branch(&self, first: Rev) -> HistoryBranch {
let mut tip = first;
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
tip = next;
}
let (newest, _) = line(self.session, Some(tip), None, 1);
let label = self
.metadata
.rev_label(tip)
.map(str::to_string)
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
HistoryBranch { id: tip.to_string(), label }
}
}
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
let person = people.person(peer);
HistoryProgressRow {
label: summarize(ops.iter().copied()),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
ops: ops.len(),
open,
}
}
/// One line for a run of changes: the kinds among them, the most frequent first.
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
let kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
let mut counts: Vec<(String, usize)> = Vec::new();
for kind in &kinds {
// A registration or a marker says nothing about the document; it labels a run only when it is all there is.
if matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::EndTransaction) && kinds.len() > 1 {
continue;
}
let label = describe(kind);
match counts.iter_mut().find(|(known, _)| *known == label) {
Some((_, count)) => *count += 1,
None => counts.push((label, 1)),
}
}
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
let mut parts: Vec<String> = counts
.iter()
.take(2)
.map(|(label, count)| match count {
1 => label.clone(),
count => format!("{label} ×{count}"),
})
.collect();
if counts.len() > 2 {
parts.push(format!("{} more", counts.len() - 2));
}
parts.join(", ")
}
fn describe(kind: &RegistryDelta) -> String {
match kind {
RegistryDelta::AddNode { .. } => "Added a node".into(),
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
RegistryDelta::AddResource { .. } => "Added a resource".into(),
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
RegistryDelta::EndTransaction => "Closed a step".into(),
RegistryDelta::Other(_) => "Changed something".into(),
}
}
/// How authors are named and coloured: the document's record first, then what the room announced, then
/// the stand-in, all by user id so a person is one person across their peers.
struct People<'a> {
session: &'a Session,
metadata: &'a HistoryMetadata,
peers: Vec<RemotePeer>,
}
struct Person {
name: String,
anonymous: bool,
mine: bool,
color: String,
}
impl People<'_> {
fn person(&self, peer: PeerId) -> Person {
// A peer that never registered, from a copy older than registrations, is its own user by convention.
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
let recorded = self.metadata.user_name(user).map(str::to_string);
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
let (name, anonymous) = match recorded.or_else(announced) {
Some(name) => (name, false),
None => (anonymous_name(user), true),
};
Person {
name,
anonymous,
mine: self.session.is_mine(peer),
color: user_color(user),
}
}
}
@@ -0,0 +1,8 @@
mod history_message;
mod history_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
#[doc(inline)]
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
@@ -0,0 +1,84 @@
//! What the History panel shows, as the frontend receives it.
/// The panel's content: a line as interactions, newest first. The head's line with the undone ones above it,
/// or a branch's line while one is followed.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryPanelState {
pub rows: Vec<HistoryRow>,
/// Work under way in the room that has not entered history yet, one row per person.
pub progress: Vec<HistoryProgressRow>,
/// Whether older interactions exist beyond the rows sent.
pub more: bool,
/// The tip of the branch being followed instead of the head's line, if any.
pub following: Option<String>,
/// Whether the document is in a session, where moving the head moves it for everyone.
pub session: bool,
}
/// One interaction: a run of deltas that undo takes back together.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryRow {
/// The rev closing the interaction, in decimal.
pub id: String,
/// The name a person gave it, or one derived from what it changed.
pub label: String,
/// Whether `label` was given by a person.
pub named: bool,
/// The tags standing on it, in name order.
pub tags: Vec<String>,
pub author: String,
/// The author has no name on record, so `author` is a stand-in.
pub anonymous: bool,
/// The author is the person at this editor.
pub mine: bool,
pub color: String,
/// When the interaction entered history, in milliseconds since the Unix epoch, if its retirer recorded it.
pub time: Option<f64>,
pub deltas: usize,
/// Branches leaving this interaction that are not on the line shown, each by its tip.
pub branches: Vec<HistoryBranch>,
/// Above the head: taken back, and redo would bring it back.
pub undone: bool,
/// On a followed branch and not on the head's line: no head reaches it.
pub abandoned: bool,
pub head: bool,
pub expanded: bool,
/// The interaction's deltas, newest first, when expanded.
pub details: Vec<HistoryDeltaRow>,
}
/// A branch leaving an interaction, named by its tip and what its newest interaction did.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryBranch {
pub id: String,
pub label: String,
}
/// One delta of an expanded interaction.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryDeltaRow {
pub id: String,
pub label: String,
pub author: String,
pub color: String,
pub time: Option<f64>,
}
/// A person with ops in the room's hot log: their open or not yet retired work.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryProgressRow {
/// What the work changes so far, in the words of the rows.
pub label: String,
pub author: String,
pub anonymous: bool,
pub mine: bool,
pub color: String,
pub ops: usize,
/// Still being made, rather than closed and waiting to enter history.
pub open: bool,
}
@@ -49,6 +49,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
IngestMessage::Ingest { data, action, mime_type, path } => {
let data_type = DataType::detect(&data, &mime_type, path.as_deref());
let fresh_identity = matches!(action, IngestAction::OpenDemo);
let placement = match action {
IngestAction::ResourceInput {
document_id,
@@ -80,7 +81,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
}
return;
}
IngestAction::Open => None,
IngestAction::Open | IngestAction::OpenDemo => None,
IngestAction::Import | IngestAction::Paste => Some((None, None)),
IngestAction::DropOnCanvas { mouse } => Some((Some(mouse), None)),
IngestAction::DropOnLayers { parent, insert_index } => Some((None, Some((parent, insert_index as usize)))),
@@ -109,6 +110,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
document_name: name,
document_path,
content: data,
fresh_identity,
});
return;
}
@@ -16,6 +16,9 @@ const SNIFFED_TEXT_LENGTH: usize = 4096;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
pub enum IngestAction {
Open,
/// Open a distributed file such as a demo artwork: the copy gets a document id of its own, so everyone
/// opening it does not share one session room.
OpenDemo,
Import,
Paste,
DropOnCanvas {
+2
View File
@@ -6,8 +6,10 @@ pub mod document_migration;
pub mod document_storage_io;
pub mod failed_documents;
pub mod fonts;
pub mod history;
pub mod ingest;
pub mod persistent_state;
pub mod sync;
pub mod utility_types;
pub mod workspace;
@@ -1,5 +1,7 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::history::HistoryMessage;
use super::persistent_state::PersistentStateMessage;
use super::sync::SyncMessage;
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::prelude::*;
use std::path::PathBuf;
@@ -20,6 +22,10 @@ pub enum PortfolioMessage {
#[child]
PersistentState(PersistentStateMessage),
#[child]
History(HistoryMessage),
#[child]
Sync(SyncMessage),
#[child]
Workspace(WorkspaceMessage),
// Messages
@@ -86,6 +92,9 @@ pub enum PortfolioMessage {
document_name: Option<String>,
document_path: Option<PathBuf>,
content: Vec<u8>,
/// Give the copy a document id of its own, so everyone opening the same distributed file, a demo artwork
/// say, does not share one session room.
fresh_identity: bool,
},
/// Delivers a document built asynchronously from a `.gdd` archive (registry → runtime, working copy
/// mounted) into the portfolio. Travels once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
@@ -5,7 +5,7 @@ use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState, SessionStatus};
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
@@ -34,6 +34,8 @@ pub struct PortfolioMessageContext<'a> {
pub preferences: &'a PreferencesMessageHandler,
pub animation: &'a AnimationMessageHandler,
pub current_tool: &'a ToolType,
/// The icon name of the active tool, which the session shows beside this peer's pointer.
pub current_tool_icon: String,
pub reset_node_definitions_on_open: bool,
pub timing_information: TimingInformation,
pub viewport: &'a ViewportMessageHandler,
@@ -53,6 +55,8 @@ pub struct PortfolioMessageHandler {
persistent_state: PersistentStateMessageHandler,
pub fonts: FontsMessageHandler,
ingest: IngestMessageHandler,
history: HistoryMessageHandler,
sync: SyncMessageHandler,
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
@@ -70,6 +74,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
preferences,
animation,
current_tool,
current_tool_icon,
reset_node_definitions_on_open,
timing_information,
viewport,
@@ -118,6 +123,26 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.ingest.process_message(message, responses, context);
}
PortfolioMessage::History(message) => {
let context = HistoryMessageContext {
documents: &mut self.documents,
active_document_id: self.active_document_id,
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
};
self.history.process_message(message, responses, context);
}
PortfolioMessage::Sync(message) => {
let context = SyncMessageContext {
documents: &mut self.documents,
active_document_id: self.active_document_id,
resource_storage,
preferences,
ipp,
viewport,
current_tool_icon,
};
self.sync.process_message(message, responses, context);
}
PortfolioMessage::Workspace(message) => {
let context = WorkspaceMessageContext {
has_active_document: self.active_document_id.is_some(),
@@ -319,11 +344,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
let (gdd, declarations) = *mounted;
document.set_storage(gdd, declarations);
document.set_storage(gdd, declarations, resource_storage.resources_mut().storage());
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
responses.add(SyncMessage::StorageMounted { document_id });
}
PortfolioMessage::DestroyAllDocuments => {
// Empty the list of internal document data
@@ -361,6 +387,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
if let Some(storage) = document.storage() {
used_resources.extend(storage.all_referenced_resource_hashes());
}
// A step taken back on undo names resources nothing else refers to until it is redone.
used_resources.extend(document.retracted_resource_hashes());
}
used_resources.extend(self.fonts.used_resources());
responses.add(ResourceStorageMessage::GarbageCollect {
@@ -381,6 +409,15 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PortfolioMessage::LoadPersistedState { state } => {
if let Some(layout) = state.workspace_layout {
self.workspace.panel_layout = layout;
// A workspace saved before the Session panel existed gets it as a tab beside Properties, behind it; one
// where it was closed keeps it closed.
let panel_layout = &mut self.workspace.panel_layout;
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
match panel_layout.find_panel(PanelType::Properties).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
Some(group) => group.tabs.push(PanelType::Session),
None => panel_layout.restore_panel(PanelType::Session),
}
}
responses.add(WorkspaceMessage::UpdatePanelsLayout);
// Refill panels whose content was lost when the layout load remounted their frontend components
@@ -474,7 +511,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
}
self.load_document(new_document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
self.load_document(new_document, document_id, resource_storage, preferences, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::NextDocument => {
@@ -506,6 +543,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_name,
document_path,
content,
fresh_identity,
} => {
let document_id = DocumentId(generate_uuid());
@@ -518,6 +556,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_name,
document_path,
content,
fresh_identity,
resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
));
@@ -549,7 +588,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.path = document_path;
// The working copy is already mounted (we opened the .gdd), so skip the async re-mount.
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
self.load_document(document, document_id, resource_storage, preferences, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
@@ -588,6 +627,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
name,
resources: None,
path: document_path,
session: None,
is_saved: document_is_saved,
};
self.document_ids.retain(|id| id != &document_id);
@@ -702,7 +742,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.name = self.resolve_document_name(candidate_name, None);
// Load the document into the portfolio so it opens in the editor
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
self.load_document(document, document_id, resource_storage, preferences, responses);
responses.add(AppWindowMessage::Focus);
@@ -943,6 +983,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
responses.add(ToolMessage::InitTools);
responses.add(SyncMessage::RefreshPanel);
responses.add(NodeGraphMessage::Init);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::ToolAbort);
@@ -1240,7 +1281,7 @@ impl PortfolioMessageHandler {
mut new_document: DocumentMessageHandler,
document_id: DocumentId,
resource_storage: &ResourceStorageMessageHandler,
validate: bool,
preferences: &PreferencesMessageHandler,
responses: &mut VecDeque<Message>,
) {
let is_new_document = !self.document_ids.contains(&document_id);
@@ -1284,9 +1325,10 @@ impl PortfolioMessageHandler {
responses.add(Self::mount_document_storage(
self.working_copy_root.clone(),
document_id,
document_graph_storage::UserId(preferences.user_id),
legacy_network,
resource_storage.resources(),
validate,
preferences.validate_storage_round_trip,
));
}
}
@@ -1299,6 +1341,7 @@ impl PortfolioMessageHandler {
fn mount_document_storage(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
user: document_graph_storage::UserId,
legacy_network: graph_craft::document::NodeNetwork,
byte_store: Box<dyn graph_craft::application_io::resource::LoadResource>,
validate: bool,
@@ -1308,7 +1351,7 @@ impl PortfolioMessageHandler {
let peer = document_graph_storage::PeerId(generate_uuid());
let future = async move {
let (gdd, reopened) = match build_or_open_working_copy(path.as_deref(), peer, document_id.0, editor_version).await {
let (gdd, reopened) = match build_or_open_working_copy(path.as_deref(), peer, user, document_id.0, editor_version).await {
Ok(result) => result,
Err(error) => {
log::error!("Failed to mount document storage for {document_id:?}: {error}");
@@ -1372,6 +1415,11 @@ impl PortfolioMessageHandler {
path: document.path.clone(),
is_saved: document.is_saved(),
resources: Some(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()).collect::<Vec<_>>().into_boxed_slice()),
session: document.storage().and_then(|gdd| match (gdd.role().is_some(), gdd.is_shared()) {
(true, _) => Some(SessionStatus::Connected),
(false, true) => Some(SessionStatus::Disconnected),
(false, false) => None,
}),
})
} else {
self.unloaded_documents.get(&document_id).cloned()
@@ -0,0 +1,98 @@
//! How a person is shown wherever the editor names one: the stand-in for someone unnamed, and the colour that
//! follows a user id through the cursors, the Session panel and the History panel.
use document_graph_storage::UserId;
/// A stand-in for a person who has not given a name, the same on every device of theirs and everywhere
/// in the room, since it comes from the user id alone.
pub(crate) fn anonymous_name(user: UserId) -> String {
let index = (user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40) as usize % ANONYMOUS_ANIMALS.len();
format!("Anonymous {}", ANONYMOUS_ANIMALS[index])
}
pub(crate) const ANONYMOUS_ANIMALS: [&str; 64] = [
"Alligator",
"Anteater",
"Armadillo",
"Axolotl",
"Badger",
"Bat",
"Beaver",
"Buffalo",
"Camel",
"Capybara",
"Chameleon",
"Cheetah",
"Chinchilla",
"Chipmunk",
"Cormorant",
"Coyote",
"Crow",
"Dingo",
"Dolphin",
"Duck",
"Elephant",
"Ferret",
"Fox",
"Frog",
"Giraffe",
"Gopher",
"Grizzly",
"Hedgehog",
"Heron",
"Hippo",
"Hyena",
"Ibex",
"Iguana",
"Jackal",
"Jaguar",
"Kangaroo",
"Koala",
"Kraken",
"Lemur",
"Leopard",
"Liger",
"Llama",
"Manatee",
"Mink",
"Monkey",
"Moose",
"Narwhal",
"Nyan Cat",
"Orangutan",
"Otter",
"Panda",
"Penguin",
"Platypus",
"Python",
"Quagga",
"Rabbit",
"Raccoon",
"Rhino",
"Sheep",
"Shrew",
"Skunk",
"Squirrel",
"Tiger",
"Turtle",
];
/// A colour for a person derived from their user id, so every peer sees the same one without anything on the
/// wire, and one person has one colour across their tabs and in the history.
pub(crate) fn user_color(user: UserId) -> String {
let hue = (user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) % 360;
let (h, s, l): (f64, f64, f64) = (hue as f64 / 60., 0.65, 0.5);
let c = (1. - (2. * l - 1.).abs()) * s;
let x = c * (1. - (h % 2. - 1.).abs());
let m = l - c / 2.;
let (r, g, b) = match h as u32 {
0 => (c, x, 0.),
1 => (x, c, 0.),
2 => (0., c, x),
3 => (0., x, c),
4 => (x, 0., c),
_ => (c, 0., x),
};
let channel = |value: f64| ((value + m) * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", channel(r), channel(g), channel(b))
}
@@ -0,0 +1,9 @@
pub(crate) mod identity;
mod sync_message;
mod sync_message_handler;
#[doc(inline)]
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
pub(crate) use sync_message_handler::now_ms;
#[doc(inline)]
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
@@ -0,0 +1,39 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::ResourceHash;
use peer_transport::TransportPeerId;
#[impl_message(Message, PortfolioMessage, Sync)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum SyncMessage {
/// Host the active document in the room every copy of it shares, and hand the frontend a link for others.
Share,
/// Open a new document that follows the session behind `token`.
Join { token: String },
/// Disconnect the active document from its room; editing goes on alone until the next share.
Leave,
/// Leave the room and host the active document as a new session with its own link, keeping its content and
/// history; the others keep the room they are in.
Fork,
/// Send the Session panel's layout for the active document.
RefreshPanel,
/// Per frame: apply what peers sent and answer their requests.
Poll,
/// A packet arrived for a document's room: poll it now rather than at the next frame. `generation`
/// names the connection it was armed for, so a wake from an earlier connection is ignored.
Wake { document_id: DocumentId, generation: u32 },
/// A document's working copy mounted; attaches it to a pending join.
StorageMounted { document_id: DocumentId },
/// The transport loop of a document's session ended. `generation` names the connection it drove, so the end of
/// a connection the document already left, or replaced by a fork, is nothing to act on.
Disconnected { document_id: DocumentId, generation: u32 },
/// A declaration a remote change names was already on hand and was read from the byte store to be
/// decoded; `None` when the store turned out not to hold it after all.
DeclarationLoaded { document_id: DocumentId, hash: ResourceHash, bytes: Option<Vec<u8>> },
/// A resource a peer asked for was read from the byte store.
ResourceLoaded {
document_id: DocumentId,
to: TransportPeerId,
hash: ResourceHash,
bytes: Vec<u8>,
},
}
@@ -0,0 +1,771 @@
use super::identity::{anonymous_name, user_color};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendRemoteCursor;
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::resource_storage::ResourcesHandle;
use crate::messages::viewport::Position;
use document_graph_storage::{HistoryMetadata, UserId, user_attr};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{LoadResource, ResourceHash};
use peer_transport::{CursorPosition, CursorSpace, DEFAULT_SIGNALING_SERVER, Event, Incoming, RemotePeer, Role, Room, SessionToken, SyncTarget};
use std::collections::HashSet;
#[derive(ExtractField)]
pub struct SyncMessageContext<'a> {
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
pub active_document_id: Option<DocumentId>,
pub resource_storage: &'a ResourceStorageMessageHandler,
pub preferences: &'a PreferencesMessageHandler,
pub ipp: &'a InputPreprocessorMessageHandler,
pub viewport: &'a ViewportMessageHandler,
pub current_tool_icon: String,
}
/// Drives every document's collaborative session: attaches transports, polls them once per frame and as
/// packets arrive, and turns remote changes into interface rebuilds.
#[derive(Debug, Default, ExtractField)]
pub struct SyncMessageHandler {
pending_join: Option<SessionToken>,
polling: bool,
/// Each connected document's room inbox, tagged with the connection it belongs to. One wake future is in
/// flight per entry: it resolves to a `Wake`, which polls and arms the next one.
incoming: HashMap<DocumentId, (u32, Incoming)>,
connections: u32,
/// Documents whose registry changed remotely since their interface was last rebuilt.
dirty: HashSet<DocumentId>,
/// Documents that just took the host's state on: once their interface follows and the graph has run, the
/// viewport is fitted to the document, so a guest sees what it joined rather than an empty canvas.
fit_after_sync: HashSet<DocumentId>,
/// When each document connected to its room still undecided, so the host role is taken once no host has
/// greeted it for the grace period.
undecided_since: HashMap<DocumentId, f64>,
blocked_reason: HashMap<DocumentId, String>,
/// Declarations being read from the byte store to be decoded, so a document waiting on them asks once.
decoding: HashSet<(DocumentId, ResourceHash)>,
/// The pointer position last sent for each connected document, so one is sent only when it moved.
last_cursor: HashMap<DocumentId, Option<CursorPosition>>,
/// The other peers' pointers over the node graph as last sent to the frontend.
graph_cursors: Vec<FrontendRemoteCursor>,
document_cursors: Vec<FrontendRemoteCursor>,
/// When each document whose transport went down is next to be reconnected.
reconnect_at: HashMap<DocumentId, f64>,
}
#[message_handler_data]
impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler {
fn process_message(&mut self, message: SyncMessage, responses: &mut VecDeque<Message>, context: SyncMessageContext) {
let SyncMessageContext {
documents,
active_document_id,
resource_storage,
preferences,
ipp,
viewport,
current_tool_icon,
} = context;
match message {
SyncMessage::Share => {
let Some(document) = active_document_id.and_then(|id| documents.get_mut(&id)) else { return };
let Some(gdd) = document.storage_mut() else {
log::warn!("Cannot share a document before its working copy is mounted");
return;
};
if gdd.role().is_some() {
return;
}
// Guests learn the name from the registry.
document.stage_name_attribute();
let Some(gdd) = document.storage_mut() else { return };
let document_id = active_document_id.expect("checked above");
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
// The panel shows the link; the clipboard gets it too, so sharing stays one step.
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
self.start_polling(responses);
}
SyncMessage::Join { token } => {
if token.trim().is_empty() {
return;
}
let token = match token.parse::<SessionToken>() {
Ok(token) => token,
Err(error) => {
log::warn!("Ignoring session link: {error}");
return;
}
};
self.pending_join = Some(token);
responses.add(PortfolioMessage::NewDocumentWithName { name: "Shared session".into() });
}
SyncMessage::StorageMounted { document_id } => {
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
return;
};
// Retirement runs on the frame tick for every document, in a session or not, so history grows as steps
// close rather than waiting for the first undo.
self.start_polling(responses);
if let Some(token) = self.pending_join.take() {
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
let incoming = room.incoming();
gdd.join(room, UserId(preferences.user_id));
announce_name(gdd, &preferences.user_name);
self.attach(document_id, incoming, responses);
responses.add(driver_future(document_id, self.connections, driver));
refresh_session_views(responses);
self.start_polling(responses);
} else if gdd.is_shared() && gdd.role().is_none() {
// The document was in its room when it was last persisted: a reload rejoins on its own.
self.connect_document(document_id, gdd, preferences, responses);
} else {
// The panel may have shown the document still mounting.
responses.add(SyncMessage::RefreshPanel);
}
}
SyncMessage::Leave => {
let Some(document_id) = active_document_id else { return };
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
return;
};
gdd.leave();
self.incoming.remove(&document_id);
self.last_cursor.remove(&document_id);
self.reconnect_at.remove(&document_id);
refresh_session_views(responses);
}
SyncMessage::Fork => {
let Some(document_id) = active_document_id else { return };
let Some(document) = documents.get_mut(&document_id) else { return };
document.stage_name_attribute();
let Some(gdd) = document.storage_mut() else { return };
// The room is derived from the manifest's document id, so a fresh id is a fresh room. A guest
// already rewrites the id when it joins, and the working copy's directory is keyed by the editor's
// own id, so nothing moves on disk.
gdd.leave();
self.incoming.remove(&document_id);
self.last_cursor.remove(&document_id);
if let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = crate::application::generate_uuid()) {
log::error!("Forking the session failed: {error}");
refresh_session_views(responses);
return;
}
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
self.start_polling(responses);
}
SyncMessage::Disconnected { document_id, generation } => {
if self.incoming.get(&document_id).is_none_or(|(current, _)| *current != generation) {
return;
}
// The transport went down under a document that meant to stay in its room: it stays shared, so
// the panel shows it disconnected and offers to reconnect, and a reopen reconnects on its own.
if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) {
gdd.disconnect();
self.reconnect_at.insert(document_id, now_ms() + RECONNECT_AFTER_MS);
}
self.incoming.remove(&document_id);
self.last_cursor.remove(&document_id);
refresh_session_views(responses);
}
SyncMessage::RefreshPanel => {
let layout = session_panel_layout(documents, active_document_id, preferences);
responses.add(LayoutMessage::SendLayout {
layout,
layout_target: LayoutTarget::SessionPanel,
});
}
SyncMessage::Poll | SyncMessage::Wake { .. } => {
// A wake names the connection it was armed for; one from a connection since left is nothing to act on.
let woken = match message {
SyncMessage::Wake { document_id, generation } => {
if self.incoming.get(&document_id).is_none_or(|(current, _)| *current != generation) {
return;
}
Some(document_id)
}
_ => None,
};
let resources = resource_storage.resources_mut();
for (&document_id, document) in documents.iter_mut() {
// Retirement follows the working copy's policy on every document, in a session or not: closed
// transactions retire once enough have waited long enough, never on a gesture.
let idle = document.network_interface.transaction_status() == TransactionStatus::Finished;
if let Some(gdd) = document.storage_mut()
&& let Err(error) = gdd.retire_due(now_ms(), idle)
{
log::error!("Retirement failed: {error}");
}
// The person behind this copy goes on the document's record of its users, so whoever opens it later
// can name the author of every step; a no-op once the name is on record.
if let Some(gdd) = document.storage_mut() {
record_profile(gdd, preferences);
}
// A document whose transport went down tries again after a pause, for as long as it is meant to be shared.
if self.reconnect_at.get(&document_id).is_some_and(|&due| now_ms() >= due)
&& let Some(gdd) = document.storage_mut()
{
self.reconnect_at.remove(&document_id);
if gdd.is_shared() && gdd.role().is_none() {
log::info!("Reconnecting {document_id:?} to its session");
self.connect_document(document_id, gdd, preferences, responses);
}
}
if document.storage().is_none_or(|gdd| gdd.role().is_none()) {
continue;
}
// A document without a host, connected that way or left that way by a host that went before
// syncing it, takes the role itself once no host has greeted it for the grace period.
if document.storage().is_some_and(|gdd| gdd.role() == Some(peer_transport::Role::Undecided)) {
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
if now_ms() - since >= ROLE_GRACE_MS
&& let Some(gdd) = document.storage_mut()
&& gdd.decide_role().is_some()
{
self.undecided_since.remove(&document_id);
refresh_session_views(responses);
}
} else {
self.undecided_since.remove(&document_id);
}
// Each movement reaches peers as it happens: what the interface recorded since the last
// frame is staged, and so broadcast, ahead of this frame's poll.
document.stage_pending_edits(&resources);
// Presence rides outside the causal broadcast: the name whenever it changed, and the pointer
// over the active document once per frame when it moved, `None` for every other document.
let cursor = (Some(document_id) == active_document_id)
.then(|| cursor_position(document, ipp, viewport, &current_tool_icon))
.flatten();
let Some(gdd) = document.storage_mut() else { continue };
announce_name(gdd, &preferences.user_name);
if self.last_cursor.get(&document_id) != Some(&cursor) {
match gdd.send_cursor(cursor.clone()) {
Ok(()) => {
self.last_cursor.insert(document_id, cursor);
}
Err(error) => log::warn!("Sending the pointer position failed: {error}"),
}
}
let events = gdd.poll_peers();
// Taken every poll rather than on an event: a full sync a hello triggers can replace the
// registry with no change event to announce it.
let changes = gdd.take_remote_changes();
if !changes.is_empty() {
document.pending_remote.extend(changes);
self.dirty.insert(document_id);
}
for event in events {
match event {
Event::Synced => {
log::info!("Join handshake: synced, applying the host's state");
refresh_session_views(responses);
self.dirty.insert(document_id);
self.fit_after_sync.insert(document_id);
}
Event::Changed => {
self.dirty.insert(document_id);
}
Event::ResourceRequested { from, hash } => {
log::debug!("Peer asked for resource {hash}");
responses.add(load_resource_future(document_id, from, hash, resources.clone()));
}
// The replica already put the bytes in the byte store; only the decoded form is missing.
Event::ResourceReceived { hash, bytes } => {
log::debug!("Received resource {hash} ({} bytes)", bytes.len());
document.cache_declaration_bytes(hash, &bytes);
self.dirty.insert(document_id);
}
Event::RoleChanged { role } => {
log::info!("Session role is now {role:?}");
refresh_session_views(responses);
}
Event::PeerJoined { .. } | Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
Event::MetadataChanged => {
refresh_session_views(responses);
responses.add(HistoryMessage::Refresh);
}
// Cursors are gathered afresh below every poll, so a move needs no action of its own.
Event::CursorMoved { .. } => {}
}
}
}
// The other peers' pointers over the node graph go to the frontend as viewport points, like the box
// selection, whenever they change; the canvas overlay draws the ones over the document.
let graph_cursors = active_document_id
.and_then(|id| documents.get(&id))
.map(|document| graph_cursors(document, preferences))
.unwrap_or_default();
if graph_cursors != self.graph_cursors {
self.graph_cursors = graph_cursors.clone();
responses.add(FrontendMessage::UpdateNodeGraphCursors { cursors: graph_cursors });
}
let document_cursors = active_document_id
.and_then(|id| documents.get(&id))
.map(|document| document_cursors(document, preferences))
.unwrap_or_default();
if document_cursors != self.document_cursors {
self.document_cursors = document_cursors.clone();
responses.add(FrontendMessage::UpdateDocumentCursors { cursors: document_cursors });
}
// Apply only once every referenced resource is in the app cache, and never underneath an
// open transaction, whose tool state names nodes a peer may have removed.
for document_id in self.dirty.clone() {
let Some(document) = documents.get_mut(&document_id) else {
self.dirty.remove(&document_id);
continue;
};
let Some(gdd) = document.storage() else { continue };
let missing = SyncTarget::missing_resources(gdd).len();
let transaction = document.network_interface.transaction_status();
if missing > 0 || transaction != TransactionStatus::Finished {
let reason = format!("missing {missing} transaction {transaction:?}");
if self.blocked_reason.get(&document_id) != Some(&reason) {
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
self.blocked_reason.insert(document_id, reason);
}
continue;
}
// Every resource is on hand, but a declaration held since an earlier session was never received from
// a peer and so never decoded: read it from the byte store, and apply once it is cached.
let undecoded = document.undecoded_declaration_hashes();
if !undecoded.is_empty() {
let reason = format!("decoding {} held declarations", undecoded.len());
if self.blocked_reason.get(&document_id) != Some(&reason) {
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
self.blocked_reason.insert(document_id, reason);
}
for hash in undecoded {
if self.decoding.insert((document_id, hash)) {
responses.add(decode_declaration_future(document_id, hash, resources.clone()));
}
}
continue;
}
self.blocked_reason.remove(&document_id);
// Stays dirty while a declaration the changes need is still on its way.
if document.apply_remote_changes(responses) {
self.dirty.remove(&document_id);
if document.adopt_name_from_storage() {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
if self.fit_after_sync.remove(&document_id) && Some(document_id) == active_document_id {
log::info!("Join handshake: the host's state is applied, fitting the viewport after the graph runs");
// The bounds come from the render, so the fit waits for the graph to run on the new document.
responses.add(DeferMessage::AfterGraphRun {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
});
}
}
// The registry names resources this peer may still have to fetch or resolve.
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
// The inbox was drained above; the next arrival wakes the next poll.
if let Some(document_id) = woken {
self.arm(document_id, responses);
}
}
SyncMessage::DeclarationLoaded { document_id, hash, bytes } => {
let Some(bytes) = bytes else {
// Stays in `decoding` so it is not asked for again every frame; the document waits on it.
log::warn!("Declaration {hash} is recorded as held but the byte store has no bytes for it");
return;
};
self.decoding.remove(&(document_id, hash));
let Some(document) = documents.get_mut(&document_id) else { return };
log::debug!("Decoded held declaration {hash} ({} bytes)", bytes.len());
document.cache_declaration_bytes(hash, &bytes);
self.dirty.insert(document_id);
}
SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => {
log::debug!("Sending resource {hash} ({} bytes)", bytes.len());
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
return;
};
if let Err(error) = gdd.send_resource(to, hash, bytes) {
log::warn!("Failed to send resource {hash} to a peer: {error}");
}
}
}
}
advertise_actions!(SyncMessageDiscriminant; Share, Leave);
}
impl SyncMessageHandler {
/// Connect `document_id`'s working copy to the room every copy of the document shares, and hand the
/// frontend the link. Returns the token, `None` when the connection could not be set up.
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut document_format::GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
let token = SessionToken::for_document(gdd.manifest().document_id);
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
let incoming = room.incoming();
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
log::error!("Connecting to the session failed: {error}");
return None;
}
announce_name(gdd, &preferences.user_name);
self.undecided_since.insert(document_id, now_ms());
self.reconnect_at.remove(&document_id);
self.attach(document_id, incoming, responses);
responses.add(driver_future(document_id, self.connections, driver));
refresh_session_views(responses);
self.start_polling(responses);
Some(token)
}
/// Poll `document_id`'s room as packets arrive, not only per frame: a hidden browser tab gets about one
/// frame a second, which made a host answer each step of a join a second late. The wake rides on the
/// editor's future plumbing, so it works the same on the desktop as in the browser.
fn attach(&mut self, document_id: DocumentId, incoming: Incoming, responses: &mut VecDeque<Message>) {
self.connections += 1;
self.incoming.insert(document_id, (self.connections, incoming));
self.arm(document_id, responses);
}
/// Put one wake future in flight for `document_id`'s current connection.
fn arm(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
let Some((generation, incoming)) = self.incoming.get(&document_id).cloned() else { return };
let future = async move {
match incoming.wait().await {
true => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Wake { document_id, generation })),
// The room's loop ended; its driver reports the disconnection.
false => Message::NoOp,
}
};
responses.add(future);
}
fn start_polling(&mut self, responses: &mut VecDeque<Message>) {
if self.polling {
return;
}
self.polling = true;
responses.add(BroadcastMessage::SubscribeEvent {
on: EventMessage::AnimationFrame,
send: Box::new(SyncMessage::Poll.into()),
});
}
}
fn driver_future(document_id: DocumentId, generation: u32, driver: peer_transport::MessageLoopFuture) -> Message {
let future = async move {
if let Err(error) = driver.await {
log::warn!("Session transport for {document_id:?} ended: {error}");
}
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Disconnected { document_id, generation }))
};
future.into()
}
/// Read a declaration the byte store already holds, so it can be decoded for a remote change that names it.
fn decode_declaration_future(document_id: DocumentId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
let future = async move {
let bytes = resources.load(hash).await.map(|resource| resource.as_ref().to_vec());
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::DeclarationLoaded { document_id, hash, bytes }))
};
future.into()
}
fn load_resource_future(document_id: DocumentId, to: peer_transport::TransportPeerId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
let future = async move {
match resources.load(hash).await {
Some(resource) => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceLoaded {
document_id,
to,
hash,
bytes: resource.as_ref().to_vec(),
})),
None => {
log::warn!("A peer asked for resource {hash} which is not in the byte store");
Message::NoOp
}
}
};
future.into()
}
/// How long a peer that connected to an empty-looking room waits for a host's hello before it takes the
/// role itself.
const ROLE_GRACE_MS: f64 = 1_500.;
/// A monotonic-enough millisecond clock for the retirement policy, which only ever compares differences.
pub(crate) fn now_ms() -> f64 {
#[cfg(target_arch = "wasm32")]
{
js_sys::Date::now()
}
#[cfg(not(target_arch = "wasm32"))]
{
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs_f64() * 1000.)
.unwrap_or(0.)
}
}
/// The session state changed: the document tabs show it as a circle and the Session panel in full.
fn refresh_session_views(responses: &mut VecDeque<Message>) {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(SyncMessage::RefreshPanel);
}
/// The Session panel for the active document: its state in words, the join link, the peers, and the actions
/// that apply in that state.
fn session_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
let heading = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).bold(true).widget_instance()]);
let note = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).multiline(true).widget_instance()]);
let user_name = preferences.user_name.as_str();
// The name and the cursor switch are preferences, so they are the same in every session and asked for once.
let name_row = || {
LayoutGroup::row(vec![
TextLabel::new("Your name").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(user_name)
.placeholder(anonymous_name(UserId(preferences.user_id)))
.on_update(|input: &TextInput| PreferencesMessage::UserName { name: input.value.clone() }.into())
.widget_instance(),
])
};
let cursors_row = || {
let checkbox_id = CheckboxId::new();
LayoutGroup::row(vec![
TextLabel::new("Show cursors").table_align(true).min_width(90).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.show_remote_cursors)
.tooltip_description("Draw the other peers' pointers over the document.")
.on_update(|checkbox: &CheckboxInput| PreferencesMessage::ShowRemoteCursors { enabled: checkbox.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
])
};
let Some(document) = active_document_id.and_then(|id| documents.get(&id)) else {
return Layout(vec![note("Open a document to share it.")]);
};
let Some(gdd) = document.storage() else {
return Layout(vec![name_row(), cursors_row(), note("The document's working copy is still being mounted.")]);
};
let fork = || {
TextButton::new("Fork")
.tooltip_label("Fork the session")
.tooltip_description("Leave this room and host the document as a new session with its own link. The others keep the room they are in.")
.on_commit(|_| SyncMessage::Fork.into())
.widget_instance()
};
// The same shape in every state: the state, the actions that apply in it, then the detail.
let (state, actions, detail) = match gdd.role() {
None if gdd.is_shared() => (
"Disconnected, reconnecting",
vec![
TextButton::new("Reconnect").icon("Link").emphasized(true).on_commit(|_| SyncMessage::Share.into()).widget_instance(),
TextButton::new("Stop Sharing").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
fork(),
],
note("The connection to the session was lost. The editor keeps trying to reconnect, and the document stays editable meanwhile."),
),
None => (
"Not shared",
vec![
TextButton::new("Share Live Session")
.icon("Link")
.emphasized(true)
.on_commit(|_| SyncMessage::Share.into())
.widget_instance(),
],
LayoutGroup::column(vec![
TextLabel::new("Share this document to edit it live with others. Everyone who opens the link works on the same document.")
.multiline(true)
.widget_instance(),
]),
),
Some(role) => {
let live = role == Role::Host || (role == Role::Guest && gdd.is_synced());
let token = SessionToken::for_document(gdd.manifest().document_id).to_string();
let copy_token = token.clone();
let bare_token = token.clone();
(
if live { "Live session" } else { "Connecting" },
vec![
TextButton::new("Copy Link")
.icon("Copy")
.emphasized(true)
.on_commit(move |_| FrontendMessage::TriggerSessionLinkCopy { token: copy_token.clone() }.into())
.widget_instance(),
TextButton::new("Disconnect").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
fork(),
],
LayoutGroup::row(vec![
TextLabel::new(token)
.monospace(true)
.selectable(true)
.tooltip_label("Session")
.tooltip_description("Opening the editor with this session in the link joins the room.")
.widget_instance(),
// The text itself, for the CLI or a message where a link is not wanted; the label is selectable but the
// editor owns the copy shortcut.
IconButton::new("Copy", 24)
.tooltip_label("Copy Session Token")
.on_update(move |_| FrontendMessage::TriggerClipboardWrite { content: bare_token.clone() }.into())
.widget_instance(),
]),
)
}
};
let mut groups = vec![name_row(), cursors_row(), heading(state), LayoutGroup::row(actions), detail];
if gdd.role().is_none() && !gdd.is_shared() {
groups.push(LayoutGroup::row(vec![
TextLabel::new("Join a session").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new("")
.placeholder("Paste a link")
.tooltip_description("Opens the shared document in a new tab, following the session behind the link.")
.on_update(|input: &TextInput| SyncMessage::Join { token: input.value.clone() }.into())
.widget_instance(),
]));
}
if gdd.role().is_some() {
let mut peers = gdd.peers();
peers.sort_by_key(|remote| remote.peer);
groups.push(heading(&format!("In the session ({})", peers.len() + 1)));
let me = match user_name.is_empty() {
true => anonymous_name(UserId(preferences.user_id)),
false => user_name.to_string(),
};
groups.push(peer_row(&format!("{me} (you)"), user_name.is_empty()));
let metadata = gdd.metadata();
groups.extend(peers.iter().map(|remote| peer_row(&display_name(remote, metadata), is_anonymous(remote, metadata))));
}
Layout(groups)
}
/// One peer in the list; an anonymous one shows its stand-in name in italics.
fn peer_row(name: &str, anonymous: bool) -> LayoutGroup {
LayoutGroup::row(vec![TextLabel::new(name).italic(anonymous).widget_instance()])
}
/// Put this user's display name on the document's record of its users; a no-op when it is already there. An
/// unnamed user is not recorded until a name to clear stands.
fn record_profile(gdd: &mut document_format::GddV1, preferences: &PreferencesMessageHandler) {
let name = preferences.user_name.trim();
let user = UserId(preferences.user_id);
if name.is_empty() && gdd.metadata().user_name(user).is_none() {
return;
}
if let Err(error) = gdd.record_user_attribute(user, user_attr::NAME, serde_json::Value::from(name), now_ms()) {
log::warn!("Recording the display name failed: {error}");
}
}
/// Tell the room this peer's display name; a no-op when it has not changed.
fn announce_name(gdd: &mut document_format::GddV1, name: &str) {
if let Err(error) = gdd.set_name(name) {
log::warn!("Announcing the display name failed: {error}");
}
}
/// The pointer while it is over the viewport, in the space it is over: the node graph's network when the
/// graph is open, the document otherwise. Rounded so jitter below a hundredth of a unit sends nothing.
fn cursor_position(document: &DocumentMessageHandler, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler, tool_icon: &str) -> Option<CursorPosition> {
let mouse = ipp.mouse.position;
let size = viewport.size();
if mouse.x < 0. || mouse.y < 0. || mouse.x > size.x() || mouse.y > size.y() {
return None;
}
let (to_viewport, space) = match document.is_graph_overlay_open() {
true => (graph_to_viewport(document)?, CursorSpace::Graph { network: shown_network(document) }),
false => (document.metadata().document_to_viewport, CursorSpace::Document),
};
let position = to_viewport.inverse().transform_point2(mouse);
Some(CursorPosition {
position: [(position.x * 100.).round() / 100., (position.y * 100.).round() / 100.],
space,
tool: (!tool_icon.is_empty()).then(|| tool_icon.to_string()),
})
}
/// The other peers' pointers over the document, in viewport pixels for the frontend, while the canvas is showing.
fn document_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
if !preferences.show_remote_cursors || document.is_graph_overlay_open() {
return Vec::new();
}
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
let to_viewport = document.metadata().document_to_viewport;
gdd.peers()
.iter()
.filter_map(|remote| {
let cursor = remote.cursor.as_ref()?;
matches!(cursor.space, CursorSpace::Document).then(|| remote_cursor(remote, cursor, to_viewport, gdd.metadata()))
})
.collect()
}
/// The other peers' pointers over the network the node graph shows, in viewport pixels for the frontend.
fn graph_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
if !preferences.show_remote_cursors || !document.is_graph_overlay_open() {
return Vec::new();
}
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
let Some(to_viewport) = graph_to_viewport(document) else { return Vec::new() };
let shown = shown_network(document);
gdd.peers()
.iter()
.filter_map(|remote| {
let cursor = remote.cursor.as_ref()?;
let CursorSpace::Graph { network } = &cursor.space else { return None };
(*network == shown).then(|| remote_cursor(remote, cursor, to_viewport, gdd.metadata()))
})
.collect()
}
/// One pointer for the frontend: its position mapped into viewport pixels, with the peer's name, colour and tool.
fn remote_cursor(remote: &RemotePeer, cursor: &CursorPosition, to_viewport: DAffine2, metadata: &HistoryMetadata) -> FrontendRemoteCursor {
let [x, y] = cursor.position;
let point = to_viewport.transform_point2(DVec2::new(x, y));
FrontendRemoteCursor {
x: point.x,
y: point.y,
name: display_name(remote, metadata),
anonymous: is_anonymous(remote, metadata),
color: user_color(remote.user),
tool: cursor.tool.clone(),
}
}
fn graph_to_viewport(document: &DocumentMessageHandler) -> Option<DAffine2> {
let metadata = document.network_interface.network_metadata(document.breadcrumb_network_path())?;
Some(metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
}
fn shown_network(document: &DocumentMessageHandler) -> Vec<u64> {
document.breadcrumb_network_path().iter().map(|id| id.0).collect()
}
/// The one rule for a name shown anywhere: the document's record of the user, else what the peer announced
/// for the room, else the stand-in.
fn display_name(remote: &RemotePeer, metadata: &HistoryMetadata) -> String {
if let Some(name) = metadata.user_name(remote.user) {
return name.to_string();
}
match remote.name.is_empty() {
true => anonymous_name(remote.user),
false => remote.name.clone(),
}
}
fn is_anonymous(remote: &RemotePeer, metadata: &HistoryMetadata) -> bool {
metadata.user_name(remote.user).is_none() && remote.name.is_empty()
}
/// How long a document whose transport went down waits before it tries its room again.
const RECONNECT_AFTER_MS: f64 = 3_000.;
+31 -5
View File
@@ -11,6 +11,10 @@ pub enum PanelType {
Layers,
Properties,
Data,
/// The live session of the active document: its state, the join link, the peers, and the sharing actions.
Session,
/// The active document's history as interactions along the head's line, with who did what and when.
History,
}
impl From<String> for PanelType {
@@ -21,6 +25,8 @@ impl From<String> for PanelType {
"Layers" => PanelType::Layers,
"Properties" => PanelType::Properties,
"Data" => PanelType::Data,
"Session" => PanelType::Session,
"History" => PanelType::History,
_ => panic!("Unknown panel type: {value}"),
}
}
@@ -28,7 +34,7 @@ impl From<String> for PanelType {
impl PanelType {
pub fn non_document_panels() -> &'static [PanelType] {
&[PanelType::Layers, PanelType::Properties, PanelType::Data]
&[PanelType::Layers, PanelType::Properties, PanelType::Data, PanelType::Session, PanelType::History]
}
}
@@ -251,6 +257,11 @@ impl WorkspacePanelLayout {
});
}
/// Whether the panel was closed by the user, so its position is remembered for a later restore.
pub fn was_closed(&self, panel_type: PanelType) -> bool {
self.saved_positions.iter().any(|saved| saved.panel_type == panel_type)
}
/// Restore a panel to its previous position if available, otherwise to its default position.
pub fn restore_panel(&mut self, panel_type: PanelType) {
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
@@ -301,6 +312,21 @@ impl WorkspacePanelLayout {
/// - Properties: top of the right column (root child 1)
/// - Layers: bottom of the right column (root child 1)
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
// The Session panel's home is a tab beside Properties and the History panel's beside Layers, so each joins
// that group whenever one is present.
let beside = match panel_type {
PanelType::Session => Some(PanelType::Properties),
PanelType::History => Some(PanelType::Layers),
_ => None,
};
if let Some(beside) = beside
&& let Some(group_id) = self.find_panel(beside)
&& let Some(group) = self.panel_group_mut(group_id)
{
group.tabs.push(panel_type);
group.active_tab_index = group.tabs.len() - 1;
return;
}
let new_id = self.next_id();
let new_group = SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
@@ -315,9 +341,9 @@ impl WorkspacePanelLayout {
// Determine which root child column to insert into and at which position
let (root_child_index, insert_at_end) = match panel_type {
PanelType::Data => (0, true), // Left column, after document
PanelType::Properties => (1, false), // Right column, at top
PanelType::Layers => (1, true), // Right column, at bottom
PanelType::Data => (0, true), // Left column, after document
PanelType::Properties | PanelType::Session => (1, false), // Right column, at top
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
_ => (1, true),
};
@@ -402,7 +428,7 @@ impl Default for WorkspacePanelLayout {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: PanelGroupId(1),
state: PanelGroupState {
tabs: vec![PanelType::Properties],
tabs: vec![PanelType::Properties, PanelType::Session],
active_tab_index: 0,
},
},
@@ -30,7 +30,13 @@ pub enum WorkspaceMessage {
active_tab_index: usize,
},
ToggleFocusDocument,
/// Bring a panel to the front: the active tab of its group, restored to its default position first when it is closed.
FocusPanel {
panel_type: PanelType,
},
ToggleDataPanelOpen,
ToggleSessionPanelOpen,
ToggleHistoryPanelOpen,
TogglePropertiesPanelOpen,
ToggleLayersPanelOpen,
UpdatePanelsLayout,
@@ -267,6 +267,19 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
let panel_type = PanelType::Layers;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::FocusPanel { panel_type } => {
if self.panel_layout.focus_document {
return;
}
let Some(group) = self.panel_layout.find_panel(panel_type) else {
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
return;
};
let Some(tab_index) = self.panel_layout.panel_group(group).and_then(|state| state.tabs.iter().position(|&tab| tab == panel_type)) else {
return;
};
responses.add(WorkspaceMessage::SetPanelGroupActiveTab { group, tab_index });
}
WorkspaceMessage::ToggleDataPanelOpen => {
if self.panel_layout.focus_document {
return;
@@ -275,6 +288,22 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
let panel_type = PanelType::Data;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::ToggleSessionPanelOpen => {
if self.panel_layout.focus_document {
return;
}
let panel_type = PanelType::Session;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::ToggleHistoryPanelOpen => {
if self.panel_layout.focus_document {
return;
}
let panel_type = PanelType::History;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::UpdatePanelsLayout => {
let panel_layout = match self.panel_layout.focus_document {
true => self.panel_layout.document_only_layout(),
@@ -390,7 +419,8 @@ impl WorkspaceMessageHandler {
PanelType::Properties => &[LayoutTarget::PropertiesPanel],
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelControlRightBar, LayoutTarget::LayersPanelBottomBar],
PanelType::Data => &[LayoutTarget::DataPanel],
PanelType::Document | PanelType::Welcome => return,
PanelType::Session => &[LayoutTarget::SessionPanel],
PanelType::Document | PanelType::Welcome | PanelType::History => return,
};
for &layout_target in targets {
@@ -416,6 +446,12 @@ impl WorkspaceMessageHandler {
PanelType::Data => {
// The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here
}
PanelType::Session => {
responses.add(SyncMessage::RefreshPanel);
}
PanelType::History => {
responses.add(HistoryMessage::Refresh);
}
PanelType::Document | PanelType::Welcome => {
// Re-send the welcome screen buttons layout to repopulate after a remount
if has_no_documents {
@@ -440,11 +476,11 @@ mod tests {
};
let group_of = |handler: &WorkspaceMessageHandler, panel_type| handler.panel_layout.find_panel(panel_type).expect("the default layout has this panel");
// The Layers panel joins the Properties panel's group as its active tab
// The Layers panel joins the Properties panel's group as its active tab, ahead of Properties so that is what is left active
let join = WorkspaceMessage::MovePanelTab {
source_group: group_of(&handler, PanelType::Layers),
target_group: group_of(&handler, PanelType::Properties),
insert_index: 1,
insert_index: 0,
};
handler.process_message(join, &mut VecDeque::new(), context());
@@ -43,6 +43,14 @@ pub enum PreferencesMessage {
enabled: bool,
},
ToggleShowStoragePreferences,
/// The display name shown to peers in a live session.
UserName {
name: String,
},
/// Whether the other peers' pointers are drawn over a shared document.
ShowRemoteCursors {
enabled: bool,
},
#[cfg(target_os = "macos")]
VSync {
vsync: bool,
@@ -26,6 +26,15 @@ pub struct PreferencesMessageHandler {
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
pub show_storage_preferences: bool,
/// Who this person is across documents and devices, drawn once and kept; `0` until then.
/// Kept as a decimal string in the preferences file: a 64-bit number does not survive the browser's JSON store.
#[serde(with = "u64_as_string")]
#[cfg_attr(feature = "wasm", tsify(type = "string"))]
pub user_id: u64,
/// The display name peers see in a live session; empty means unnamed.
pub user_name: String,
/// Draw the other peers' pointers over a shared document.
pub show_remote_cursors: bool,
#[cfg(target_os = "macos")]
pub vsync: bool,
}
@@ -72,6 +81,9 @@ impl Default for PreferencesMessageHandler {
validate_storage_round_trip: false,
save_as_gdd: false,
show_storage_preferences: false,
user_id: 0,
user_name: String::new(),
show_remote_cursors: true,
#[cfg(target_os = "macos")]
vsync: false,
}
@@ -87,6 +99,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
// Management messages
PreferencesMessage::Load { preferences } => {
*self = preferences;
if self.user_id == 0 {
self.user_id = crate::application::generate_uuid();
}
responses.add(PortfolioMessage::EditorPreferences);
responses.add(PreferencesMessage::ModifyLayout {
@@ -149,6 +164,15 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
self.show_storage_preferences = !self.show_storage_preferences;
responses.add(MenuBarMessage::SendLayout);
}
PreferencesMessage::UserName { name } => {
self.user_name = name.trim().to_string();
responses.add(SyncMessage::RefreshPanel);
}
PreferencesMessage::ShowRemoteCursors { enabled } => {
self.show_remote_cursors = enabled;
responses.add(SyncMessage::RefreshPanel);
responses.add(OverlaysMessage::Draw);
}
#[cfg(target_os = "macos")]
PreferencesMessage::VSync { vsync } => {
self.vsync = vsync;
@@ -161,3 +185,26 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
advertise_actions!(PreferencesMessageDiscriminant;
);
}
/// A `u64` written as a decimal string, since the preferences pass through JSON in the browser, where a
/// number this wide loses precision or, as a BigInt, cannot be written at all. Reads a number too.
mod u64_as_string {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&value.to_string())
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Stored {
Text(String),
Number(u64),
}
match Stored::deserialize(deserializer)? {
Stored::Text(text) => text.parse().map_err(serde::de::Error::custom),
Stored::Number(number) => Ok(number),
}
}
}
+2
View File
@@ -33,8 +33,10 @@ pub use crate::messages::portfolio::document::resource::{ResourceMessage, Resour
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageDiscriminant, FailedDocumentsMessageHandler};
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
pub use crate::messages::portfolio::history::{HistoryMessage, HistoryMessageContext, HistoryMessageDiscriminant, HistoryMessageHandler};
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
pub use crate::messages::portfolio::workspace::{WorkspaceMessage, WorkspaceMessageContext, WorkspaceMessageDiscriminant, WorkspaceMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
@@ -7,6 +7,17 @@ pub struct ResourcesHandle {
inner: Arc<dyn ResourceStorage>,
}
impl ResourcesHandle {
pub fn new(inner: Arc<dyn ResourceStorage>) -> Self {
Self { inner }
}
/// The shared store behind this handle, for a consumer that needs to keep it alive itself.
pub fn storage(&self) -> Arc<dyn ResourceStorage> {
self.inner.clone()
}
}
impl LoadResource for ResourcesHandle {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
self.inner.load(hash)
@@ -381,6 +381,18 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
}
impl ToolMessageHandler {
/// The icon name of the active tool, for showing other peers what this one holds. The shapes share the
/// Shape tool, so the shelf's highlighted shape names the icon rather than the tool.
pub fn active_tool_icon(&self) -> String {
let tool_data = &self.tool_state.tool_data;
match tool_data.active_shape_type {
Some(ToolType::Line) => Line.icon_name(),
Some(ToolType::Rectangle) => Rectangle.icon_name(),
Some(ToolType::Ellipse) => Ellipse.icon_name(),
_ => tool_data.tools.get(&tool_data.active_tool_type).map(|tool| tool.icon_name()).unwrap_or_default(),
}
}
pub fn actions_with_preferences(&self, preferences: &PreferencesMessageHandler) -> ActionList {
let mut list = self.actions();
+2 -1
View File
@@ -3,7 +3,7 @@
import Editor from "/src/components/Editor.svelte";
import { createSubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
import { loadDemoArtwork } from "/src/utility-functions/network";
import { joinSessionFromUrl, loadDemoArtwork } from "/src/utility-functions/network";
import { operatingSystem } from "/src/utility-functions/platform";
import { initWasm } from "/src/utility-functions/wasm-loader";
import { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -29,6 +29,7 @@
});
await loadDemoArtwork(editor);
joinSessionFromUrl(editor);
});
onDestroy(() => {
+4
View File
@@ -12,6 +12,7 @@
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
import { createHistoryStore, destroyHistoryStore } from "/src/stores/history";
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
import { createTooltipStore, destroyTooltipStore } from "/src/stores/tooltip";
@@ -30,6 +31,7 @@
document: createDocumentStore(subscriptions),
fullscreen: createFullscreenStore(subscriptions),
nodeGraph: createNodeGraphStore(subscriptions),
history: createHistoryStore(subscriptions),
portfolio: createPortfolioStore(subscriptions, editor),
appWindow: createAppWindowStore(subscriptions),
colorPicker: createColorPickerStore(subscriptions),
@@ -59,6 +61,7 @@
destroyDocumentStore();
destroyFullscreenStore();
destroyNodeGraphStore();
destroyHistoryStore();
destroyPortfolioStore();
destroyAppWindowStore();
destroyColorPickerStore();
@@ -101,6 +104,7 @@
--color-f-white: #fff;
--color-error-red: #d6536e;
--color-warning-yellow: #d5aa43;
--color-session-green: #4f9a60;
--color-data-general: #cfcfcf;
--color-data-general-dim: #8a8a8a;
@@ -5,6 +5,7 @@
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Graph from "/src/components/views/Graph.svelte";
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
@@ -695,6 +696,10 @@
bind:this={viewport}
data-viewport
>
<!-- Other peers' pointers over the document, in viewport pixels -->
{#each $document.remoteCursors as cursor}
<RemoteCursor {cursor} />
{/each}
{#if !$appWindow.viewportHolePunch}
<svg class="artboards" style:width={canvasWidthCSS} style:height={canvasHeightCSS}>
{@html artworkSvg}
@@ -0,0 +1,399 @@
<script lang="ts">
import { getContext } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { HistoryStore } from "/src/stores/history";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
const editor = getContext<EditorWrapper>("editor");
const history = getContext<HistoryStore>("history");
// "3 min ago" for the recent past, a date for anything older; nothing when the retirer recorded no time.
function when(ms: number | undefined): string {
if (ms === undefined) return "";
const seconds = Math.max(0, Math.round((Date.now() - ms) / 1000));
if (seconds < 45) return "just now";
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.round(minutes / 60);
if (hours < 24) return `${hours} h ago`;
const days = Math.round(hours / 24);
if (days < 7) return days === 1 ? "yesterday" : `${days} days ago`;
return new Date(ms).toLocaleDateString();
}
function count(n: number, one: string, many: string): string {
return `${n} ${n === 1 ? one : many}`;
}
// The row whose name is being edited, and the row a tag is being typed for.
let renaming: string | undefined = undefined;
let tagging: string | undefined = undefined;
function commitName(id: string, label: string) {
editor.renameHistoryInteraction(id, label);
renaming = undefined;
}
function commitTag(id: string, tag: string) {
if (tag.trim()) editor.tagHistoryInteraction(id, tag, true);
tagging = undefined;
}
</script>
<LayoutCol class="history-panel">
{#if $history.following}
<LayoutRow class="following">
<TextLabel>Viewing a branch</TextLabel>
<TextButton label="Back to now" action={() => editor.followHistoryBranch(undefined)} />
</LayoutRow>
{/if}
<LayoutCol class="body" scrollableY={true}>
{#each $history.progress as row}
<div class="row progress">
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
<div class="text">
<span class="label">{row.label || (row.open ? "In progress" : "Waiting to enter history")}</span>
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{row.mine ? `${row.author} (you)` : row.author}</span>
· {count(row.ops, "change", "changes")}
· {row.open ? "in progress" : "not yet in history"}
</span>
</div>
</div>
{/each}
{#each $history.rows as row (row.id)}
<div class="row" class:head={row.head} class:undone={row.undone} class:abandoned={row.abandoned}>
<button
class="expand"
class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
></button>
<span class="rail"><span class="dot" style:background={row.color}></span></span>
<div class="text">
{#if renaming === row.id}
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
{:else}
<span class="label" class:named={row.named}>{row.label}</span>
{/if}
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{row.mine ? `${row.author} (you)` : row.author}</span>
{#if row.time}· {when(row.time)}{/if}
· {count(row.deltas, "change", "changes")}
</span>
{#if row.tags.length > 0 || tagging === row.id}
<span class="tags">
{#each row.tags as tag (tag)}
<span class="tag">{tag}<button class="remove" data-tooltip-label="Remove the tag" on:click={() => editor.tagHistoryInteraction(row.id, tag, false)}>×</button></span>
{/each}
{#if tagging === row.id}
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
{/if}
</span>
{/if}
{#if row.branches.length > 0}
<span class="branches">
{#each row.branches as branch (branch.id)}
<button class="branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
{/each}
</span>
{/if}
</div>
<span class="actions">
<button class="small" data-tooltip-label="Name this step" on:click={() => (renaming = renaming === row.id ? undefined : row.id)}>Name</button>
<button class="small" data-tooltip-label="Tag this step" on:click={() => (tagging = tagging === row.id ? undefined : row.id)}>Tag</button>
{#if row.undone}
<IconButton icon="HistoryRedo" size={16} tooltipLabel="Bring back" tooltipDescription="Redo up to and including this step." action={() => editor.historyBringBack(row.id)} />
{:else if row.abandoned}
<IconButton
icon="HistoryRedo"
size={16}
tooltipLabel="Bring back"
tooltipDescription="Do this step again on top of the current line."
action={() => editor.historyBringBack(row.id)}
/>
{:else}
{#if !row.head}
<IconButton
icon="HistoryUndo"
size={16}
tooltipLabel="Go back to here"
tooltipDescription={$history.session ? "Move everyone's document back to this step. The steps since stay as a branch." : "Undo up to this step."}
action={() => editor.historyGoBack(row.id)}
/>
{/if}
<IconButton
icon="Trash"
size={16}
tooltipLabel="Remove this step"
tooltipDescription="Take this step out and keep the ones after it."
action={() => editor.historyRemoveStep(row.id)}
/>
{/if}
</span>
{#if row.head}<span class="marker">Now</span>{/if}
{#if row.undone}<span class="marker">Undone</span>{/if}
{#if row.abandoned}<span class="marker">Branch</span>{/if}
</div>
{#if row.expanded}
{#each row.details as delta (delta.id)}
<div class="row delta" class:undone={row.undone}>
<span class="rail"><span class="tick"></span></span>
<div class="text">
<span class="label">{delta.label}</span>
<span class="meta">
<span class="author">{delta.author}</span>
{#if delta.time}· {when(delta.time)}{/if}
</span>
</div>
</div>
{/each}
{/if}
{/each}
{#if $history.more}
<div class="more">
<TextButton label="Show older" action={() => editor.loadMoreHistory()} />
</div>
{/if}
{#if $history.rows.length === 0 && $history.progress.length === 0}
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
{/if}
</LayoutCol>
</LayoutCol>
<style lang="scss">
.history-panel {
flex-grow: 1;
padding: 4px 0;
.following {
flex: 0 0 auto;
align-items: center;
justify-content: space-between;
padding: 0 8px 4px 8px;
}
.row {
display: flex;
align-items: center;
min-height: 32px;
padding: 2px 8px 2px 4px;
gap: 6px;
&.head {
background: var(--color-3-darkgray);
}
&.undone,
&.abandoned {
.rail,
.text {
opacity: 0.6;
}
}
&.delta {
min-height: 24px;
padding-left: 28px;
font-size: 11px;
}
.actions {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
visibility: hidden;
.small {
font-size: 11px;
line-height: 14px;
padding: 0 4px;
border: none;
border-radius: 2px;
background: var(--color-4-dimgray);
color: var(--color-c-brightgray);
cursor: pointer;
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
&:hover .actions {
visibility: visible;
}
.expand {
flex: 0 0 auto;
width: 16px;
height: 16px;
padding: 0;
border: none;
background: none;
position: relative;
cursor: pointer;
&::after {
content: "";
position: absolute;
left: 5px;
top: 4px;
border: 4px solid transparent;
border-left: 5px solid var(--color-8-uppergray);
}
&.expanded::after {
left: 3px;
top: 6px;
border: 4px solid transparent;
border-top: 5px solid var(--color-8-uppergray);
}
&:hover::after {
border-left-color: var(--color-e-nearwhite);
}
&.expanded:hover::after {
border-left-color: transparent;
border-top-color: var(--color-e-nearwhite);
}
}
.rail {
flex: 0 0 12px;
display: flex;
justify-content: center;
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
&.hollow {
background: none;
border: 2px solid;
width: 6px;
height: 6px;
}
}
.tick {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--color-6-lowergray);
}
}
.text {
flex: 1 1 0;
min-width: 0;
display: flex;
flex-direction: column;
line-height: 16px;
.label {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.meta {
color: var(--color-a-softgray);
font-size: 11px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.anonymous {
font-style: italic;
}
}
.label.named {
font-weight: 600;
}
.tags {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
margin-top: 2px;
.tag {
display: inline-flex;
align-items: center;
gap: 2px;
font-size: 11px;
line-height: 14px;
padding: 0 2px 0 4px;
border-radius: 2px;
background: var(--color-accent-hover);
color: var(--color-f-white);
.remove {
border: none;
background: none;
color: inherit;
padding: 0 2px;
cursor: pointer;
line-height: 14px;
}
}
}
.branches {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 2px;
.branch {
font-size: 11px;
line-height: 14px;
padding: 0 4px;
border: none;
border-radius: 2px;
background: var(--color-4-dimgray);
color: var(--color-c-brightgray);
cursor: pointer;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
}
.marker {
flex: 0 0 auto;
font-size: 10px;
line-height: 14px;
padding: 0 4px;
border-radius: 2px;
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
.more {
display: flex;
justify-content: center;
padding: 8px;
}
}
</style>
@@ -0,0 +1,22 @@
<script lang="ts">
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { sessionPanelLayout } from "/src/stores/portfolio";
</script>
<LayoutCol class="session-panel">
<LayoutCol class="body" scrollableY={true}>
<WidgetLayout layout={$sessionPanelLayout} layoutTarget="SessionPanel" />
</LayoutCol>
</LayoutCol>
<style lang="scss">
.session-panel {
flex-grow: 1;
padding: 4px 8px;
.widget-span:has(.text-label.multiline) {
flex: 1 1 100%;
}
}
</style>
@@ -5,6 +5,7 @@
import NodeCatalog from "/src/components/floating-menus/NodeCatalog.svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
@@ -862,6 +863,11 @@
</div>
</div>
<!-- Other peers' pointers over the graph, in viewport pixels like the box selection -->
{#each $nodeGraph.remoteCursors as cursor}
<RemoteCursor {cursor} />
{/each}
<!-- Box selection widget -->
{#if $nodeGraph.box}
<div
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more