diff options
| author | tv <tv@krebsco.de> | 2026-11-29 03:42:52 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-29 03:42:52 +0000 |
| commit | e75c6ff95fbbaf9a4d951b82c4f2ba8d7bf3526b (patch) | |
| tree | 89d7a6f0c54c83ef45d87c154b06ba4997257347 /src/document/passing.rs | |
| parent | a5b58282e496de7243f4f433deb3984e8fab8b3c (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/document/passing.rs')
| -rw-r--r-- | src/document/passing.rs | 197 |
1 files changed, 197 insertions, 0 deletions
diff --git a/src/document/passing.rs b/src/document/passing.rs new file mode 100644 index 0000000..bbe51a0 --- /dev/null +++ b/src/document/passing.rs @@ -0,0 +1,197 @@ +//! Passing an Automerge document on to a peer (`docs/document.md`, Passing on): what goes +//! to it next (`next`), by the session with it (`sync::SyncSession`), as the wire +//! carries it now. Whom a node syncs with and when, along whose tree, and what is counted +//! of it, is the swarm's (`swarm::sync`). + +use tokio::time::Instant; +use tracing::{debug, info}; + +use super::replica::Replica; +use super::signatures; +use super::sync::SyncSession; +use crate::swarm::throughput::SyncBytes; +use crate::transport::{DeltaSignatures, DeltaSpec, SyncBody, SyncPayload}; + +/// What goes to a peer next. +pub(crate) struct Outgoing { + pub(crate) body: SyncBody, + /// The sender takes it as delivered (`SyncSession::assume_delivered`): it had + /// everything the peer had, and awaits no answer. + pub(crate) delivered: bool, + /// The signatures of the changes it carries, packed (`signatures::pack`). + pub(crate) signatures: Vec<u8>, + /// Where taken as delivered, the bytes it carries of the document. + pub(crate) delivered_bytes: Option<usize>, +} + +/// How large a message to a peer may be before what it would carry is offered as a blob +/// (`threshold`), and what lowered that, to say so: the throughput measured to the peer +/// (`rate`), a message that failed whole to it lately (`failed`). +pub(crate) struct Whole { + pub(crate) threshold: usize, + pub(crate) rate: Option<f64>, + pub(crate) failed: Option<usize>, +} + +/// The next message for the peer `session` is with, of the document `replica` holds, if +/// there is anything to say: changes as they are, where it passes a writer's on along +/// its tree (`pushing`) to a peer level with it; else a sync message; or, where that is +/// larger than `whole` allows, an offer of the changes as a blob, whose signatures `keep` +/// keeps to serve. Under the locks the message's epoch is read under. +pub(crate) fn next( + session: &mut SyncSession, + replica: &Replica, + pushing: bool, + whole: &Whole, + bytes_before: SyncBytes, + keep: impl FnOnce(Vec<u8>) -> DeltaSignatures, +) -> Option<Outgoing> { + let delta_threshold = whole.threshold; + // To a peer that had nothing we lack, with nothing awaited: taken as delivered + // (`SyncSession::assume_delivered`). + let level = session.reply.is_none() && session.have_all_theirs(&replica.doc); + // 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 = session.offer_again( + &replica.doc, + replica.heads(), + delta_threshold, + Instant::now(), + ); + // 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 && pushing && again.is_none()) + .then(|| { + session.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(SyncBody::Changes { + heads, + changes: changes + .into_iter() + .map(serde_bytes::ByteBuf::from) + .collect(), + }) + } else if let Some(from) = again { + let spec = 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(SyncBody::Delta(spec)) + } else { + let message = session.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, session.carried()); + if payload.0.len() + signatures.len() * signatures::PACKED <= delta_threshold { + carried_signatures = Some(signatures); + return Some(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 = session.withdraw_for_delta(&replica.doc, Instant::now()); + let spec = 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" + ); + session.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 = ?whole.rate.map(|rate| rate as u64), + failed_whole = ?whole.failed, + from = spec.from.len(), + to = spec.to.len(), + "Sync message too large; offering the changes as a blob" + ); + session.offered(&spec.from, &spec.to, payload.0.len()); + Some(SyncBody::Delta(spec)) + }) + }; + let delivered = level && matches!(body, Some(SyncBody::Message(_) | SyncBody::Changes { .. })); + let mut delivered_bytes = None; + if delivered { + session.assume_delivered(replica.heads()); + delivered_bytes = match &body { + Some(SyncBody::Message(payload)) => Some(payload.0.len()), + Some(SyncBody::Changes { changes, .. }) => { + Some(changes.iter().map(|change| change.len()).sum()) + } + _ => None, + }; + } + // 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 + // (`keep`): the peer fetches them with the delta. A message carrying no changes takes + // none. + let signatures = match &mut body { + Some(SyncBody::Delta(spec)) => { + let signatures = replica.signatures.for_delta(&replica.doc, &spec.from); + spec.signatures = (!signatures.is_empty()).then(|| keep(signatures::pack(&signatures))); + Vec::new() + } + Some(_) => carried_signatures.unwrap_or_else(|| { + replica + .signatures + .for_changes(&replica.doc, session.carried()) + }), + None => Vec::new(), + }; + Some(Outgoing { + body: body?, + delivered, + signatures: signatures::pack(&signatures), + delivered_bytes, + }) +} + +/// `body` with a large sync message deflated, if it shrinks (`compress`): and from how +/// many bytes to how many. Not under a lock: it takes a while. +pub(crate) fn deflated(body: SyncBody) -> (SyncBody, Option<(usize, usize)>) { + match body { + SyncBody::Message(payload) => match crate::compress::deflate(&payload.0) { + Some(deflated) => { + let sizes = (payload.0.len(), deflated.len()); + ( + SyncBody::Deflated(SyncPayload(deflated.into())), + Some(sizes), + ) + } + None => (SyncBody::Message(payload), None), + }, + other => (other, None), + } +} + +/// How many bytes of the document `body` carries itself: none for an offer of a blob. +pub(crate) fn carried_bytes(body: &SyncBody) -> Option<usize> { + match body { + SyncBody::Message(payload) | SyncBody::Deflated(payload) => Some(payload.0.len()), + SyncBody::Changes { changes, .. } => Some(changes.iter().map(|change| change.len()).sum()), + SyncBody::Delta(_) => None, + } +} |
