//! Automerge synchronization: the sync worker, delivery with retries, inbound sync //! messages, and the change publisher that feeds incremental streams. use std::collections::HashSet; use std::sync::Arc; use std::sync::atomic::Ordering; use anyhow::{Context, Result, anyhow, bail}; use tokio::sync::mpsc; use tokio::time::Instant; use tracing::{debug, info, trace, warn}; use crate::locks::MutexExt; use crate::state::{AppState, PeerState, Standing}; use crate::swarm::peer::{peer_swarm, send_hello_once}; use crate::swarm::source; use crate::swarm::throughput::SyncBytes; use crate::transport::{self, ParsedMessage}; #[derive(Debug)] pub(crate) enum SyncEvent { PeerValidated(String), DocumentChanged, MessageReceived(String), PeerNeedsSync(String), } async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> { if state.remake.fetching_snapshot() { // Rejoining: the snapshot comes as a download, not in a sync message. Sync // starts once it is here (`remake::catchup`). trace!("Waiting for the snapshot download; not syncing yet"); return Ok(()); } let Some(peer_state_mutex) = state.get_peer_state(peer).await else { trace!("Peer was forgotten; skipping sync"); return Ok(()); }; { use crate::locks::MutexExt; let refusing = state.screening.lock_or_recover().refusing(peer).is_some(); let mut ps = peer_state_mutex.lock().await; let now_with = (ps.run_id, ps.epoch_seq); match (refusing, ps.refused_with) { (false, _) => ps.refused_with = None, // All it commits builds on what we refused (`document::screen`). (true, None) => { ps.refused_with = Some(now_with); trace!("Refusing the peer as a whole; not syncing with it"); return Ok(()); } (true, Some(with)) if with == now_with => { trace!("Refusing the peer as a whole; not syncing with it"); return Ok(()); } // Another document since: without what we refused, or what it builds on it // is refused again. (true, Some(_)) => { ps.refused_with = None; drop(ps); state.screening.lock_or_recover().forgive(peer); } } } // A set of events is passed on otherwise (`swarm::set`): with a peer that holds // one, and of the Automerge document a node holds beside one alone, no sync. #[cfg(feature = "federation")] if state.of_a_set() || crate::swarm::set::holds_a_set_alone(state, peer).await { return Ok(()); } let we_ready = state.is_ready().await; let validated_swarm = { let peer_state = peer_state_mutex.lock().await; if peer_state.liveness.is_dormant() { // Reactivation re-handshakes, and PeerValidated then restarts sync. trace!("Skipping sync with dormant peer"); return Ok(()); } if peer_state .epoch .is_some_and(|epoch| epoch != state.local_epoch()) { // Unrelated document histories must never be synced. trace!("Skipping sync with peer on another epoch"); return Ok(()); } let Standing::Member { swarm_id } = &peer_state.standing else { return Ok(()); }; if let Some(wait) = source::defer(state, peer, &peer_state) { trace!( wait_ms = wait.as_millis(), "Catching up from another peer first; not syncing with this one yet" ); // Done earlier when the initial sync completes (every peer is enqueued // then); this only matters if the source goes quiet. state.request_sync_after(peer, wait); return Ok(()); } if peer_state .sync .leave_opening(we_ready, peer_state.reports_ready) { // Its own opening (or anything else from it) brings us back here. trace!("Leaving the opening sync message to the peer, which isn't ready"); return Ok(()); } if !peer_state.sync.has_opened() && !crate::swarm::topology::is_neighbour(state, peer) { // We only answer peers that aren't our neighbours. trace!("Not opening sync with a peer that isn't our neighbour"); return Ok(()); } swarm_id.clone() }; let swarm_id = state .swarm_id() .await .ok_or_else(|| anyhow!("Cannot sync without an established swarm ID"))?; if validated_swarm != swarm_id { bail!("Peer {peer} belongs to a different swarm"); } { let mut peer_state = peer_state_mutex.lock().await; if let Some(sending) = &mut peer_state.sync.sending { sending.regenerate = true; return Ok(()); } if peer_state .sync .retry_at .is_some_and(|at| Instant::now() < at) { // The retry timer enqueues the peer once it's due. return Ok(()); } if peer_state.sync.delta_offered { // Its answer, or the reply timeout, brings us back here. trace!("A delta is offered; waiting for the peer"); return Ok(()); } } let (session, encoded) = { let doc = Arc::clone(&state.doc); let psm = Arc::clone(&peer_state_mutex); let transport = Arc::clone(&state.transport); let peer_owned = peer.to_owned(); let ready = state.is_ready().await; // Before this message is counted. let bytes_before = SyncBytes::of(&state.traffic, peer); // Lower towards a peer a message that large wouldn't reach whole: a slow link // takes a delta chunk by chunk, where a message whole would fail and be sent // again, whole, every time. let rate = state .throughput .lock_or_recover() .get(peer) .map(|estimate| estimate.bytes_per_sec); let failed = peer_state_mutex.lock().await.failed_whole(Instant::now()); let whole = crate::document::passing::Whole { threshold: state.blobs.delta_threshold_for(rate, failed), rate, failed, }; let stats = Arc::clone(&state.stats); let clock = Arc::clone(&state.clock); let signer = state.clone(); // The session the message comes from, for its send's outcome. let (session, generated) = tokio::task::spawn_blocking( move || -> (u64, Result>) { // Label the message with the epoch of the document it was generated // from, read under the same lock. let (session, epoch, epoch_seq, outgoing, writer) = { // This node's latest change, if this message may take it, leaves // signed: signed, then looked at again under the lock the message is // made under, signed again if a write came in between (a few times // at most; past them it goes as it is, its signature with the next). let mut tries = 0; let replica = loop { signer.sign_sent(&doc); let replica = doc.blocking_read(); tries += 1; if tries >= 3 || !signer.sign_due(&replica) { break replica; } }; let mut peer_state = psm.blocking_lock(); let (epoch, epoch_seq) = (replica.epoch, replica.epoch_seq); // Whose change it passes on, if any: this message carries it. let writer = peer_state.tree_writer.take(); // Under the same locks as the epoch label: the message belongs to // this document. let outgoing = crate::document::passing::next( &mut peer_state.sync, &replica, writer.is_some(), &whole, bytes_before, |signatures| signer.blobs.keep(signatures), ); if let Some(bytes) = outgoing .as_ref() .and_then(|outgoing| outgoing.delivered_bytes) { stats.delivered_sent(bytes); } (peer_state.sync.id(), epoch, epoch_seq, outgoing, writer) }; let Some(outgoing) = outgoing else { return (session, Ok(None)); }; // A large message deflated, if it shrinks (`compress`). let (body, shrunk) = crate::document::passing::deflated(outgoing.body); if let Some((from, to)) = shrunk { stats.deflated(from, to); } // What the envelope adds to an Automerge message (`swarm::stats`), and of // that, the epoch's tag (msgpack: 12 bytes, up to 20 for generations past // 127). let inner = crate::document::passing::carried_bytes(&body); let envelope = transport::SyncEnvelope { epoch: transport::EpochTag::of(epoch), epoch_seq, body, ready, writer, delivered: outgoing.delivered, sent: clock.now_millis(), signatures: serde_bytes::ByteBuf::from(outgoing.signatures), }; let encoded = transport .encode(&peer_owned, &ParsedMessage::Sync(envelope)) .map(Some); if let (Ok(Some(encoded)), Some(inner)) = (&encoded, inner) { stats.sync_framing(encoded.payload_len.saturating_sub(inner)); } (session, encoded) }, ) .await .context("Sync generation task panicked")?; let generated = match generated { Ok(generated) => generated, Err(error) => { // Not encodable, so nothing went out: take back what it would have carried. let _ = peer_state_mutex .lock() .await .sync .send_failed(session, Instant::now()); return Err(error); } }; let Some(encoded) = generated else { return Ok(()); }; // Its answer is due. let reply_due = peer_state_mutex .lock() .await .sync .reply .as_ref() .map(|wait| wait.deadline); if let Some(at) = reply_due { state.peers_due.by(at); } (session, encoded) }; // Off the sync worker: a slow send (a large message, a busy transport) mustn't hold // up every other peer's. One message per peer is in flight (`sending`), so a peer's // messages still go out in order. let state = state.clone(); let peer = peer.to_owned(); tokio::spawn(async move { if let Err(error) = send_generated(&state, &peer, &peer_state_mutex, session, encoded).await { warn!(peer = %peer, error = %format!("{error:#}"), "Sync processing failed"); } }); Ok(()) } /// Hands a message generated from session `session` to the transport and settles it. async fn send_generated( state: &AppState, peer: &str, peer_state_mutex: &tokio::sync::Mutex, session: u64, encoded: transport::EncodedMessage, ) -> Result<()> { // No state locks are held across the send. match state.transport.send_encoded(&encoded).await { Ok(()) => { let regenerate = peer_state_mutex.lock().await.sync.send_succeeded(session); trace!( regenerate, "Outbound sync message accepted by the transport" ); if regenerate { state.request_sync(peer); } Ok(()) } Err(error) => { let delay = { let mut peer_state = peer_state_mutex.lock().await; let now = Instant::now(); peer_state.whole_failed(encoded.payload_len, now); peer_state.sync.send_failed(session, now) }; let Some(delay) = delay else { // The new session may not have opened yet. debug!("Sync message refused, but a reset already discarded it"); state.request_sync(peer); return Ok(()); }; warn!( retry_ms = delay.as_millis(), error = %format!("{error:#}"), "Sync delivery failed; generating a fresh message later" ); state.request_sync_after(peer, delay); Ok(()) } } } pub(crate) async fn handle_sync( state: &AppState, peer: &str, envelope: transport::SyncEnvelope, ) -> Result<()> { debug!(peer = %peer, "Processing sync envelope"); // This message is counted already (`transport::traffic`). let arrived = (Instant::now(), SyncBytes::of(&state.traffic, peer)); // How long it took to come, where we know the peer's clock (`swarm::hop`). let hop_delay = state.transport.clock_offset(peer).map(|offset| { crate::swarm::hop::delay_ms(envelope.sent, state.clock.now_millis(), offset.offset_ms) }); let peer_state_mutex = state.get_or_create_peer_state(peer).await; let needs_hello = { let mut peer_state = peer_state_mutex.lock().await; if let Some(delay_ms) = hop_delay { peer_state.hop_delays.record(delay_ms, arrived.0); } match &peer_state.standing { Standing::Stranger | Standing::Admitted => { // Not processed: our handshake reply resets the session anyway, and the // sender's reply timeout resends what still matters. debug!(peer = %peer, "Dropping sync message from a peer that isn't a member yet"); true } // Its swarm was proven by the handshake (the envelope doesn't say it again). Standing::Member { swarm_id } => match state.swarm_id().await { Some(ours) if &ours == swarm_id => false, _ => bail!("Sync from {peer}, a member of swarm {swarm_id}, which isn't ours"), }, } }; if needs_hello { // The peer treats us as a member but we don't know it, typically because we // restarted. Our HELLO makes it reset its sync state and reply. if let Err(error) = send_hello_once(state, peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "HELLO to unknown sync sender failed; will retry"); } return Ok(()); } // The tag names our epoch, or the message is of no epoch we sync on (the sender // switched meanwhile, or we did). let Some(epoch) = envelope.epoch.resolve([state.local_epoch()]) else { debug!(peer = %peer, epoch = %envelope.epoch, "Dropped sync message from another epoch"); return Ok(()); }; let epoch_label = epoch; // Signatures of changes (`document::signatures`): a malformed list, or more than any // sender sends, counts for nothing. let mut signatures = crate::document::signatures::unpack(&envelope.signatures) .filter(|signatures| signatures.len() <= crate::document::signatures::MAX_PER_MESSAGE) .unwrap_or_default(); let from_ready = envelope.ready; let writer = envelope.writer; let delivered = envelope.delivered; // Changes pushed along a tree (`SyncBody::Changes`): their heads and bytes, made // into the Automerge message that would have brought them (`Received::pushed`). let (payload, deflated, pushed) = match envelope.body { // Of a document of another kind: none this node holds, which a peer holding // one isn't let near (`peer::inbound`). transport::SyncBody::Kind(_) => return Ok(()), transport::SyncBody::Message(payload) => (payload, false, None), transport::SyncBody::Deflated(payload) => (payload, true, None), transport::SyncBody::Changes { heads, changes } => { let changes: Vec> = changes .into_iter() .map(serde_bytes::ByteBuf::into_vec) .collect(); let len = changes.iter().map(Vec::len).sum::(); ( transport::SyncPayload(bytes::Bytes::new()), false, Some((heads, changes, len)), ) } transport::SyncBody::Delta(spec) => { // An offer answers what we sent as much as a message would: the wait for an // answer ends here, not when the download does (its reply timeout would // otherwise count against a peer that answered, suspect its path and give it // up as the source to catch up from). What it offers is what it has. { let mut peer_state = peer_state_mutex.lock().await; peer_state.reports_ready = Some(from_ready); peer_state.last_heads = Some((epoch, spec.stands())); peer_state.last_sync_rx = Some(Instant::now()); peer_state.sync.answered_by_offer(); } // Of changes the blob brings: they wait for them (`Signatures::offer`). if !signatures.is_empty() { let doc = Arc::clone(&state.doc); tokio::task::spawn_blocking(move || { let mut replica = doc.blocking_write(); if replica.epoch == epoch { let replica = &mut *replica; replica.signatures.offer(&replica.doc, signatures); } }) .await .context("Signatures task panicked")?; } fetch_delta(state, peer, epoch, spec); return Ok(()); } }; let wire_len = pushed.as_ref().map_or(payload.0.len(), |(_, _, len)| *len); if wire_len > crate::swarm::blob::MAX_SYNC_MESSAGE { // Not decoded: a node of this version sends a delta instead. warn!(peer = %peer, bytes = wire_len, "Dropping a sync message larger than any sender should send"); return Ok(()); } let check_caught_up = !state.initial_sync_done.load(Ordering::Acquire); // Writes held until a ready neighbour is synced with once (`AppState::hold_writes`). let writes_held = *state.writes_held.borrow(); let check_level = check_caught_up || writes_held; let applied = { let doc = Arc::clone(&state.doc); let peer_state_mutex = Arc::clone(&peer_state_mutex); let stats = Arc::clone(&state.stats); let throughput = Arc::clone(&state.throughput); let screening = Arc::clone(&state.screening); let rtt = state .lock_rtt() .effective(peer, Instant::now(), state.timing.rtt_fresh_for()); // While catching up, everything arrives late; that says nothing about propagation. let measure_propagation = !check_caught_up; let message = payload; let peer = peer.to_owned(); let clock = Arc::clone(&state.clock); let ahead_ms = state.clock_ahead_ms.load(Ordering::Relaxed); let own_writers = Arc::clone(&state.own_writers); // Some((level with a ready peer, heads changed, carried changes, the new changes' // authors with theirs, and whether any has none, how long to wait before answering // if it brought only changes refused before)) when applied, None when the message // belongs to another epoch. type Applied = ( bool, bool, bool, (Vec<(String, Vec)>, bool), Option, Option<(u32, Vec)>, ); tokio::task::spawn_blocking(move || -> Result> { let (payload_len, message) = crate::document::passing::received(message, deflated, pushed)?; stats.sync_received(payload_len); let mut replica = doc.blocking_write(); // Authoritative check, under the same lock as the apply: the document may // have switched epochs since the message was accepted. if replica.epoch != epoch { return Ok(None); } let carried = message.carries_changes(); let change_bytes = if carried { message.change_bytes() } else { 0 }; if carried { stats.carrying(change_bytes); } let mut peer_state = peer_state_mutex.blocking_lock(); peer_state.reports_ready = Some(from_ready); // What it says it has (`swarm::relay::unreached`). peer_state.last_heads = Some((epoch, message.stands())); let (taken, took) = crate::document::passing::take( &mut peer_state.sync, &mut replica, message, std::mem::take(&mut signatures), &screening, ); if taken.forged > 0 { tracing::warn!(peer = %peer, forged = taken.forged, "A peer brought changes forged under another node's actor: refused"); } if let Some(actor) = taken.fresh_actor.clone() { own_writers.add(actor); } took.context("Automerge sync failed")?; let refused_again = taken.refused_again; let mut roots = taken.roots.clone(); peer_state.last_sync_rx = Some(Instant::now()); // It offers again only what we refused, and would as fast as we answer: we // answer later, later each time (`SyncSession::refused_again`). // What it brought that broke the rules, told to it now and then // (`swarm::refusals`). let tell = (!roots.is_empty() && peer_state.sync.refusals_due(Instant::now())) .then(|| (replica.epoch_seq, std::mem::take(&mut roots))); let back_off = if refused_again { Some(peer_state.sync.refused_again(Instant::now())) } else { if carried { peer_state.sync.refusals_settled(); } None }; if let Some(wait) = &peer_state.sync.reply { throughput .lock_or_recover() .exchange(&peer, wait.started, arrived, rtt); } else if let Some(delay_ms) = hop_delay.filter(|ms| *ms > 0) { // Nothing awaited: as long as it took to come. throughput.lock_or_recover().message( &peer, payload_len as u64, std::time::Duration::from_millis(delay_ms as u64), arrived.0, rtt, ); } peer_state.sync.reply_settled(); let settled = crate::document::passing::settle( &mut peer_state.sync, &mut replica, &peer, &taken, carried, delivered, check_level && from_ready, ); stats.asked_known_elsewhere(settled.asked); peer_state.asked_known += (settled.asked.0 + settled.asked.1) as u64; if settled.answering_behind { stats.answering_behind(); } stats.heads_seen(settled.heads); let changed = settled.changed; if let Some(new) = settled.new { stats.new_changes(new); } match settled.waits { Some(true) => stats.waiting(), Some(false) => { stats.nothing_new(payload_len, writer.is_some(), delivered, change_bytes) } None => {} } // Whose they are, to pass them on along their writers' trees, however they // came (along a tree, with an answer, pulled). let (authors, times) = ((settled.authors, settled.unauthored), settled.times); if changed && measure_propagation { // Now by the peers' clocks (their median): this node's own clock skew // doesn't count; the writer's still does. let now_ms = clock.now_millis().as_u64() as i64 - ahead_ms; let delays: Vec = times.into_iter().map(|time| now_ms - time).collect(); if writer.is_none() { stats.off_tree(&delays); } stats.propagated(delays); } Ok(Some(( // Only from a ready peer, and only if it has heads at all: empty heads are // "contained" in every document, so they prove nothing. A peer still // catching up has them, and so does a ready peer whose document is empty // (a misconfigured second swarm, or a genesis node in its first seconds, // before it registered itself). settled.level, changed, carried, authors, back_off, tell, ))) }) .await .context("Sync task panicked")?? }; let Some((level, changed, carried, (authors, unauthored), back_off, tell)) = applied else { debug!(peer = %peer, epoch = %epoch_label, "Dropped sync message from another epoch"); return Ok(()); }; if let Some((epoch_seq, roots)) = tell { crate::swarm::refusals::tell(state, peer, epoch, epoch_seq, roots).await; } if let Some(delay) = back_off { debug!( peer = %peer, wait_ms = delay.as_millis(), "Offered only changes refused before; answering later" ); state.request_sync_after(peer, delay); } source::reported(state, peer, from_ready, None); if level && writes_held { state.release_writes(peer); } let caught_up = level && check_caught_up; let just_caught_up = caught_up && !state.initial_sync_done.swap(true, Ordering::AcqRel); if just_caught_up { info!(peer = %peer, "Initial sync complete"); state .stats .caught_up(state.traffic.total().received.sync.bytes); source::finished(state, peer); state.join_progress.notify_one(); } state.notify_store_changed(); crate::swarm::relay::pulled(state, peer); if state.initial_sync_done.load(Ordering::Acquire) && !just_caught_up { state .dissemination() .note_arrival(state, peer, writer, carried, &authors) .await; } // Caught up: our other neighbours may lack what the source had. if changed || just_caught_up { let writers: Vec<(u64, Vec)> = authors .into_iter() .map(|(author, changes)| (crate::swarm::topology::pair_key(&author), changes)) .collect(); crate::swarm::relay::announce(state, peer, &writers, unauthored).await; } else if carried && let Some(writer) = writer && state.initial_sync_done.load(Ordering::Acquire) { // A writer's changes along its tree that we had already: they came another way // first, not saying whose (with an answer to one of our messages, say), so we // passed nothing on then. Our children in its tree may lack them still. state .dissemination() .forward(state, writer, peer, &[]) .await; } state .sync_events .send(SyncEvent::MessageReceived(peer.to_owned())) .map_err(|error| anyhow!("Failed to notify sync worker: {error}"))?; Ok(()) } /// The peer offered the changes we lack as a blob (`SyncBody::Delta`): fetch them, from /// it and any other peer that has them, apply them, and sync on. One download per peer /// at a time: the offer is repeated while it runs. fn fetch_delta(state: &AppState, peer: &str, epoch: transport::Epoch, spec: transport::DeltaSpec) { if !state.blobs.start_delta(peer) { debug!(peer = %peer, "Delta offered while another downloads; after it"); return; } let state = state.clone(); let peer = peer.to_owned(); tokio::spawn(async move { let done = DeltaDone { state: state.clone(), peer: peer.clone(), }; let applied = download_and_apply_delta(&state, &peer, epoch, spec).await; drop(done); match applied { Ok(changed) => { state.notify_store_changed(); if changed { crate::swarm::relay::announce(&state, &peer, &[], true).await; } } Err(error) => { warn!(peer = %peer, error = %format!("{error:#}"), "Delta download failed; syncing on"); } } // Our next message says what we have now; the peer answers with the rest. state.request_sync(&peer); }); } /// The delta download from `peer` ended, when dropped: however it ended, a panic /// included, the next may start (`Blobs::end_delta`), and those that offered meanwhile /// send what is still missing (our next message says what we have now). struct DeltaDone { state: AppState, peer: String, } impl Drop for DeltaDone { fn drop(&mut self) { for other in self.state.blobs.end_delta(&self.peer) { if other != self.peer { self.state.request_sync(&other); } } } } /// Returns whether our heads changed. async fn download_and_apply_delta( state: &AppState, peer: &str, epoch: transport::Epoch, spec: transport::DeltaSpec, ) -> Result { // The offerer first: it holds what it offers (`blob::fetch` asks it first). let mut peers = vec![peer.to_owned()]; peers.extend( state .active_peers_on_local_epoch() .await .into_iter() .filter(|other| other != peer), ); if let Some(peer_state) = state.get_peer_state(peer).await { let doc = Arc::clone(&state.doc); let from = spec.from.clone(); let known = tokio::task::spawn_blocking(move || { let replica = doc.blocking_read(); peer_state .blocking_lock() .sync .known_beyond(&replica.doc, &from) }) .await .context("Delta check task panicked")?; if known > 0 { // Offered before it heard what we have: it would bring those again. Our // next message tells it (`fetch_delta`); it offers afresh if still needed. info!(peer = %peer, known, "Offered changes partly here already; not fetched"); return Ok(false); } } // Its signatures first, from the offerer alone: another node holding the changes // holds signatures of its own, not these. let signatures = match spec.signatures { Some(at) => { let most = (crate::document::signatures::MAX_PER_MESSAGE * crate::document::signatures::PACKED) as u64; if at.size > most { bail!("the offered changes' signatures are larger than any message's"); } let bytes = crate::swarm::blob::fetch_content(state, at.hash, at.size, vec![peer.to_owned()]) .await .context("Fetching the offered changes' signatures")?; crate::document::signatures::unpack(&bytes) .context("the offered changes' signatures aren't whole")? } None => Vec::new(), }; info!(peer = %peer, to = spec.to.len(), "Fetching changes offered as a blob"); let started = Instant::now(); let bytes = crate::swarm::blob::fetch_delta(state, &spec, peers).await?; info!( peer = %peer, bytes = bytes.len(), took_ms = started.elapsed().as_millis() as u64, "Fetched changes offered as a blob" ); let doc = Arc::clone(&state.doc); let peer_state = state.get_peer_state(peer).await; let stats = Arc::clone(&state.stats); // As for sync messages (`receive`): not while catching up. let measure_propagation = state.initial_sync_done.load(Ordering::Acquire); let clock = Arc::clone(&state.clock); let ahead_ms = state.clock_ahead_ms.load(Ordering::Relaxed); let screening = Arc::clone(&state.screening); let own_writers = Arc::clone(&state.own_writers); tokio::task::spawn_blocking(move || -> Result { let mut replica = doc.blocking_write(); if replica.epoch != epoch { bail!("the epoch changed during the download"); } let (fresh_actor, bulk) = crate::document::passing::take_bulk( &mut replica, &bytes, signatures, &spec.to, &screening, measure_propagation, ); if let Some(actor) = fresh_actor { own_writers.add(actor); } let bulk = bulk?; stats.heads_seen(bulk.heads); let changed = bulk.changed; let heads_before = bulk.heads_before; if changed && measure_propagation { // As in `receive`; a delta goes along no writer's tree. let now_ms = clock.now_millis().as_u64() as i64 - ahead_ms; let delays: Vec = bulk.times.into_iter().map(|time| now_ms - time).collect(); stats.off_tree(&delays); stats.propagated(delays); } if let Some(peer_state) = peer_state { let mut peer_state = peer_state.blocking_lock(); // Sync from it made progress: no heal for a while (`keepalive`). peer_state.last_sync_rx = Some(Instant::now()); if changed { // From its history: none goes back (`SyncSession::came_from_peer`), nor // is offered back as a delta. peer_state.sync.came_from_peer(&replica.doc, &heads_before); } } Ok(changed) }) .await .context("Delta apply task panicked")? } /// Our own changes since `seen_heads` (which become the heads now), if what changed /// is a write of ours; None if none of it is ours (a change fetched as a blob), or the /// document was replaced (an epoch switch, a rejoin: its heads are no longer ours). async fn own_changes( state: &AppState, seen: &mut crate::document::passing::Mark, ) -> Option> { 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) { let mut dirty_peers = HashSet::::new(); 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 = crate::document::passing::mark(&*state.doc.read().await); info!("Starting the sync worker"); loop { if dirty_peers.is_empty() && !document_dirty { match rx.recv().await { Some(event) => match event { SyncEvent::PeerValidated(peer) | SyncEvent::MessageReceived(peer) | SyncEvent::PeerNeedsSync(peer) => { dirty_peers.insert(peer); } SyncEvent::DocumentChanged => { document_dirty = true; } }, None => { warn!("Sync event channel closed"); return; } } } // Coalesce event bursts. while let Ok(event) = rx.try_recv() { match event { SyncEvent::PeerValidated(peer) | SyncEvent::MessageReceived(peer) | SyncEvent::PeerNeedsSync(peer) => { dirty_peers.insert(peer); } SyncEvent::DocumentChanged => { document_dirty = true; } } } // Let pending HTTP task locks wake up and complete their lifecycle transitions gracefully. tokio::task::yield_now().await; if document_dirty { document_dirty = false; // Lock and extract only the cloned string keys into a small transient vector let peer_keys: Vec = { let peers_guard = state.peer_states.read().await; peers_guard.keys().cloned().collect() }; // Our own changes go to our neighbours, saying they're ours: they pass them // on along our tree (`swarm::tree`). Others only get answers to what they // send us. But neighbours that get them from another parent in our tree (a // sibling they have a much faster link to: `tree::parent`) count as having // them, as in `tree::forward`, and get nothing now. let own = crate::swarm::topology::pair_key(state.local_id()); let ours = own_changes(&state, &mut seen_heads).await; let covered = match &ours { Some(ours) => match state.dissemination().plan(&state, own).await { Some(plan) => { for neighbour in &plan.covered { if let Some(peer_state) = state.get_peer_state(neighbour).await { peer_state .lock() .await .sync .known_to_peer(ours, Instant::now()); } } plan.covered } None => Vec::new(), }, None => Vec::new(), }; for peer in peer_keys { if peer_swarm(&state, &peer).await.is_some() && crate::swarm::topology::is_neighbour(&state, &peer) && !covered.contains(&peer) { if let Some(peer_state) = state.get_peer_state(&peer).await { peer_state.lock().await.tree_writer = Some(own); } dirty_peers.insert(peer); } } } let peers: Vec = dirty_peers.drain().collect(); for peer in peers { if let Err(error) = deliver_sync_to_peer(&state, &peer).await { warn!( peer = %peer, error = %format!("{error:#}"), "Sync processing failed" ); } } } }