From 2a475153b715c954935ae46d3773ffbf3d007f03 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 04:05:41 +0000 Subject: document: where a document stands, and a peer, is the document's to compare document::passing: a Mark, where a document stood, by which what changed since and the node's own units since are told (changed_since, own_since: the change publisher, the sync worker); and of where a peer says it stands, what the document lacks, whether the peer holds what the document held, a pull of what is lacking, and what it has counting as sent no more (lacking, peer_holds, pull, heard: the relay, keepalives). The published stamp gives its summary and its mark. --- src/document/passing.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++- src/document/replica.rs | 12 ++++++ src/document/sync.rs | 5 +++ src/swarm/changes.rs | 37 ++++-------------- src/swarm/peer/keepalive.rs | 25 +++++------- src/swarm/relay.rs | 27 +++++-------- src/swarm/sync.rs | 20 +++------- src/transport/mod.rs | 6 +++ 8 files changed, 148 insertions(+), 79 deletions(-) (limited to 'src') diff --git a/src/document/passing.rs b/src/document/passing.rs index 10b888d..0b9a3dd 100644 --- a/src/document/passing.rs +++ b/src/document/passing.rs @@ -11,7 +11,7 @@ use super::replica::Replica; use super::signatures; use super::sync::{Received, SyncSession}; use crate::swarm::throughput::SyncBytes; -use crate::transport::{DeltaSignatures, DeltaSpec, SyncBody, SyncPayload}; +use crate::transport::{DeltaSignatures, DeltaSpec, HeadsSummary, SyncBody, SyncPayload}; /// What goes to a peer next. pub(crate) struct Outgoing { @@ -454,3 +454,96 @@ pub(crate) fn take_bulk( }), ) } + +/// Where a document stood, kept to tell later what came since (`mark`): its heads then. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Mark(Vec); + +impl Mark { + /// Standing at `heads`. + pub(super) fn at(heads: &[ChangeHash]) -> Mark { + Mark(heads.to_vec()) + } +} + +/// Where the document `replica` holds stands now. +pub(crate) fn mark(replica: &Replica) -> Mark { + Mark(replica.heads().to_vec()) +} + +/// What changed in the document `replica` holds since `since`: where it stands now, the +/// paths that changed, and those of them where writes at once made a conflict. After +/// another document took its place (an epoch switch, a rejoin, a drop), the root alone, +/// which everything is within. +pub(crate) fn changed_since( + replica: &Replica, + since: &Mark, +) -> (Mark, Vec>, Vec>) { + let now = mark(replica); + if now == *since { + return (now, Vec::new(), Vec::new()); + } + if !super::changes::missing(&replica.doc, &since.0).is_empty() { + return (now, vec![Vec::new()], Vec::new()); + } + let mut paths = Vec::new(); + let mut conflicts = Vec::new(); + for changed in replica.changed_since(&since.0, super::store::InLists::Index) { + if changed.conflict { + conflicts.push(changed.path.clone()); + } + paths.push(changed.path); + } + (now, paths, conflicts) +} + +/// The units the node `node` made itself since `seen` (which becomes where the document +/// stands now), if what came since is a write of its own; None if none of it is (a +/// change fetched as a blob), or another document took its place meanwhile. +pub(crate) fn own_since( + replica: &Replica, + seen: &mut Mark, + node: &str, +) -> Option> { + let before = std::mem::replace(seen, mark(replica)); + if !super::changes::holds_all(&replica.doc, &before.0) { + return None; + } + super::changes::since(&replica.doc, &before.0) + .authors + .into_iter() + .find(|(author, _)| author == node) + .map(|(_, hashes)| hashes.into_iter().map(Into::into).collect()) +} + +/// Of where a peer says it stands (`theirs`), what the document lacks: with a digest, +/// of the sample it lists. +pub(crate) fn lacking(doc: &super::Document, theirs: &HeadsSummary) -> Vec { + super::changes::missing(doc, theirs.listed()) + .into_iter() + .map(Into::into) + .collect() +} + +/// Whether a peer standing at `theirs` holds all the document held at `ours`. +pub(crate) fn peer_holds(doc: &super::Document, theirs: &HeadsSummary, ours: &Mark) -> bool { + super::changes::covers(doc, theirs.listed(), &ours.0) +} + +/// Has the session ask the peer for what the document lacks of where it stands +/// (`theirs`, `lacking` of it): all of it, where the peer listed all; else what is +/// known to lack. +pub(crate) fn pull(session: &mut SyncSession, theirs: &HeadsSummary, lacking: Vec) { + session.pull_from(match theirs.heads() { + Some(heads) => heads.to_vec(), + None => lacking.into_iter().map(Into::into).collect(), + }); +} + +/// A peer said where it stands, outside a session's messages: what it has counts as +/// sent to it no more (`SyncSession::heard_heads`). Nothing where it gave a digest. +pub(crate) fn heard(session: &mut SyncSession, doc: &super::Document, theirs: &HeadsSummary) { + if let Some(heads) = theirs.heads() { + session.heard_heads(doc, heads); + } +} diff --git a/src/document/replica.rs b/src/document/replica.rs index a6eaade..092878b 100644 --- a/src/document/replica.rs +++ b/src/document/replica.rs @@ -166,6 +166,18 @@ pub(crate) struct Stamp { pub(crate) heads: Arc<[ChangeHash]>, } +impl Stamp { + /// Where the document stands, as a keepalive says it. + pub(crate) fn summary(&self) -> crate::transport::HeadsSummary { + crate::transport::HeadsSummary::of(self.heads.to_vec()) + } + + /// Where the document stands, to tell later what came since. + pub(crate) fn mark(&self) -> super::passing::Mark { + super::passing::Mark::at(&self.heads) + } +} + impl Replica { pub(crate) fn new(epoch: Epoch, doc: Document) -> Self { let (stamp, _) = watch::channel(Stamp { diff --git a/src/document/sync.rs b/src/document/sync.rs index e1caaef..805d1f9 100644 --- a/src/document/sync.rs +++ b/src/document/sync.rs @@ -101,6 +101,11 @@ impl Received { })) } + /// Where the sender says it stands, as a keepalive would say it. + pub(crate) fn stands(&self) -> crate::transport::HeadsSummary { + crate::transport::HeadsSummary::of(self.heads().to_vec()) + } + /// The sender's heads, as it says. pub(crate) fn heads(&self) -> &[crate::document::ChangeHash] { &self.0.heads diff --git a/src/swarm/changes.rs b/src/swarm/changes.rs index a04ce7d..fd0d32a 100644 --- a/src/swarm/changes.rs +++ b/src/swarm/changes.rs @@ -7,56 +7,35 @@ use std::sync::Arc; use tracing::{info, warn}; -use crate::document::changes; -use crate::document::store::{ChangeSet, InLists}; +use crate::document::store::ChangeSet; use crate::state::AppState; pub(crate) async fn run_change_publisher(state: AppState) { let mut changed = state.change_tx.subscribe(); - // The replica's heads (sorted, as of its last refresh: every change refreshes them). - let mut last_heads = state.doc.read().await.heads().to_vec(); + // Where the document stood when last looked at. + let mut last = crate::document::passing::mark(&*state.doc.read().await); info!("Starting change publisher"); while changed.changed().await.is_ok() { - let before = last_heads.clone(); + let before = last.clone(); let doc = Arc::clone(&state.doc); let looked = tokio::task::spawn_blocking(move || { - let replica = doc.blocking_read(); - let heads = replica.heads().to_vec(); - if heads == before { - return (heads, Vec::new(), Vec::new()); - } - - // After an epoch switch the previous heads belong to the old document: - // report the root as changed, which every stream is related to. - if !changes::missing(&replica.doc, &before).is_empty() { - return (heads, vec![Vec::new()], Vec::new()); - } - - let mut paths = Vec::new(); - let mut conflicts = Vec::new(); - for changed in replica.changed_since(&before, InLists::Index) { - if changed.conflict { - conflicts.push(changed.path.clone()); - } - paths.push(changed.path); - } - (heads, paths, conflicts) + crate::document::passing::changed_since(&doc.blocking_read(), &before) }) .await; - let (heads, paths, conflicts) = match looked { + let (now, paths, conflicts) = match looked { Ok(looked) => looked, // The runtime is shutting down (the node stops): nothing to publish to. Err(error) if error.is_cancelled() => return, Err(error) => std::panic::resume_unwind(error.into_panic()), }; - if heads == last_heads { + if now == last { continue; } - last_heads = heads; + last = now; for path in &conflicts { warn!(path = ?path, "Concurrent writes produced a conflict"); diff --git a/src/swarm/peer/keepalive.rs b/src/swarm/peer/keepalive.rs index 51ff14a..72ab033 100644 --- a/src/swarm/peer/keepalive.rs +++ b/src/swarm/peer/keepalive.rs @@ -180,11 +180,7 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta // and reading them doesn't wait for a sync message being applied. let (heads, epoch, epoch_seq) = { let stamp = state.stamp.borrow(); - ( - transport::HeadsSummary::of(stamp.heads.to_vec()), - stamp.epoch, - stamp.epoch_seq, - ) + (stamp.summary(), stamp.epoch, stamp.epoch_seq) }; let syncs_with_you = match state.get_peer_state(peer).await { Some(peer_state) => peer_state.lock().await.syncs_on(epoch), @@ -221,14 +217,15 @@ pub(super) async fn status_received(state: &AppState, peer: &str) { /// A STATUS, or a STATUS_REPLY, said the peer's heads: what it has counts as sent to it /// no more (`SyncSession::heard_heads`). Off the consumer: it takes the document's lock. pub(super) fn heard_heads(state: &AppState, peer: &str, remote: &transport::Status) { - let Some(heads) = remote.heads.heads() else { - return; - }; - if heads.is_empty() || remote.epoch != state.local_epoch() { + if remote.heads.heads().is_none_or(<[_]>::is_empty) || remote.epoch != state.local_epoch() { return; } - let (state, peer, heads, epoch) = - (state.clone(), peer.to_owned(), heads.to_vec(), remote.epoch); + let (state, peer, theirs, epoch) = ( + state.clone(), + peer.to_owned(), + remote.heads.clone(), + remote.epoch, + ); tokio::spawn(async move { let Some(peer_state) = state.get_peer_state(&peer).await else { return; @@ -238,11 +235,7 @@ pub(super) fn heard_heads(state: &AppState, peer: &str, remote: &transport::Stat if replica.epoch != epoch { return; } - peer_state - .lock() - .await - .sync - .heard_heads(&replica.doc, &heads); + crate::document::passing::heard(&mut peer_state.lock().await.sync, &replica.doc, &theirs); }); } diff --git a/src/swarm/relay.rs b/src/swarm/relay.rs index 560a41e..76428f0 100644 --- a/src/swarm/relay.rs +++ b/src/swarm/relay.rs @@ -274,11 +274,10 @@ async fn unreached( 1 => senders.iter().next().cloned(), _ => None, }; - let (epoch, heads) = { + let (epoch, ours, stood) = { let stamp = state.stamp.borrow(); - (stamp.epoch, stamp.heads.to_vec()) + (stamp.epoch, stamp.summary(), stamp.mark()) }; - let ours = HeadsSummary::of(heads.clone()); // What each neighbour said it has. let mut said = Vec::new(); for (peer, peer_state) in state.peers_snapshot().await { @@ -305,7 +304,7 @@ async fn unreached( .filter(|(_, last)| { !last.as_ref().is_some_and(|theirs| { *theirs == ours - || crate::document::changes::covers(&replica.doc, theirs.listed(), &heads) + || crate::document::passing::peer_holds(&replica.doc, theirs, &stood) }) }) .map(|(peer, _)| peer) @@ -326,7 +325,7 @@ pub(crate) struct Pulling { /// Whether we lack any of `heads` (with a digest, any of the sample it lists). pub(crate) async fn lacks(state: &AppState, heads: &HeadsSummary) -> bool { let replica = state.doc.read().await; - !crate::document::changes::missing(&replica.doc, heads.listed()).is_empty() + !crate::document::passing::lacking(&replica.doc, heads).is_empty() } /// A STATUS from `peer` (a keepalive's, or an announcement): if it has heads we lack, @@ -337,14 +336,12 @@ pub(crate) async fn lacks(state: &AppState, heads: &HeadsSummary) -> bool { /// was missed. One wait per peer: a STATUS that comes meanwhile is the one judged at the /// end (`PeerState::pull_pending`). pub(crate) async fn pull_after_grace(state: &AppState, peer: &str, remote: &transport::Status) { - if HeadsSummary::of(state.stamp.borrow().heads.to_vec()) != remote.heads { + if state.stamp.borrow().summary() != remote.heads { let missing = { let replica = state.doc.read().await; - crate::document::changes::missing(&replica.doc, remote.heads.listed()) + crate::document::passing::lacking(&replica.doc, &remote.heads) }; if !missing.is_empty() { - let missing: Vec = - missing.into_iter().map(Into::into).collect(); state.dissemination().announced(peer, &missing); let grace = state .lock_rtt() @@ -372,7 +369,7 @@ pub(crate) async fn pull_if_behind( return false; } // The common case, the same heads, needs only the published heads. - let ours = HeadsSummary::of(state.stamp.borrow().heads.to_vec()); + let ours = state.stamp.borrow().summary(); if ours == remote.heads { return false; } @@ -380,17 +377,11 @@ pub(crate) async fn pull_if_behind( // have all of it, a later keepalive lists others. let missing = { let replica = state.doc.read().await; - crate::document::changes::missing(&replica.doc, remote.heads.listed()) + crate::document::passing::lacking(&replica.doc, &remote.heads) }; if missing.is_empty() { return false; } - // All heads, when we know them; otherwise those we lack. - let theirs = match remote.heads.heads() { - Some(heads) => heads.to_vec(), - None => missing, - }; - let Some(peer_state) = state.get_peer_state(peer).await else { return false; }; @@ -420,7 +411,7 @@ pub(crate) async fn pull_if_behind( } // Automerge asks for whatever these heads need that we don't have. - peer_state.lock().await.sync.pull_from(theirs); + crate::document::passing::pull(&mut peer_state.lock().await.sync, &remote.heads, missing); state.stats.pull_started(); debug!(peer = %peer, "Neighbour has changes we lack; pulling"); state.request_sync(peer); diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index bb99547..65a02ea 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -427,7 +427,7 @@ pub(crate) async fn handle_sync( { let mut peer_state = peer_state_mutex.lock().await; peer_state.reports_ready = Some(from_ready); - peer_state.last_heads = Some((epoch, transport::HeadsSummary::of(spec.to.clone()))); + peer_state.last_heads = Some((epoch, spec.stands())); peer_state.last_sync_rx = Some(Instant::now()); peer_state.sync.answered_by_offer(); } @@ -509,7 +509,7 @@ pub(crate) async fn handle_sync( peer_state.reports_ready = Some(from_ready); // What it says it has (`swarm::relay::unreached`). peer_state.last_heads = - Some((epoch, transport::HeadsSummary::of(message.heads().to_vec()))); + Some((epoch, message.stands())); let (taken, took) = crate::document::passing::take( &mut peer_state.sync, &mut replica, @@ -855,19 +855,9 @@ async fn download_and_apply_delta( /// document was replaced (an epoch switch, a rejoin: its heads are no longer ours). async fn own_changes( state: &AppState, - seen_heads: &mut Vec, + seen: &mut crate::document::passing::Mark, ) -> Option> { - let replica = state.doc.read().await; - let before = std::mem::replace(seen_heads, replica.heads().to_vec()); - if !crate::document::changes::holds_all(&replica.doc, &before) { - return None; - } - let since = crate::document::changes::since(&replica.doc, &before); - since - .authors - .into_iter() - .find(|(author, _)| author == state.local_id()) - .map(|(_, hashes)| hashes.into_iter().map(Into::into).collect()) + crate::document::passing::own_since(&*state.doc.read().await, seen, state.local_id()) } pub(crate) async fn run_sync_worker(state: AppState, mut rx: mpsc::UnboundedReceiver) { @@ -875,7 +865,7 @@ pub(crate) async fn run_sync_worker(state: AppState, mut rx: mpsc::UnboundedRece let mut document_dirty = false; // The heads as of the last document change looked at: what came since, and which of // it is ours (`own_changes`). - let mut seen_heads = state.doc.read().await.heads().to_vec(); + let mut seen_heads = crate::document::passing::mark(&*state.doc.read().await); info!("Starting the sync worker"); diff --git a/src/transport/mod.rs b/src/transport/mod.rs index 6fe17eb..4fa3ec3 100644 --- a/src/transport/mod.rs +++ b/src/transport/mod.rs @@ -861,6 +861,12 @@ pub(crate) struct DeltaSignatures { } impl DeltaSpec { + /// Where whoever offers it stands, as a keepalive would say it: what it offers is + /// what it has. + pub(crate) fn stands(&self) -> HeadsSummary { + HeadsSummary::of(self.to.clone()) + } + pub(crate) fn new(mut from: Vec, mut to: Vec) -> Self { from.sort_unstable(); from.dedup(); -- cgit v1.3.1