From 2ae7562083f5f96490f90e9398762cf6a024d51e Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 04:00:43 +0000 Subject: document: a unit's name, which the swarm passes on by document::UnitId: the name of a unit of a document as its kind has it, an Automerge change's hash. What the swarm announces, forwards along trees, tells a peer it refused and drops is named so (the dissemination, relay, refusals, AppState::drop_taken), and the session is told so what a peer gets from another; a change's hash it is where the document is asked, and on the wire. --- src/document/mod.rs | 33 +++++++++++++++++++++++++++++++++ src/document/passing.rs | 16 ++++++++++++---- src/document/sync.rs | 34 ++++++++++++++++++++++------------ src/simtest/policy.rs | 2 +- src/state/host.rs | 6 +++--- src/swarm/dissemination.rs | 10 +++++----- src/swarm/flood.rs | 6 +++--- src/swarm/plumtree.rs | 14 +++++++------- src/swarm/refusals.rs | 15 ++++++++++----- src/swarm/relay.rs | 4 +++- src/swarm/sync.rs | 10 +++++----- src/swarm/tree.rs | 8 ++++---- 12 files changed, 108 insertions(+), 50 deletions(-) diff --git a/src/document/mod.rs b/src/document/mod.rs index 3872ea9..2e65bee 100644 --- a/src/document/mod.rs +++ b/src/document/mod.rs @@ -13,6 +13,39 @@ pub(crate) use automerge::{ ScalarValue, }; +/// The name of a unit of a document, as its kind of document has it (`docs/document.md`, +/// Passing on): what is announced, asked for, refused and counted is named so, above the +/// seam. An Automerge document's units are its changes, named by their hashes. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) struct UnitId(pub(crate) [u8; 32]); + +impl From for UnitId { + fn from(hash: ChangeHash) -> Self { + UnitId(hash.0) + } +} + +impl From for ChangeHash { + fn from(unit: UnitId) -> Self { + ChangeHash(unit.0) + } +} + +impl std::fmt::Display for UnitId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + for byte in self.0 { + write!(f, "{byte:02x}")?; + } + Ok(()) + } +} + +impl std::fmt::Debug for UnitId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self}") + } +} + /// The version of Automerge this build makes documents with: a remake needs the same on /// every node, and a federation the same encoding of a change (`remake::snapshot`). pub(crate) fn engine_version() -> &'static str { diff --git a/src/document/passing.rs b/src/document/passing.rs index f745d42..10b888d 100644 --- a/src/document/passing.rs +++ b/src/document/passing.rs @@ -232,7 +232,7 @@ pub(crate) struct Taken { /// 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, + pub(crate) roots: Vec, /// 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 @@ -280,7 +280,7 @@ pub(crate) fn take( heads_before, said, refused_again: outcome.refused_again, - roots: outcome.roots, + roots: outcome.roots.into_iter().map(Into::into).collect(), forged: outcome.forged, fresh_actor: outcome.fresh_actor, }; @@ -305,7 +305,7 @@ pub(crate) struct Settled { /// predecessors (the peer's heads aren't the document's yet), or had come before. pub(crate) waits: Option, /// Whose the changes it brought are, whether any is nobody's, and when each was made. - pub(crate) authors: Vec<(String, Vec)>, + pub(crate) authors: Vec<(String, Vec)>, pub(crate) unauthored: bool, pub(crate) times: Vec, /// Where asked: whether the document holds all the peer said it has. @@ -354,7 +354,15 @@ pub(crate) fn settle( 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), + Some(since) => ( + since + .authors + .into_iter() + .map(|(author, hashes)| (author, hashes.into_iter().map(Into::into).collect())) + .collect(), + since.unauthored, + since.times, + ), None => (Vec::new(), false, Vec::new()), }; Settled { diff --git a/src/document/sync.rs b/src/document/sync.rs index 2de8e60..e1caaef 100644 --- a/src/document/sync.rs +++ b/src/document/sync.rs @@ -761,12 +761,15 @@ impl SyncSession { /// The peer has `changes`, or will without us (another parent in their writer's /// tree brings them, `swarm::tree::forward`): counted as sent, they don't go to it, /// unless it asks for them (`resend_if_needed`). - pub(crate) fn known_to_peer(&mut self, changes: &[crate::document::ChangeHash], now: Instant) { + pub(crate) fn known_to_peer(&mut self, changes: &[crate::document::UnitId], now: Instant) { self.known_elsewhere .retain(|_, at| now.saturating_duration_since(*at) < KNOWN_ELSEWHERE_KEPT); - for hash in changes { - if self.state.sent_hashes.insert(*hash) { - self.known_elsewhere.insert(*hash, now); + for hash in changes + .iter() + .map(|unit| crate::document::ChangeHash::from(*unit)) + { + if self.state.sent_hashes.insert(hash) { + self.known_elsewhere.insert(hash, now); } } } @@ -779,11 +782,14 @@ impl SyncSession { pub(crate) fn with_predecessors( &mut self, doc: &Document, - changes: &[crate::document::ChangeHash], + changes: &[crate::document::UnitId], now: Instant, ) { - for hash in changes { - let Some(change) = doc.get_change_by_hash(hash) else { + for hash in changes + .iter() + .map(|unit| crate::document::ChangeHash::from(*unit)) + { + let Some(change) = doc.get_change_by_hash(&hash) else { continue; }; for dep in change.deps() { @@ -1275,6 +1281,10 @@ mod model; mod tests { use super::*; + fn units(hashes: &[crate::document::ChangeHash]) -> Vec { + hashes.iter().copied().map(Into::into).collect() + } + /// After a loss, the changes the peer lacks go in one message, not one per round /// trip (`answer_for_everything_since_shared`). #[test] @@ -1540,7 +1550,7 @@ mod tests { let (now, bytes) = (Instant::now(), SyncBytes::default()); for i in 0..100 { change(&mut ours, |doc| doc.put(ROOT, "key", i).unwrap()); - a.known_to_peer(&ours.get_heads(), now); + a.known_to_peer(&units(&ours.get_heads()), now); } theirs.merge(&mut ours.clone()).unwrap(); assert_eq!(a.sent_hashes_len(), 100); @@ -1559,7 +1569,7 @@ mod tests { // Older heads than those, said later (a STATUS overtaken): nothing changes. change(&mut ours, |doc| doc.put(ROOT, "key", 100).unwrap()); - a.known_to_peer(&ours.get_heads(), now); + a.known_to_peer(&units(&ours.get_heads()), now); let older = theirs.get_heads(); theirs.merge(&mut ours.clone()).unwrap(); assert_eq!(a.heard_heads(&ours, &theirs.get_heads()), 1); @@ -2093,7 +2103,7 @@ mod tests { let (now, bytes) = (Instant::now(), SyncBytes::default()); change(&mut ours, |doc| doc.put(ROOT, "elsewhere", 2).unwrap()); - a.known_to_peer(&ours.get_heads(), Instant::now()); + a.known_to_peer(&units(&ours.get_heads()), Instant::now()); let message = a.generate(&ours, now, bytes).expect("our heads moved"); a.send_succeeded(a.id()); let carried = decode(&message).unwrap().change_bytes(); @@ -2122,9 +2132,9 @@ mod tests { let (now, bytes) = (Instant::now(), SyncBytes::default()); change(&mut ours, |doc| doc.put(ROOT, "elsewhere", 2).unwrap()); - a.known_to_peer(&ours.get_heads(), now); + a.known_to_peer(&units(&ours.get_heads()), now); change(&mut ours, |doc| doc.put(ROOT, "along", 3).unwrap()); - a.with_predecessors(&ours, &ours.get_heads(), now); + a.with_predecessors(&ours, &units(&ours.get_heads()), now); let message = a.generate(&ours, now, bytes).expect("our heads moved"); b.receive(&mut theirs, decode(&message).unwrap()).unwrap(); assert_eq!(theirs.get_heads(), ours.get_heads(), "both in one message"); diff --git a/src/simtest/policy.rs b/src/simtest/policy.rs index e58f0c3..3531ac7 100644 --- a/src/simtest/policy.rs +++ b/src/simtest/policy.rs @@ -847,7 +847,7 @@ async fn a_refusal_naming_the_root() { replica.epoch_seq, ) }; - crate::swarm::refusals::tell(&a, b.local_id(), epoch, epoch_seq, vec![root]).await; + crate::swarm::refusals::tell(&a, b.local_id(), epoch, epoch_seq, vec![root.into()]).await; tokio::time::sleep(Duration::from_secs(3)).await; assert!(holds(&b, "notes/x").await, "b dropped its document"); assert_eq!(b.remake.list_quarantine(|entry| entry.id.clone()).len(), 0); diff --git a/src/state/host.rs b/src/state/host.rs index 357814e..66bb71c 100644 --- a/src/state/host.rs +++ b/src/state/host.rs @@ -105,7 +105,7 @@ impl AppState { /// second member to say so (`peer` the first, `why` its rules' reason), where it has /// another neighbour: its rules and one peer's word might both be off, the swarm's /// not. Two members colluding pass it; it guards against one. - pub(crate) async fn drop_taken(&self, root: ChangeHash, peer: &str, why: &str) { + pub(crate) async fn drop_taken(&self, root: crate::document::UnitId, peer: &str, why: &str) { /// Changes a drop takes, at most, on one peer's word: more, or more than a tenth /// of the document (past `SMALL_DROP`), wait for another's. const BIG_DROP: usize = 100; @@ -125,7 +125,7 @@ impl AppState { return None; } use crate::document::dropping::{Kept, Tainted}; - let tainted = match Tainted::of(&replica.doc, root)? { + let tainted = match Tainted::of(&replica.doc, root.into())? { Ok(tainted) => tainted, Err(Kept::Root) => { error!(change = %root, "Asked to drop the epoch's root; kept it"); @@ -144,7 +144,7 @@ impl AppState { let mut screening = state.screening.lock_or_recover(); let said = screening .of(replica.epoch_seq) - .hold_drop(root, &peer); + .hold_drop(root.into(), &peer); if said < 2 { error!(change = %root, peer = %peer, changes = count, why = %why, "A peer says we hold a change the swarm's rules refuse, and ours do too, but dropping it takes much: waiting for another member to say so"); return None; diff --git a/src/swarm/dissemination.rs b/src/swarm/dissemination.rs index 4c15d0f..11d9295 100644 --- a/src/swarm/dissemination.rs +++ b/src/swarm/dissemination.rs @@ -11,7 +11,7 @@ use async_trait::async_trait; use tracing::trace; -use crate::document::ChangeHash; +use crate::document::UnitId; use crate::state::AppState; use crate::swarm::tree::Plan; @@ -34,7 +34,7 @@ pub(crate) trait Dissemination: Send + Sync + 'static { state: &AppState, writer: u64, from: &str, - changes: &[ChangeHash], + changes: &[UnitId], ) -> Option; /// What a sync message from `peer` says about how well this works (`/admin/stats`): @@ -46,7 +46,7 @@ pub(crate) trait Dissemination: Send + Sync + 'static { peer: &str, writer: Option, carried: bool, - authors: &[(String, Vec)], + authors: &[(String, Vec)], ); /// `peer` asks us to send it `writer`'s changes at once (`eager`, a GRAFT) or to @@ -59,7 +59,7 @@ pub(crate) trait Dissemination: Send + Sync + 'static { /// `peer` told us of `heads` we lack (a STATUS: an announcement, or its keepalive's), /// for a way that minds which neighbour has changes first (PlumTree). By default /// nothing. - fn announced(&self, peer: &str, heads: &[ChangeHash]) { + fn announced(&self, peer: &str, heads: &[UnitId]) { let _ = (peer, heads); } @@ -83,7 +83,7 @@ pub(crate) async fn pass_on( state: &AppState, writer: u64, from: &str, - changes: &[ChangeHash], + changes: &[UnitId], mut plan: Plan, ) -> Plan { if !changes.is_empty() { diff --git a/src/swarm/flood.rs b/src/swarm/flood.rs index 39cb096..2883f80 100644 --- a/src/swarm/flood.rs +++ b/src/swarm/flood.rs @@ -8,7 +8,7 @@ use async_trait::async_trait; -use crate::document::ChangeHash; +use crate::document::UnitId; use crate::state::AppState; use crate::swarm::dissemination::{Dissemination, pass_on}; use crate::swarm::topology; @@ -41,7 +41,7 @@ impl Dissemination for Flood { state: &AppState, writer: u64, from: &str, - changes: &[ChangeHash], + changes: &[UnitId], ) -> Option { let plan = self.plan(state, writer).await?; Some(pass_on(state, writer, from, changes, plan).await) @@ -55,7 +55,7 @@ impl Dissemination for Flood { peer: &str, writer: Option, carried: bool, - authors: &[(String, Vec)], + authors: &[(String, Vec)], ) { let _ = peer; if writer.is_some() && carried && authors.is_empty() { diff --git a/src/swarm/plumtree.rs b/src/swarm/plumtree.rs index 9560b9f..340fa68 100644 --- a/src/swarm/plumtree.rs +++ b/src/swarm/plumtree.rs @@ -45,7 +45,7 @@ use async_trait::async_trait; use tokio::time::Instant; use tracing::debug; -use crate::document::ChangeHash; +use crate::document::UnitId; use crate::locks::MutexExt; use crate::state::AppState; use crate::swarm::dissemination::{Dissemination, pass_on}; @@ -99,7 +99,7 @@ const SETTLE_UNKNOWN: Duration = Duration::from_secs(2); #[derive(Default)] pub(crate) struct PlumTree { lazy: Mutex>, - announced: Mutex>, + announced: Mutex>, ahead_times: Mutex>, /// When we last grafted each link (`settling`). grafted: Mutex>, @@ -124,7 +124,7 @@ impl PlumTree { /// pushes in a row: its link is the faster, by at least an announcement's delay /// (`relay::ANNOUNCE_DELAY`), which a push over it doesn't wait. The changes are /// forgotten as announced. - fn ahead(&self, peer: &str, authors: &[(String, Vec)]) -> Option { + fn ahead(&self, peer: &str, authors: &[(String, Vec)]) -> Option { let now = Instant::now(); let told: Vec<(String, Instant)> = { let mut announced = self.announced.lock_or_recover(); @@ -186,7 +186,7 @@ impl PlumTree { } /// The changes, come another way, are forgotten as announced. - fn forget_announced(&self, authors: &[(String, Vec)]) { + fn forget_announced(&self, authors: &[(String, Vec)]) { let mut announced = self.announced.lock_or_recover(); for change in authors.iter().flat_map(|(_, changes)| changes) { announced.remove(change); @@ -241,7 +241,7 @@ impl Dissemination for PlumTree { state: &AppState, writer: u64, from: &str, - changes: &[ChangeHash], + changes: &[UnitId], ) -> Option { let plan = self.plan(state, writer).await?; Some(pass_on(state, writer, from, changes, plan).await) @@ -262,7 +262,7 @@ impl Dissemination for PlumTree { peer: &str, writer: Option, carried: bool, - authors: &[(String, Vec)], + authors: &[(String, Vec)], ) { match writer { Some(writer) if carried && authors.is_empty() => { @@ -304,7 +304,7 @@ impl Dissemination for PlumTree { } /// The first to tell us of each head is the one noticed. - fn announced(&self, peer: &str, heads: &[ChangeHash]) { + fn announced(&self, peer: &str, heads: &[UnitId]) { let mut announced = self.announced.lock_or_recover(); if announced.len() + heads.len() > MAX_ANNOUNCED { announced.clear(); diff --git a/src/swarm/refusals.rs b/src/swarm/refusals.rs index 652f9bc..bdc727e 100644 --- a/src/swarm/refusals.rs +++ b/src/swarm/refusals.rs @@ -18,7 +18,7 @@ use std::time::Duration; use tracing::{debug, warn}; -use crate::document::ChangeHash; +use crate::document::UnitId; use crate::document::replica::Epoch; use crate::state::AppState; use crate::transport::{ParsedMessage, RefusalsMessage}; @@ -34,13 +34,13 @@ pub(crate) async fn tell( peer: &str, epoch: Epoch, epoch_seq: u32, - mut changes: Vec, + mut changes: Vec, ) { changes.truncate(MAX_LISTED); let message = ParsedMessage::Refusals(RefusalsMessage { epoch, epoch_seq, - changes, + changes: changes.into_iter().map(Into::into).collect(), }); if let Err(error) = state.transport.send_message(peer, &message).await { // Told again with the next refusal. @@ -53,7 +53,12 @@ pub(crate) async fn tell( pub(crate) async fn received(state: &AppState, peer: &str, message: RefusalsMessage) { let doc = std::sync::Arc::clone(&state.doc); let screening = std::sync::Arc::clone(&state.screening); - let changes: Vec = message.changes.into_iter().take(MAX_LISTED).collect(); + let changes: Vec = message + .changes + .into_iter() + .take(MAX_LISTED) + .map(Into::into) + .collect(); let judged = tokio::task::spawn_blocking(move || { use crate::locks::MutexExt; let replica = doc.blocking_read(); @@ -76,7 +81,7 @@ pub(crate) async fn received(state: &AppState, peer: &str, message: RefusalsMess let mut refused = None; let mut taken = Vec::new(); for hash in changes { - match crate::access::rules::judge_held(&replica.doc, replica.epoch, &hash) { + match crate::access::rules::judge_held(&replica.doc, replica.epoch, &hash.into()) { Some(Err(why)) => { refused = Some((hash, why)); break; diff --git a/src/swarm/relay.rs b/src/swarm/relay.rs index 54749b0..560a41e 100644 --- a/src/swarm/relay.rs +++ b/src/swarm/relay.rs @@ -153,7 +153,7 @@ pub(crate) struct Pending { pub(crate) async fn announce( state: &AppState, from: &str, - writers: &[(u64, Vec)], + writers: &[(u64, Vec)], unauthored: bool, ) { if !state.initial_sync_done.load(Ordering::Acquire) { @@ -343,6 +343,8 @@ pub(crate) async fn pull_after_grace(state: &AppState, peer: &str, remote: &tran crate::document::changes::missing(&replica.doc, remote.heads.listed()) }; if !missing.is_empty() { + let missing: Vec = + missing.into_iter().map(Into::into).collect(); state.dissemination().announced(peer, &missing); let grace = state .lock_rtt() diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index 006df9d..bb99547 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -484,9 +484,9 @@ pub(crate) async fn handle_sync( bool, bool, bool, - (Vec<(String, Vec)>, bool), + (Vec<(String, Vec)>, bool), Option, - Option<(u32, Vec)>, + Option<(u32, Vec)>, ); tokio::task::spawn_blocking(move || -> Result> { let (payload_len, message) = @@ -658,7 +658,7 @@ pub(crate) async fn handle_sync( } // Caught up: our other neighbours may lack what the source had. if changed || just_caught_up { - let writers: Vec<(u64, Vec)> = authors + let writers: Vec<(u64, Vec)> = authors .into_iter() .map(|(author, changes)| (crate::swarm::topology::pair_key(&author), changes)) .collect(); @@ -856,7 +856,7 @@ async fn download_and_apply_delta( async fn own_changes( state: &AppState, seen_heads: &mut Vec, -) -> Option> { +) -> 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) { @@ -867,7 +867,7 @@ async fn own_changes( .authors .into_iter() .find(|(author, _)| author == state.local_id()) - .map(|(_, hashes)| hashes) + .map(|(_, hashes)| hashes.into_iter().map(Into::into).collect()) } pub(crate) async fn run_sync_worker(state: AppState, mut rx: mpsc::UnboundedReceiver) { diff --git a/src/swarm/tree.rs b/src/swarm/tree.rs index 4d5afd8..0dd4e31 100644 --- a/src/swarm/tree.rs +++ b/src/swarm/tree.rs @@ -388,7 +388,7 @@ pub(crate) async fn note_arrival( peer: &str, writer: Option, carried: bool, - authors: &[(String, Vec)], + authors: &[(String, Vec)], ) { match writer { Some(writer) if carried => { @@ -663,7 +663,7 @@ pub(crate) async fn forward( state: &AppState, writer: u64, from: &str, - changes: &[crate::document::ChangeHash], + changes: &[crate::document::UnitId], ) -> Option { let plan = plan(state, writer).await?; Some(crate::swarm::dissemination::pass_on(state, writer, from, changes, plan).await) @@ -688,7 +688,7 @@ impl crate::swarm::dissemination::Dissemination for WritersTrees { state: &AppState, writer: u64, from: &str, - changes: &[crate::document::ChangeHash], + changes: &[crate::document::UnitId], ) -> Option { forward(state, writer, from, changes).await } @@ -699,7 +699,7 @@ impl crate::swarm::dissemination::Dissemination for WritersTrees { peer: &str, writer: Option, carried: bool, - authors: &[(String, Vec)], + authors: &[(String, Vec)], ) { note_arrival(state, peer, writer, carried, authors).await; } -- cgit v1.3.1