aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/document/passing.rs177
-rw-r--r--src/swarm/sync.rs145
2 files changed, 217 insertions, 105 deletions
diff --git a/src/document/passing.rs b/src/document/passing.rs
index bbe51a0..381b5c7 100644
--- a/src/document/passing.rs
+++ b/src/document/passing.rs
@@ -6,9 +6,10 @@
use tokio::time::Instant;
use tracing::{debug, info};
+use super::ChangeHash;
use super::replica::Replica;
use super::signatures;
-use super::sync::SyncSession;
+use super::sync::{Received, SyncSession};
use crate::swarm::throughput::SyncBytes;
use crate::transport::{DeltaSignatures, DeltaSpec, SyncBody, SyncPayload};
@@ -195,3 +196,177 @@ pub(crate) fn carried_bytes(body: &SyncBody) -> Option<usize> {
SyncBody::Delta(_) => None,
}
}
+
+/// A message as it came, read: its bytes of the document, and what it says. Not under a
+/// lock: inflating and decoding a large one takes a while. No larger than any sender
+/// should send, deflated or not.
+pub(crate) fn received(
+ message: SyncPayload,
+ deflated: bool,
+ pushed: Option<(Vec<ChangeHash>, Vec<Vec<u8>>, usize)>,
+) -> anyhow::Result<(usize, Received)> {
+ use anyhow::Context;
+ let message = if deflated {
+ SyncPayload(
+ crate::compress::inflate(&message.0, crate::swarm::blob::MAX_SYNC_MESSAGE)
+ .context("Inflating a sync message")?
+ .into(),
+ )
+ } else {
+ message
+ };
+ Ok(match pushed {
+ Some((heads, changes, len)) => (
+ len,
+ Received::pushed(heads, changes).context("Pushed changes that don't decode")?,
+ ),
+ None => (message.0.len(), super::sync::decode(&message)?),
+ })
+}
+
+/// What taking a message did (`take`).
+pub(crate) struct Taken {
+ /// The document's heads before, and those the peer said it has.
+ pub(crate) heads_before: Vec<ChangeHash>,
+ pub(crate) said: Vec<ChangeHash>,
+ /// It carried changes, all of them refused before (`screen::Outcome`).
+ pub(crate) refused_again: bool,
+ /// The changes that broke a rule, of those refused.
+ pub(crate) roots: Vec<ChangeHash>,
+ /// Changes it carried forged under another node's actor.
+ pub(crate) forged: usize,
+ /// The fresh actor this node writes as from now on, where it carried a change of
+ /// this node's actor that the node didn't make.
+ pub(crate) fresh_actor: Option<super::ActorId>,
+}
+
+/// Takes `message`, from the peer `session` is with, into the document `replica` holds:
+/// the changes it carries judged first, each as the policy it was written under has it
+/// (`screen`), whether this document has one yet or not, and vouched for by the
+/// `signatures` it came with too, where that policy requires them; then the rest of it
+/// given to the session. What it did so far, where that failed too: a fresh actor is the
+/// node's from then on.
+pub(crate) fn take(
+ session: &mut SyncSession,
+ replica: &mut Replica,
+ mut message: Received,
+ mut signatures: Vec<(ChangeHash, [u8; 64])>,
+ screening: &std::sync::Mutex<super::screen::Screening>,
+) -> (Taken, anyhow::Result<()>) {
+ use crate::locks::MutexExt;
+ let heads_before = replica.heads().to_vec();
+ let said = message.heads().to_vec();
+ let (epoch, epoch_seq) = (replica.epoch, replica.epoch_seq);
+ let mut outcome = super::screen::Outcome::default();
+ let result = replica.logged_signed(|doc, known, log| {
+ let result = (|| {
+ let bytes = message.take_changes();
+ known.offer(doc, std::mem::take(&mut signatures));
+ outcome = super::screen::apply_bytes(
+ doc,
+ epoch,
+ epoch_seq,
+ &bytes,
+ screening,
+ Some(&mut *known),
+ log,
+ )?;
+ session.lacks(screening.lock_or_recover().waiting.lacking(doc));
+ session.receive_logged(doc, message, log)
+ })();
+ (result, true)
+ });
+ let taken = Taken {
+ heads_before,
+ said,
+ refused_again: outcome.refused_again,
+ roots: outcome.roots,
+ forged: outcome.forged,
+ fresh_actor: outcome.fresh_actor,
+ };
+ (taken, result)
+}
+
+/// Where a document and the session with a peer stand once a message was taken
+/// (`settle`).
+pub(crate) struct Settled {
+ /// What was asked for again that the peer is known to have elsewhere
+ /// (`SyncSession::resend_if_needed`).
+ pub(crate) asked: (usize, usize),
+ /// How many heads the document has now, and whether they changed.
+ pub(crate) heads: usize,
+ pub(crate) changed: bool,
+ /// The message was taken as delivered, and the peer is behind: the answer brings it
+ /// what it lacks.
+ pub(crate) answering_behind: bool,
+ /// How many of the changes it brought are new to the session.
+ pub(crate) new: Option<usize>,
+ /// It carried changes and the heads stayed: whether what it brought waits for
+ /// predecessors (the peer's heads aren't the document's yet), or had come before.
+ pub(crate) waits: Option<bool>,
+ /// Whose the changes it brought are, whether any is nobody's, and when each was made.
+ pub(crate) authors: Vec<(String, Vec<ChangeHash>)>,
+ pub(crate) unauthored: bool,
+ pub(crate) times: Vec<i64>,
+ /// Where asked: whether the document holds all the peer said it has.
+ pub(crate) level: bool,
+}
+
+/// Settles the session with `peer` after a message was taken (`taken`): what the peer
+/// still lacks asked for again, the signatures waiting for what came offered, and, where
+/// the message was taken as `delivered`, whether an answer is due at all.
+pub(crate) fn settle(
+ session: &mut SyncSession,
+ replica: &mut Replica,
+ peer: &str,
+ taken: &Taken,
+ carried: bool,
+ delivered: bool,
+ level: bool,
+) -> Settled {
+ let heads_before = &taken.heads_before;
+ let asked = session.resend_if_needed(&replica.doc, peer, Instant::now());
+ replica.refresh_heads();
+ // The signatures waiting for what it brought (those it sent, offered before).
+ if replica.heads() != heads_before.as_slice() {
+ let replica = &mut *replica;
+ replica.signatures.offer(&replica.doc, Vec::new());
+ }
+ let heads_after = replica.heads().to_vec();
+ let mut answering_behind = false;
+ if delivered {
+ // Level with the sender now, which takes the message as delivered: nothing to
+ // answer (`SyncSession::answered_as_delivered`). Unless it is behind us: then the
+ // answer brings it what it lacks.
+ let behind = session.peer_behind(&replica.doc, &heads_after);
+ let answered = session.answered_as_delivered(&replica.doc, &heads_after);
+ answering_behind = behind && !answered;
+ }
+ let changed = heads_after != *heads_before;
+ // What it brought, walked once.
+ let since = changed.then(|| super::changes::since(&replica.doc, heads_before));
+ // They came from it: none goes back (`SyncSession::came_from_peer`).
+ let new = since
+ .as_ref()
+ .map(|since| session.these_came_from_peer(&since.hashes));
+ // Its heads not ours yet: what it brought waits for predecessors, which isn't having
+ // come twice.
+ let waits =
+ (carried && !changed).then(|| !super::changes::holds_all(&replica.doc, &taken.said));
+ let (authors, unauthored, times) = match since {
+ Some(since) => (since.authors, since.unauthored, since.times),
+ None => (Vec::new(), false, Vec::new()),
+ };
+ Settled {
+ asked,
+ heads: heads_after.len(),
+ changed,
+ answering_behind,
+ new,
+ waits,
+ authors,
+ unauthored,
+ times,
+ level: level && session.have_all_theirs(&replica.doc),
+ }
+}
diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs
index 0770343..18e5653 100644
--- a/src/swarm/sync.rs
+++ b/src/swarm/sync.rs
@@ -489,25 +489,8 @@ pub(crate) async fn handle_sync(
Option<(u32, Vec<crate::document::ChangeHash>)>,
);
tokio::task::spawn_blocking(move || -> Result<Option<Applied>> {
- // Before the lock: inflating and decoding a large message takes a while. No
- // larger than any sender should send, deflated or not.
- let message = if deflated {
- transport::SyncPayload(
- crate::compress::inflate(&message.0, crate::swarm::blob::MAX_SYNC_MESSAGE)
- .context("Inflating a sync message")?
- .into(),
- )
- } else {
- message
- };
- let (payload_len, message) = match pushed {
- Some((heads, changes, len)) => (
- len,
- crate::document::sync::Received::pushed(heads, changes)
- .context("Pushed changes that don't decode")?,
- ),
- None => (message.0.len(), crate::document::sync::decode(&message)?),
- };
+ let (payload_len, message) =
+ crate::document::passing::received(message, deflated, pushed)?;
stats.sync_received(payload_len);
let mut replica = doc.blocking_write();
@@ -527,48 +510,22 @@ pub(crate) async fn handle_sync(
// What it says it has (`swarm::relay::unreached`).
peer_state.last_heads =
Some((epoch, transport::HeadsSummary::of(message.heads().to_vec())));
- let heads_before = replica.heads().to_vec();
- let said = message.heads().to_vec();
-
- let sync = &mut peer_state.sync;
- let epoch_seq = replica.epoch_seq;
- let mut message = message;
- let mut refused_again = false;
- let mut roots = Vec::new();
- replica
- .logged_signed(|doc, known, log| {
- let result = (|| {
- // Judged first, each as the policy it was written under has it
- // (`document::screen`), whether this document has one yet or not;
- // and vouched for by the signatures it sent too, where that policy
- // requires them.
- {
- let bytes = message.take_changes();
- known.offer(doc, std::mem::take(&mut signatures));
- let outcome = crate::document::screen::apply_bytes(
- doc,
- epoch,
- epoch_seq,
- &bytes,
- &screening,
- Some(&mut *known),
- log,
- )?;
- refused_again = outcome.refused_again;
- roots = outcome.roots;
- if outcome.forged > 0 {
- tracing::warn!(peer = %peer, forged = outcome.forged, "A peer brought changes forged under another node's actor: refused");
- }
- if let Some(actor) = outcome.fresh_actor {
- own_writers.add(actor);
- }
- sync.lacks(screening.lock_or_recover().waiting.lacking(doc));
- }
- sync.receive_logged(doc, message, log)
- })();
- (result, true)
- })
- .context("Automerge sync failed")?;
+ 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`).
@@ -600,55 +557,35 @@ pub(crate) async fn handle_sync(
}
peer_state.sync.reply_settled();
- let asked = peer_state
- .sync
- .resend_if_needed(&replica.doc, &peer, Instant::now());
- stats.asked_known_elsewhere(asked);
- peer_state.asked_known += (asked.0 + asked.1) as u64;
- replica.refresh_heads();
- // The signatures waiting for what it brought (those it sent, offered before).
- if replica.heads() != heads_before.as_slice() {
- let replica = &mut *replica;
- replica.signatures.offer(&replica.doc, Vec::new());
- }
- let heads_after = replica.heads().to_vec();
- if delivered {
- // Level with the sender now, which takes the message as delivered:
- // nothing to answer (`SyncSession::answered_as_delivered`). Unless it is
- // behind us: then the answer brings it what it lacks.
- let behind = peer_state.sync.peer_behind(&replica.doc, &heads_after);
- let answered = peer_state
- .sync
- .answered_as_delivered(&replica.doc, &heads_after);
- if behind && !answered {
- stats.answering_behind();
- }
+ 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(heads_after.len());
- let changed = heads_after != heads_before;
- // What it brought, walked once.
- let since =
- changed.then(|| crate::document::changes::since(&replica.doc, &heads_before));
- if let Some(since) = &since {
- // They came from it: none goes back (`SyncSession::came_from_peer`).
- let new = peer_state.sync.these_came_from_peer(&since.hashes);
+ stats.heads_seen(settled.heads);
+ let changed = settled.changed;
+ if let Some(new) = settled.new {
stats.new_changes(new);
}
- if carried && !changed {
- // Its heads not ours yet: what it brought waits for predecessors, which
- // isn't having come twice.
- if !crate::document::changes::holds_all(&replica.doc, &said) {
- stats.waiting();
- } else {
- stats.nothing_new(payload_len, writer.is_some(), delivered, change_bytes);
+ 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) = match since {
- Some(since) => ((since.authors, since.unauthored), since.times),
- None => ((Vec::new(), false), Vec::new()),
- };
+ 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.
@@ -666,7 +603,7 @@ pub(crate) async fn handle_sync(
// 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).
- check_level && from_ready && peer_state.sync.have_all_theirs(&replica.doc),
+ settled.level,
changed,
carried,
authors,