From d90eacdee6d7fdf3cf0346671818af69d2bd2fea Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Tue, 29 Sep 2026 14:37:00 +0000 Subject: [PATCH] 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 --- document/format/src/export.rs | 3 + document/format/src/layout.rs | 5 + document/format/src/lib.rs | 20 ++- document/format/src/manifest.rs | 10 +- document/format/src/network.rs | 18 ++- document/format/src/persist.rs | 37 ++++- document/format/tests/history_metadata.rs | 109 +++++++++++++ document/graph-storage/src/attributes/attr.rs | 3 + document/graph-storage/src/crdt.rs | 5 + .../graph-storage/src/history_metadata.rs | 150 ++++++++++++++++++ document/graph-storage/src/lib.rs | 2 + document/graph-storage/src/session.rs | 40 ++++- .../graph-storage/src/tests/bookkeeping.rs | 2 + document/peer-transport/src/packet.rs | 8 +- document/peer-transport/src/replica.rs | 26 ++- document/peer-transport/src/target.rs | 12 +- .../portfolio/sync/sync_message_handler.rs | 55 +++++-- node-graph/graphene-cli/src/repl.rs | 1 + 18 files changed, 478 insertions(+), 28 deletions(-) create mode 100644 document/format/tests/history_metadata.rs create mode 100644 document/graph-storage/src/history_metadata.rs diff --git a/document/format/src/export.rs b/document/format/src/export.rs index bd41ee9bc6..6bd83d567c 100644 --- a/document/format/src/export.rs +++ b/document/format/src/export.rs @@ -158,6 +158,9 @@ impl Gdd { 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() { + sink.write_entry(&io::path_for(self.layout.metadata_basename(), codecs.metadata), &codecs.metadata.write_single(&self.metadata)?)?; + } let working_copy_hashes: std::collections::HashSet = self.resource_hashes().await?.into_iter().collect(); diff --git a/document/format/src/layout.rs b/document/format/src/layout.rs index cd08fe2d17..6594da30a7 100644 --- a/document/format/src/layout.rs +++ b/document/format/src/layout.rs @@ -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" } diff --git a/document/format/src/lib.rs b/document/format/src/lib.rs index efa647d4f5..86da699570 100644 --- a/document/format/src/lib.rs +++ b/document/format/src/lib.rs @@ -17,7 +17,7 @@ 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, UserId}; +use document_graph_storage::{Delta, HistoryMetadata, HotOp, PeerId, Registry, Session, UserId}; #[cfg(feature = "conversion")] use graphene_resource::LoadResource; use graphene_resource::{ResourceHash, ResourceStorage}; @@ -57,6 +57,7 @@ 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; +pub const DEFAULT_METADATA_CODEC: Codec = Codec::Json; pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack; pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames; pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames; @@ -80,6 +81,12 @@ pub struct Gdd { /// 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, /// 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, @@ -119,6 +126,7 @@ pub(crate) struct PendingPersist { pub(crate) history: bool, pub(crate) hot_log: bool, pub(crate) snapshot: bool, + pub(crate) metadata: bool, } impl Clone for Gdd { @@ -129,6 +137,8 @@ impl Clone for Gdd { 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, @@ -194,6 +204,10 @@ impl Gdd { true => io::read_single(&working, layout.session_basename(), codecs.session).await?, false => SessionState::default(), }; + let metadata: HistoryMetadata = match io::exists(&working, layout.metadata_basename(), codecs.metadata).await { + true => io::read_single(&working, layout.metadata_basename(), codecs.metadata).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; @@ -235,6 +249,8 @@ impl Gdd { 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, @@ -271,6 +287,8 @@ impl Gdd { 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")] diff --git a/document/format/src/manifest.rs b/document/format/src/manifest.rs index 3d12da4b90..08701a9343 100644 --- a/document/format/src/manifest.rs +++ b/document/format/src/manifest.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use crate::Codec; -use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC, DEFAULT_SESSION_CODEC}; +use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_METADATA_CODEC, DEFAULT_REGISTRY_CODEC, DEFAULT_SESSION_CODEC}; /// Magic string carried in [`Manifest::format`] to identify a `.gdd` document. pub const FORMAT_MAGIC: &str = "gdd"; @@ -21,6 +21,13 @@ pub struct PayloadCodecs { pub history: Codec, pub hot_log: Codec, pub session: Codec, + /// Added after the first working copies were written, so a manifest without it reads as the default. + #[serde(default = "default_metadata_codec")] + pub metadata: Codec, +} + +fn default_metadata_codec() -> Codec { + DEFAULT_METADATA_CODEC } impl Default for PayloadCodecs { @@ -30,6 +37,7 @@ impl Default for PayloadCodecs { history: DEFAULT_HISTORY_CODEC, hot_log: DEFAULT_HOT_LOG_CODEC, session: DEFAULT_SESSION_CODEC, + metadata: DEFAULT_METADATA_CODEC, } } } diff --git a/document/format/src/network.rs b/document/format/src/network.rs index 4b940ad8f8..754c65c794 100644 --- a/document/format/src/network.rs +++ b/document/format/src/network.rs @@ -5,7 +5,7 @@ use std::collections::HashSet; -use document_graph_storage::{Delta, HeadMove, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredHotOps, Rev, Session, Touched, UserId}; +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; @@ -185,6 +185,7 @@ impl SyncTarget for Gdd { history: true, hot_log: true, snapshot: true, + metadata: false, }; Ok(()) } @@ -282,6 +283,18 @@ impl SyncTarget for Gdd { Ok(()) } + fn metadata(&self) -> HistoryMetadata { + self.metadata.clone() + } + + fn absorb_metadata(&mut self, remote: &HistoryMetadata) -> Result { + let changed = self.metadata.merge(remote); + if changed { + self.pending_persist.metadata = true; + } + Ok(changed) + } + fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> { let touched = self.session.retract_hot_ops(ops); self.remote_changes.touched.extend(touched); @@ -338,6 +351,9 @@ impl SyncTarget for Gdd { self.persist_registry_snapshot()?; self.persist_session_state()?; } + if pending.metadata { + self.persist_metadata()?; + } Ok(()) } diff --git a/document/format/src/persist.rs b/document/format/src/persist.rs index c8f2d2964b..a1f4133fb1 100644 --- a/document/format/src/persist.rs +++ b/document/format/src/persist.rs @@ -6,7 +6,7 @@ use document_container::AsyncContainer; #[cfg(feature = "conversion")] use document_graph_storage::NodeMetadataSource; -use document_graph_storage::{Delta, HotOp, RegistryDelta, Rev, TimeStamp, UserId}; +use document_graph_storage::{Delta, HistoryMetadata, HotOp, RegistryDelta, Rev, TimeStamp, UserId, WallStamp}; #[cfg(feature = "conversion")] use graphene_resource::ResourceStorage; @@ -216,6 +216,33 @@ impl Gdd { Ok(()) } + /// 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 { + let stamp = WallStamp { + ms: wall_ms.max(0.) as u64, + peer: self.session.peer(), + }; + if !self.metadata.set_user_attribute(user, key, value, stamp) { + return Ok(false); + } + self.persist_metadata()?; + #[cfg(feature = "network")] + if let Some(replica) = &mut self.network { + replica.send_metadata(&self.metadata)?; + } + Ok(true) + } + + pub(crate) fn persist_metadata(&mut self) -> Result<(), Error> { + io::write_single(&self.working, self.layout.metadata_basename(), self.manifest.codecs.metadata, &self.metadata) + } + pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> { let state = SessionState { peer_id: self.session.peer(), @@ -389,6 +416,8 @@ impl Gdd { /// 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, 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. @@ -467,6 +496,12 @@ impl Gdd { /// 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 diff --git a/document/format/tests/history_metadata.rs b/document/format/tests/history_metadata.rs new file mode 100644 index 0000000000..7fe5f71ae9 --- /dev/null +++ b/document/format/tests/history_metadata.rs @@ -0,0 +1,109 @@ +// 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, TimeStamp, UserId, 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 (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")); + }); +} + +#[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)); + } + }); +} diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index 485f04dfe2..d698b8fd3d 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -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"; } diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index f06d865881..cefa3fb9d8 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -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 { + 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 { diff --git a/document/graph-storage/src/history_metadata.rs b/document/graph-storage/src/history_metadata.rs new file mode 100644 index 0000000000..4fa5d8ddef --- /dev/null +++ b/document/graph-storage/src/history_metadata.rs @@ -0,0 +1,150 @@ +//! What people say about a document's history, kept beside it rather than in it: who its users are, and +//! later what its steps are called and which are tagged. None of it is folded, so moving the head never +//! changes it and stating it never rewrites a delta. Every fact carries a wall-clock stamp and the last +//! writer wins, which makes the whole record a state that merges by taking the newer fact per key, in any +//! order and any number of times. + +use crate::ids::{PeerId, 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, +} + +/// One stated value with its stamp. +#[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, +} + +/// 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 record kept beside a document's history. Users are kept sorted by id so two copies holding the +/// same facts serialize alike. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct HistoryMetadata { + #[serde(default)] + pub users: Vec, +} + +impl HistoryMetadata { + pub fn is_empty(&self) -> bool { + self.users.is_empty() + } + + 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()) + } + + /// 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 whether anything changed. + pub fn set_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> bool { + let record = self.user_record_mut(user); + if let Some(existing) = record.attributes.get(key) { + if existing.value == value { + return false; + } + if stamp <= existing.stamp { + stamp.ms = existing.stamp.ms + 1; + } + } + record.attributes.insert(key.to_string(), Fact { value, stamp }); + true + } + + /// Take on another copy's facts: for every key, the newer stamp wins. Returns whether anything changed. + pub fn merge(&mut self, other: &Self) -> bool { + let mut changed = false; + for theirs in &other.users { + let record = self.user_record_mut(theirs.user); + for (key, fact) in &theirs.attributes { + if record.attributes.get(key).is_none_or(|mine| fact.stamp > mine.stamp) { + record.attributes.insert(key.clone(), fact.clone()); + changed = true; + } + } + } + changed + } + + fn user_record_mut(&mut self, user: UserId) -> &mut UserRecord { + 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] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stamp(ms: u64, peer: u64) -> WallStamp { + WallStamp { ms, peer: PeerId(peer) } + } + + #[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))); + assert!(b.set_user_attribute(UserId(1), user_attr::NAME, "Ada L.".into(), stamp(20, 2))); + + let mut ab = a.clone(); + assert!(ab.merge(&b)); + let mut ba = b.clone(); + assert!(!ba.merge(&a)); + assert_eq!(ab, ba); + assert_eq!(ab.user_name(UserId(1)), Some("Ada L.")); + assert!(!ab.merge(&b), "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)); + assert!(record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(5, 1))); + assert_eq!(record.user_name(UserId(1)), Some("Countess")); + assert_eq!(record.user_attribute(UserId(1), user_attr::NAME).unwrap().stamp.ms, 101); + assert!(!record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(500, 1)), "the same value is no change"); + } + + #[test] + fn an_empty_name_counts_as_unnamed_and_users_stay_sorted() { + 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)); + assert_eq!(record.user_name(UserId(9)), None); + assert_eq!(record.users.iter().map(|record| record.user).collect::>(), vec![UserId(3), UserId(9)]); + } +} diff --git a/document/graph-storage/src/lib.rs b/document/graph-storage/src/lib.rs index 7fc21cab83..53e2b2f66b 100644 --- a/document/graph-storage/src/lib.rs +++ b/document/graph-storage/src/lib.rs @@ -5,6 +5,7 @@ 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; @@ -23,6 +24,7 @@ pub use attributes::*; pub use crdt::*; pub use document::*; pub use history::History; +pub use history_metadata::{Fact, HistoryMetadata, UserRecord, WallStamp, user_attr}; pub use ids::*; pub use model::*; pub use registry::*; diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 1748994e67..c5fb07ff6c 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -410,10 +410,9 @@ impl Session { 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)?; - if original.is_interaction_end() - && let Some(&rev) = revs.last() - { - self.document.history.mark_interaction_end(rev, original.timestamp); + // 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())); } @@ -489,16 +488,23 @@ impl Session { /// Returns the new revs, for an ordinary retirement-style broadcast. pub fn restore_interaction(&mut self, dropped: Rev) -> Result, CrdtError> { let base = self.interaction_start_parent(dropped).ok_or(CrdtError::NotUndoable(dropped))?; - let mut ops = Vec::new(); + 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))?; + let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone(); current = delta.parent; - ops.push((delta.kind.clone(), Some(delta.timestamp))); + originals.push(delta); } - ops.reverse(); + 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); } @@ -810,6 +816,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. diff --git a/document/graph-storage/src/tests/bookkeeping.rs b/document/graph-storage/src/tests/bookkeeping.rs index bc42499b33..2f407ce6f2 100644 --- a/document/graph-storage/src/tests/bookkeeping.rs +++ b/document/graph-storage/src/tests/bookkeeping.rs @@ -357,6 +357,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() { 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::>()) .expect("merge"); @@ -368,6 +369,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() { 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"); diff --git a/document/peer-transport/src/packet.rs b/document/peer-transport/src/packet.rs index f16315b430..ea73154786 100644 --- a/document/peer-transport/src/packet.rs +++ b/document/peer-transport/src/packet.rs @@ -1,4 +1,4 @@ -use document_graph_storage::{Delta, HeadMove, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, UserId}; +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. @@ -61,6 +61,9 @@ pub enum SyncPacket { Cursor { position: Option, }, + /// 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 @@ -84,6 +87,9 @@ pub struct SyncPayload { /// to the same room by opening its own copy later. #[serde(default)] pub document_id: Option, + /// 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` diff --git a/document/peer-transport/src/replica.rs b/document/peer-transport/src/replica.rs index 2f4759e1bf..9d3a9b0f1d 100644 --- a/document/peer-transport/src/replica.rs +++ b/document/peer-transport/src/replica.rs @@ -1,7 +1,7 @@ use crate::packet::{Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload}; use crate::target::{SyncTarget, TargetError}; use crate::transport::{Transport, TransportEvent, TransportPeerId}; -use document_graph_storage::{Delta, HeadMove, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId}; +use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId}; use std::collections::{HashMap, HashSet}; pub enum Event { @@ -25,6 +25,8 @@ pub enum Event { CursorMoved { peer: PeerId, }, + /// Something on record about the history's users changed, from a peer or a sync. + MetadataChanged, /// The guest has applied the host's state. Synced, /// Remote ops changed the target. @@ -292,6 +294,14 @@ impl Replica { self.transport.broadcast_except(None, &SyncPacket::Profile { name: self.name.clone() }) } + /// Tell the room what this peer has on record about the history, after it changed here. + pub fn send_metadata(&mut self, metadata: &HistoryMetadata) -> Result<(), PacketError> { + if self.peers.is_empty() { + return Ok(()); + } + self.transport.broadcast_except(None, &SyncPacket::Metadata(metadata.clone())) + } + /// Tell the room where this peer's pointer is, `None` once it left the viewport. The /// caller coalesces: one call per frame at most, and none when nothing moved. pub fn send_cursor(&mut self, position: Option) -> Result<(), PacketError> { @@ -714,6 +724,7 @@ impl Replica { retired: target.retired_marks(), retracted: target.retracted_marks(), document_id: target.document_id(), + metadata: target.metadata(), }; log::info!("Join handshake: sync answered with {} deltas and {} hot ops", sync.deltas.len(), sync.hot_log.len()); self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?; @@ -746,6 +757,14 @@ impl Replica { } target.absorb_retired_marks(&sync.retired)?; target.absorb_retracted_marks(&sync.retracted)?; + if target.absorb_metadata(&sync.metadata)? { + events.push(Event::MetadataChanged); + } + // What this copy had on record, a name given while apart say, reaches the room the same way. + let own = target.metadata(); + if !own.is_empty() { + self.transport.broadcast_except(None, &SyncPacket::Metadata(own))?; + } self.deferred.extend(target.apply_remote_hot_ops(held)?); self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?); @@ -816,6 +835,11 @@ impl Replica { events.push(Event::CursorMoved { peer: remote.peer }); } } + SyncPacket::Metadata(remote) => { + if target.absorb_metadata(&remote)? { + events.push(Event::MetadataChanged); + } + } SyncPacket::ResourceRequest(hashes) => { for hash in hashes { match target.resource_bytes(hash) { diff --git a/document/peer-transport/src/target.rs b/document/peer-transport/src/target.rs index 9c8ae59aca..c9b38f9e49 100644 --- a/document/peer-transport/src/target.rs +++ b/document/peer-transport/src/target.rs @@ -1,4 +1,4 @@ -use document_graph_storage::{Delta, HeadMove, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, Session}; +use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, Session}; use std::collections::HashSet; pub type TargetError = Box; @@ -30,6 +30,16 @@ pub trait SyncTarget { /// 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 { + Ok(false) + } + /// Replace all state with the given retired state. fn load(&mut self, registry: Registry, history: Vec, head: Option) -> Result<(), TargetError>; /// Must be idempotent on structural ops: a buffered op may already be reflected by the sync. diff --git a/editor/src/messages/portfolio/sync/sync_message_handler.rs b/editor/src/messages/portfolio/sync/sync_message_handler.rs index cda4e8e7e2..bc2a5f1dc3 100644 --- a/editor/src/messages/portfolio/sync/sync_message_handler.rs +++ b/editor/src/messages/portfolio/sync/sync_message_handler.rs @@ -6,7 +6,7 @@ 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::{PeerId, UserId}; +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}; @@ -197,6 +197,11 @@ impl MessageHandler> for SyncMessageHandler { 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() @@ -276,7 +281,7 @@ impl MessageHandler> for SyncMessageHandler log::info!("Session role is now {role:?}"); refresh_session_views(responses); } - Event::PeerJoined { .. } | Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses), + Event::PeerJoined { .. } | Event::PeerLeft { .. } | Event::ProfileChanged { .. } | Event::MetadataChanged => refresh_session_views(responses), // Cursors are gathered afresh below every poll, so a move needs no action of its own. Event::CursorMoved { .. } => {} } @@ -630,7 +635,8 @@ fn session_panel_layout(documents: &HashMap, false => user_name.to_string(), }; groups.push(peer_row(&format!("{me} (you)"), user_name.is_empty())); - groups.extend(peers.iter().map(|remote| peer_row(&display_name(remote), remote.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) } @@ -640,6 +646,19 @@ 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) { @@ -678,7 +697,7 @@ fn document_cursors(document: &DocumentMessageHandler, preferences: &Preferences .iter() .filter_map(|remote| { let cursor = remote.cursor.as_ref()?; - matches!(cursor.space, CursorSpace::Document).then(|| remote_cursor(remote, cursor, to_viewport)) + matches!(cursor.space, CursorSpace::Document).then(|| remote_cursor(remote, cursor, to_viewport, gdd.metadata())) }) .collect() } @@ -696,21 +715,21 @@ fn graph_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMes .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)) + (*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) -> FrontendRemoteCursor { +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), - anonymous: remote.name.is_empty(), - color: peer_color(remote.peer), + name: display_name(remote, metadata), + anonymous: is_anonymous(remote, metadata), + color: user_color(remote.user), tool: cursor.tool.clone(), } } @@ -724,13 +743,22 @@ fn shown_network(document: &DocumentMessageHandler) -> Vec { document.breadcrumb_network_path().iter().map(|id| id.0).collect() } -fn display_name(remote: &RemotePeer) -> String { +/// 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() +} + /// 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. fn anonymous_name(user: UserId) -> String { @@ -808,9 +836,10 @@ const ANONYMOUS_ANIMALS: [&str; 64] = [ /// How long a document whose transport went down waits before it tries its room again. const RECONNECT_AFTER_MS: f64 = 3_000.; -/// A colour for a peer derived from its id, so every peer sees the same one without anything on the wire. -fn peer_color(peer: PeerId) -> String { - let hue = (peer.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) % 360; +/// 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. +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()); diff --git a/node-graph/graphene-cli/src/repl.rs b/node-graph/graphene-cli/src/repl.rs index bed558c332..cd31a47687 100644 --- a/node-graph/graphene-cli/src/repl.rs +++ b/node-graph/graphene-cli/src/repl.rs @@ -18,6 +18,7 @@ pub fn report(event: &Event) { Event::RoleChanged { role } => println!("role is now {role:?}"), Event::ProfileChanged { peer } => println!("peer {peer:?} announced a name"), Event::CursorMoved { .. } => {} + Event::MetadataChanged => println!("the record of the document's users changed"), Event::Synced => println!("synced"), Event::Changed => println!("document changed"), Event::ResourceReceived { hash, bytes } => println!("received resource {hash} ({} bytes)", bytes.len()),