aboutsummaryrefslogtreecommitdiffstats
path: root/src/swarm/sync.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 03:42:52 +0000
committertv <tv@krebsco.de>2026-11-29 03:42:52 +0000
commite75c6ff95fbbaf9a4d951b82c4f2ba8d7bf3526b (patch)
tree89d7a6f0c54c83ef45d87c154b06ba4997257347 /src/swarm/sync.rs
parenta5b58282e496de7243f4f433deb3984e8fab8b3c (diff)
document: what goes to a peer next is the document's to say
document::passing::next: the next message for a peer, by the session with it: changes as they are along a tree, a sync message, or an offer of the changes as a blob where a message would be too large, with the signatures of what it carries, and whether it is taken as delivered. swarm::sync keeps whose tree a message is along, the epoch it is of, the envelope, and what is counted of it.
Diffstat (limited to 'src/swarm/sync.rs')
-rw-r--r--src/swarm/sync.rs201
1 files changed, 27 insertions, 174 deletions
diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs
index 517f67d..0770343 100644
--- a/src/swarm/sync.rs
+++ b/src/swarm/sync.rs
@@ -163,7 +163,11 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> {
.get(peer)
.map(|estimate| estimate.bytes_per_sec);
let failed = peer_state_mutex.lock().await.failed_whole(Instant::now());
- let delta_threshold = state.blobs.delta_threshold_for(rate, failed);
+ 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);
@@ -173,7 +177,7 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> {
move || -> (u64, Result<Option<transport::EncodedMessage>>) {
// Label the message with the epoch of the document it was generated
// from, read under the same lock.
- let (session, epoch, epoch_seq, body, writer, delivered, signatures) = {
+ 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
@@ -191,196 +195,45 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> {
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();
- // To a peer that had nothing we lack, with nothing awaited: taken
- // as delivered (`SyncSession::assume_delivered`).
- let level = peer_state.sync.reply.is_none()
- && peer_state.sync.have_all_theirs(&replica.doc);
// Under the same locks as the epoch label: the message belongs to
// this document.
- // The same delta as last time, the peer's heads and ours unchanged
- // (it didn't answer in time): offered again without generating the
- // message it replaces, which may take seconds when large.
- let again = peer_state.sync.offer_again(
- &replica.doc,
- replica.heads(),
- delta_threshold,
- Instant::now(),
+ let outgoing = crate::document::passing::next(
+ &mut peer_state.sync,
+ &replica,
+ writer.is_some(),
+ &whole,
+ bytes_before,
+ |signatures| signer.blobs.keep(signatures),
);
- // Along a tree, taken as delivered: the changes as they are
- // (`SyncSession::push`). Only those too small to deflate: larger ones go
- // as a message, deflated (`compress`).
- let pushed = (level && writer.is_some() && again.is_none())
- .then(|| {
- peer_state.sync.push(
- &replica.doc,
- delta_threshold.min(crate::compress::WORTH_FROM - 1),
- )
- })
- .flatten();
- // A message's signatures, where finding them was part of deciding it.
- let mut carried_signatures = None;
- let mut body = if let Some((heads, changes)) = pushed {
- Some(transport::SyncBody::Changes {
- heads,
- changes: changes
- .into_iter()
- .map(serde_bytes::ByteBuf::from)
- .collect(),
- })
- } else if let Some(from) = again {
- let spec = transport::DeltaSpec::new(from, replica.heads().to_vec());
- debug!(
- from = spec.from.len(),
- to = spec.to.len(),
- "Offering the same changes as a blob again"
- );
- Some(transport::SyncBody::Delta(spec))
- } else {
- let message =
- peer_state
- .sync
- .generate(&replica.doc, Instant::now(), bytes_before);
- message.and_then(|payload| {
- // Its signatures count towards its size: a whole document
- // pulled carries one per writer.
- let signatures = replica
- .signatures
- .for_changes(&replica.doc, peer_state.sync.carried());
- if payload.0.len()
- + signatures.len() * crate::document::signatures::PACKED
- <= delta_threshold
- {
- carried_signatures = Some(signatures);
- return Some(transport::SyncBody::Message(payload));
- }
- // Too large for one message: all or nothing, and on a slow link
- // within the transport's delivery limit. The peer fetches it in
- // chunks.
- let from = peer_state
- .sync
- .withdraw_for_delta(&replica.doc, Instant::now());
- let spec = transport::DeltaSpec::new(from, replica.heads().to_vec());
- if spec.to.iter().all(|head| spec.from.contains(head)) {
- // It has our heads: nothing to offer (Automerge thought it
- // lacked what it has, as from a view of it that was old).
- debug!(
- message_bytes = payload.0.len(),
- "Sync message too large, but the peer has our heads; not sent"
- );
- peer_state.sync.nothing_to_send();
- return None;
- }
- // And why it is too large here: the threshold, lowered by the
- // throughput measured to the peer or a message that failed whole
- // to it lately (`Blobs::delta_threshold_for`).
- info!(
- message_bytes = payload.0.len(),
- threshold = delta_threshold,
- throughput = ?rate.map(|rate| rate as u64),
- failed_whole = ?failed,
- from = spec.from.len(),
- to = spec.to.len(),
- "Sync message too large; offering the changes as a blob"
- );
- peer_state
- .sync
- .offered(&spec.from, &spec.to, payload.0.len());
- Some(transport::SyncBody::Delta(spec))
- })
- };
- let delivered = level
- && matches!(
- body,
- Some(
- transport::SyncBody::Message(_)
- | transport::SyncBody::Changes { .. }
- )
- );
- if delivered {
- peer_state.sync.assume_delivered(replica.heads());
- match &body {
- Some(transport::SyncBody::Message(payload)) => {
- stats.delivered_sent(payload.0.len());
- }
- Some(transport::SyncBody::Changes { changes, .. }) => {
- stats.delivered_sent(changes.iter().map(|c| c.len()).sum());
- }
- _ => {}
- }
+ if let Some(bytes) = outgoing
+ .as_ref()
+ .and_then(|outgoing| outgoing.delivered_bytes)
+ {
+ stats.delivered_sent(bytes);
}
- // With changes, the signatures of those it carries: they go where
- // changes go, along the trees, so a peer that got these changes
- // elsewhere got the signatures with them; and changes sent again go
- // vouched for as the first time. A delta's, of each writer with
- // changes in it its latest, go as a blob of their own, from this node
- // (`Blobs::keep`): the peer fetches them with the delta. A message
- // carrying no changes takes none.
- let signatures = match &mut body {
- Some(transport::SyncBody::Delta(spec)) => {
- let signatures = replica.signatures.for_delta(&replica.doc, &spec.from);
- spec.signatures = (!signatures.is_empty()).then(|| {
- signer
- .blobs
- .keep(crate::document::signatures::pack(&signatures))
- });
- Vec::new()
- }
- Some(_) => carried_signatures.unwrap_or_else(|| {
- replica
- .signatures
- .for_changes(&replica.doc, peer_state.sync.carried())
- }),
- None => Vec::new(),
- };
- let signatures = crate::document::signatures::pack(&signatures);
- (
- peer_state.sync.id(),
- epoch,
- epoch_seq,
- body,
- writer,
- delivered,
- signatures,
- )
+ (peer_state.sync.id(), epoch, epoch_seq, outgoing, writer)
};
- let Some(body) = body else {
+ let Some(outgoing) = outgoing else {
return (session, Ok(None));
};
// A large message deflated, if it shrinks (`compress`).
- let body = match body {
- transport::SyncBody::Message(payload) => {
- match crate::compress::deflate(&payload.0) {
- Some(deflated) => {
- stats.deflated(payload.0.len(), deflated.len());
- transport::SyncBody::Deflated(transport::SyncPayload(
- deflated.into(),
- ))
- }
- None => transport::SyncBody::Message(payload),
- }
- }
- other => other,
- };
+ 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 = match &body {
- transport::SyncBody::Message(payload)
- | transport::SyncBody::Deflated(payload) => Some(payload.0.len()),
- transport::SyncBody::Changes { changes, .. } => {
- Some(changes.iter().map(|change| change.len()).sum())
- }
- transport::SyncBody::Delta(_) => None,
- };
+ let inner = crate::document::passing::carried_bytes(&body);
let envelope = transport::SyncEnvelope {
epoch: transport::EpochTag::of(epoch),
epoch_seq,
body,
ready,
writer,
- delivered,
+ delivered: outgoing.delivered,
sent: clock.now_millis(),
- signatures: serde_bytes::ByteBuf::from(signatures),
+ signatures: serde_bytes::ByteBuf::from(outgoing.signatures),
};
let encoded = transport
.encode(&peer_owned, &ParsedMessage::Sync(envelope))