diff options
Diffstat (limited to 'src/swarm')
| -rw-r--r-- | src/swarm/bootstrap.rs | 179 | ||||
| -rw-r--r-- | src/swarm/members.rs | 22 | ||||
| -rw-r--r-- | src/swarm/mod.rs | 2 | ||||
| -rw-r--r-- | src/swarm/peer/handshake.rs | 18 | ||||
| -rw-r--r-- | src/swarm/peer/inbound.rs | 38 | ||||
| -rw-r--r-- | src/swarm/peer/keepalive.rs | 17 | ||||
| -rw-r--r-- | src/swarm/reach.rs | 4 | ||||
| -rw-r--r-- | src/swarm/set.rs | 278 | ||||
| -rw-r--r-- | src/swarm/stability.rs | 6 | ||||
| -rw-r--r-- | src/swarm/state_file.rs | 10 | ||||
| -rw-r--r-- | src/swarm/sync.rs | 10 | ||||
| -rw-r--r-- | src/swarm/topology/mod.rs | 31 | ||||
| -rw-r--r-- | src/swarm/working_links.rs | 6 |
13 files changed, 576 insertions, 45 deletions
diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 7626d53..45c86e6 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -39,6 +39,11 @@ const BOOTSTRAP_REPORT: Duration = Duration::from_secs(300); /// Retrying seeds that didn't resolve: first after this, doubling up to the maximum. const RESOLVE_RETRY: Duration = Duration::from_secs(5); const RESOLVE_RETRY_MAX: Duration = Duration::from_secs(300); +/// A seed that resolved, and whose HELLO failed, is said HELLO again this soon, a few +/// times (`HELLO_SOON`): what a node speaks is mostly known a moment after it proved +/// where it is, and a HELLO in a version that can't say this node's kind didn't go. +const HELLO_AGAIN: Duration = Duration::from_millis(250); +const HELLO_SOON: u32 = 4; /// How this node starts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -52,6 +57,27 @@ pub(crate) enum Start { } pub(crate) async fn bootstrap(state: &AppState, seeds: &[String], start: Start) -> Result<()> { + // A set of events is its store's document, and the store's ID its swarm's: it + // starts on what it holds, with nothing in the document the node holds beside. + // Holding nothing of it yet, it first gathers what the set begins from of the + // members it reaches through its seeds (`swarm::set::ask_to_start`). + #[cfg(feature = "federation")] + if state.of_a_set() { + if let Some(store) = state.holding.store_id() { + state.set_expected_swarm_id(store.to_string()).await?; + } + if state.holding.with(|_| ()).is_none() { + reach_seeds(state, seeds).await; + let mut closing = state.closing.subscribe(); + while state.holding.with(|_| ()).is_none() { + crate::swarm::set::ask_to_start(state).await; + tokio::select! { + () = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} + _ = closing.wait_for(|closing| *closing) => return Ok(()), + } + } + } + } if let Start::FromDocument(origin) = start { let Some(swarm_id) = state.swarm_id().await else { bail!("starting on a document without a swarm ID"); @@ -314,6 +340,68 @@ impl StoreStart { })) } + /// The store's own document, a set of events (`--store-document`), kept in the file + /// at `path`: as the file has it, where there is one, which must be this store's; + /// else begun from the root, where the node is given it and pins no checkpoint; else + /// to be gathered of its peers, from the checkpoint `pin` names, or the root, by its + /// name; of `both` kinds, none without a file. What a checkpoint forgot is kept for + /// `keeps`. + pub(crate) fn set( + &self, + path: &Path, + files: &Files, + pin: Option<crate::federation::store::Id>, + keeps: std::time::Duration, + both: bool, + ) -> Result<Option<crate::federation::held::Begun>> { + use crate::federation::fold::Federation; + use crate::federation::held::Begun; + use crate::federation::store::{memory::Store, passing::Start, set::Set}; + let now = std::time::Instant::now(); + let held = files + .read(FileKind::Store, path) + .with_context(|| format!("Reading the store's document {}", path.display()))?; + if let Some(bytes) = held { + let set = Set::<Federation>::load(&bytes, keeps, now).map_err(|refused| { + anyhow::anyhow!( + "The store's document {} doesn't read ({}): move it away only knowing the node then starts anew, and may take what it refused", + path.display(), + refused.0 + ) + })?; + if set.store().id() != self.id { + bail!( + "The store's document {} is of store {}, not {}", + path.display(), + set.store().id(), + self.id + ); + } + info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); + return Ok(Some(Begun::Set(Box::new(set)))); + } + // A node of both kinds makes its set of the store as it reads it of its + // document (`Holding::of_both`). + if both { + return Ok(None); + } + match (&self.root, pin) { + (Some((root, kept)), None) => { + let store = + Store::<Federation>::new(root.clone(), kept.clone()).map_err(|refused| { + anyhow::anyhow!("The store's root is none: {}", refused.0) + })?; + info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)"); + Ok(Some(Begun::Set(Box::new(Set::new(store, keeps))))) + } + (_, pin) => { + let at = pin.unwrap_or(self.id); + info!(swarm_id = %self.id, from = %at, "Joining the swarm holding the store with nothing of it: its set begins from what members give by that name"); + Ok(Some(Begun::Start(Start::new(self.id, at, keeps)))) + } + } + } + /// The swarm's ID: the root's, in hex. pub(crate) fn swarm_id(&self) -> String { self.id.to_string() @@ -512,7 +600,7 @@ fn load_backup(path: &Path, files: &Files) -> Result<Document> { async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut unresolved = seeds.to_vec(); let mut failing = HashSet::new(); - resolve_seeds(state, &mut unresolved, &mut failing).await; + let mut unsaid = resolve_seeds(state, &mut unresolved, &mut failing).await; if unresolved.is_empty() { return; } @@ -520,13 +608,18 @@ async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut closing = state.closing.subscribe(); tokio::spawn(async move { let mut retry = RESOLVE_RETRY; + let mut soon = 0; while !unresolved.is_empty() { tokio::select! { - () = tokio::time::sleep(retry) => {} + () = tokio::time::sleep(if unsaid && soon < HELLO_SOON { HELLO_AGAIN } else { retry }) => {} _ = closing.wait_for(|closing| *closing) => return, } - resolve_seeds(&state, &mut unresolved, &mut failing).await; - retry = (retry * 2).min(RESOLVE_RETRY_MAX); + if unsaid && soon < HELLO_SOON { + soon += 1; + } else { + retry = (retry * 2).min(RESOLVE_RETRY_MAX); + } + unsaid = resolve_seeds(&state, &mut unresolved, &mut failing).await; } }); } @@ -535,7 +628,9 @@ async fn resolve_seeds( state: &AppState, unresolved: &mut Vec<String>, failing: &mut HashSet<String>, -) { +) -> bool { + // Whether a seed resolved and its HELLO failed. + let mut unsaid = false; let mut still = Vec::new(); for seed in unresolved.drain(..) { match state.transport.resolve_seed(&seed).await { @@ -549,6 +644,19 @@ async fn resolve_seeds( crate::swarm::roots::seed_found(state, &peer); if let Err(error) = send_hello_once(state, &peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "Initial HELLO failed; will retry"); + // Again with the seeds that don't resolve yet: nothing else says + // HELLO again to a node that is no neighbour (`peer::worker`). + if let Some(peer_state) = state.get_peer_state(&peer).await { + let mut peer_state = peer_state.lock().await; + if matches!( + peer_state.hello_state, + crate::state::HelloState::AwaitingReply { .. } + ) { + peer_state.hello_state = crate::state::HelloState::NotSent; + } + } + unsaid = true; + still.push(seed); } } Err(error) => { @@ -562,6 +670,7 @@ async fn resolve_seeds( } } *unresolved = still; + unsaid } /// Why the node is still joining, for the log. @@ -631,6 +740,66 @@ mod tests { assert!(joining.starting(None, None).unwrap().is_none()); } + #[cfg(feature = "federation")] + #[test] + fn a_stores_document_is_begun_from_the_root_or_gone_on_with() { + use crate::federation::harness::{self, Party, Spec}; + use crate::federation::store::memory::Offered; + use std::time::{Duration, Instant}; + + let tv = Party::new("tv", 1); + let root = Spec::first(&[&tv], &[]).root(); + let id = Id::of(&root); + let store = StoreStart { + id, + root: Some((root.clone(), Vec::new())), + }; + let joining = StoreStart { id, root: None }; + let dir = crate::files::scratch_dir("store-document"); + let path = dir.join("store.events"); + let files = Files::default(); + let keeps = Duration::from_secs(60); + use crate::federation::held::Begun; + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps, false) { + Ok(Some(Begun::Set(set))) => Some(*set), + Ok(Some(Begun::Start(_)) | None) => None, + Err(error) => panic!("{error:#}"), + }; + // No file: from the root, where given and no checkpoint is pinned; else to be + // gathered of peers. + assert!(set_of(&joining, None).is_none()); + assert!(set_of(&store, Some(Id::of(b"a checkpoint"))).is_none()); + let mut set = set_of(&store, None).expect("from the root"); + let write = tv.write(&[id], "home/tv/a", harness::str("1")); + assert!(matches!( + set.offer(write.clone(), Instant::now()), + Offered::Taken(_) + )); + std::fs::write(&path, set.save(Instant::now())).unwrap(); + // A file: gone on with, the root given or not. + for start in [&store, &joining] { + let read = set_of(start, None).expect("from the file"); + assert_eq!(read.store().taken(), &[Id::of(&write)]); + } + // Of another store, or no document: refused. + let other_root = Spec::first(&[&Party::new("lass", 2)], &[]).root(); + let other = StoreStart { + id: Id::of(&other_root), + root: Some((other_root, Vec::new())), + }; + assert!(other.set(&path, &files, None, keeps, false).is_err()); + std::fs::write(&path, b"something else").unwrap(); + assert!(store.set(&path, &files, None, keeps, false).is_err()); + // A node of both kinds: the file, where there is one; else none here. + std::fs::remove_file(&path).unwrap(); + assert!( + store + .set(&path, &files, None, keeps, true) + .unwrap() + .is_none() + ); + } + /// A fork's root, and the event it keeps on a line of its own: the swarm starts from /// the changes founding it. Without that event: no store's root. #[test] diff --git a/src/swarm/members.rs b/src/swarm/members.rs index eac4d55..5a54593 100644 --- a/src/swarm/members.rs +++ b/src/swarm/members.rs @@ -368,14 +368,16 @@ pub(crate) async fn ensure_registered(state: &AppState) { shortest, ) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); ( - registered(&replica.doc, &local), - alias(&replica.doc, &local), - dashboard(&replica.doc, &local), - addresses(&replica.doc, &local), - millis_at(&replica.doc, &alive_path(&local)), - millis_at(&replica.doc, &window_path(&local)), - shortest_window(&replica.doc, state.electorate_window), + registered(listed, &local), + alias(listed, &local), + dashboard(listed, &local), + addresses(listed, &local), + millis_at(listed, &alive_path(&local)), + millis_at(listed, &window_path(&local)), + shortest_window(listed, state.electorate_window), ) }; let wanted = state.alias.clone(); @@ -454,7 +456,11 @@ pub(crate) async fn ensure_registered(state: &AppState) { // The party it is of, as configured. #[cfg(feature = "federation")] if let Some(ours) = state.holding.party() { - let recorded = party(&state.doc.read().await.doc, &local); + let entries = state.entries(); + let recorded = party( + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &local, + ); if recorded.as_deref() != Some(ours) { let (path, value) = (party_path(&local), json!(ours)); match state diff --git a/src/swarm/mod.rs b/src/swarm/mod.rs index 6c0a242..1637130 100644 --- a/src/swarm/mod.rs +++ b/src/swarm/mod.rs @@ -19,6 +19,8 @@ pub(crate) mod refusals; pub(crate) mod relay; pub(crate) mod roots; pub(crate) mod rtt; +#[cfg(feature = "federation")] +pub(crate) mod set; pub(crate) mod skew; pub(crate) mod source; pub(crate) mod speaking; diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs index 2e5a315..fc0a31b 100644 --- a/src/swarm/peer/handshake.rs +++ b/src/swarm/peer/handshake.rs @@ -144,7 +144,7 @@ async fn transmit_hello(state: &AppState, peer: &str) -> Result<()> { .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: kind_to(state, peer).await.to_owned(), }), ) .await; @@ -180,6 +180,20 @@ async fn say_what_we_speak(state: &AppState, peer: &str) { } } +/// The kind of document this node says to `peer` it holds: the one the peer's +/// handshakes said, of those this node holds; where the peer said none yet, and this +/// node holds more than one, each in turn, HELLO by HELLO, until one is answered. +async fn kind_to(state: &AppState, peer: &str) -> &'static str { + let kinds = state.kinds(); + let Some(peer_state) = state.get_peer_state(peer).await else { + return kinds[0]; + }; + let peer_state = peer_state.lock().await; + peer_state + .kind + .unwrap_or(kinds[peer_state.hello_attempts as usize % kinds.len()]) +} + pub(super) async fn ensure_handshake(state: &AppState, peer: &str) { if let Err(error) = send_hello_once(state, peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "HELLO failed; will retry"); @@ -255,7 +269,7 @@ pub(super) async fn send_hello_reply( .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: kind_to(state, peer).await.to_owned(), }; debug!(to = %peer, ready, "Sending HELLO_REPLY"); diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index a558ded..b6c486d 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -114,12 +114,22 @@ pub(crate) async fn handle_message( ParsedMessage::HelloReply(reply) => Some(&reply.kind), _ => None, }; - if let Some(theirs) = kind.filter(|kind| *kind != crate::document::KIND) { - anyhow::bail!( - "{peer} holds a document of another kind ({theirs}; this node's is {}): they sync \ - nothing; a release that knows the kind does", - crate::document::KIND - ); + if let Some(theirs) = kind { + let Some(held) = state.kinds().iter().find(|held| *held == theirs) else { + anyhow::bail!( + "{peer} holds a document of another kind ({theirs}; this node's is {}): they \ + sync nothing; a release that knows the kind does", + state.kinds().join(" and ") + ); + }; + // Of the kinds this node holds, the one the peer holds: what it is told in + // turn, and passed on. + state + .get_or_create_peer_state(&peer) + .await + .lock() + .await + .kind = Some(held); } // The root its document starts from: another than ours, of our epoch, is another @@ -218,6 +228,18 @@ pub(crate) async fn handle_message( .map_err(|error| anyhow!("Failed to notify sync worker: {error}"))?; } transport::ParsedMessage::Sync(envelope) => { + // Of a set of events: this node's set's to take, where it holds one + // (`swarm::set`); and of an Automerge document nothing, where it holds a set + // alone. + #[cfg(feature = "federation")] + if state.of_a_set() || matches!(envelope.body, transport::SyncBody::Kind(_)) { + if let transport::SyncBody::Kind(body) = envelope.body + && state.holding.has_a_set() + { + crate::swarm::set::received(state, &peer, body).await; + } + return Ok(()); + } if reactivated { ensure_handshake(state, &peer).await; } @@ -251,6 +273,8 @@ pub(crate) async fn handle_message( crate::swarm::blob::handle(state, &peer, blob).await; } transport::ParsedMessage::Status(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An announcement is no keepalive; it is answered only if we lack some of the // heads it announced (`relay::lacks`), so the announcer learns what we have // that it lacks while we pull. Having all of them, we are as far or further, @@ -290,6 +314,8 @@ pub(crate) async fn handle_message( } } transport::ParsedMessage::StatusReply(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An answer to our slow round's announcement: a tree missed. let announced = peer_state.lock().await.slow_announced_at.take(); if let Some(at) = announced { diff --git a/src/swarm/peer/keepalive.rs b/src/swarm/peer/keepalive.rs index 72ab033..bbcc6e3 100644 --- a/src/swarm/peer/keepalive.rs +++ b/src/swarm/peer/keepalive.rs @@ -182,10 +182,21 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta let stamp = state.stamp.borrow(); (stamp.summary(), stamp.epoch, stamp.epoch_seq) }; - let syncs_with_you = match state.get_peer_state(peer).await { - Some(peer_state) => peer_state.lock().await.syncs_on(epoch), - None => false, + let (syncs_with_you, _of_a_set) = match state.get_peer_state(peer).await { + Some(peer_state) => { + let peer_state = peer_state.lock().await; + ( + peer_state.syncs_on(epoch), + peer_state + .kind + .is_some_and(|kind| kind != crate::document::KIND), + ) + } + None => (false, false), }; + // To a peer that holds a set of events, where this node's stands (`swarm::set`). + #[cfg(feature = "federation")] + let heads = crate::swarm::set::stamp(state, _of_a_set).unwrap_or(heads); let (reaches, round_trips) = crate::swarm::reach::published_with_round_trips(state); transport::Status { heads, diff --git a/src/swarm/reach.rs b/src/swarm/reach.rs index 760bcb5..20961ad 100644 --- a/src/swarm/reach.rs +++ b/src/swarm/reach.rs @@ -196,7 +196,9 @@ pub(crate) fn of(said: Option<&(Instant, Vec<u64>)>) -> Option<Vec<u64>> { /// The members of our member list by pair key, to name what neighbours say they reach. pub(crate) async fn names(state: &AppState) -> HashMap<u64, String> { let replica = state.doc.read().await; - members::members(&replica.doc) + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + members::members(listed) .into_iter() .map(|member| (topology::pair_key(&member), member)) .collect() diff --git a/src/swarm/set.rs b/src/swarm/set.rs new file mode 100644 index 0000000..54a48fe --- /dev/null +++ b/src/swarm/set.rs @@ -0,0 +1,278 @@ +//! Passing a set of events on between nodes (`docs/document.md`, A set of events): the +//! swarm's side of `federation::store::passing`, for a node whose store a set carries +//! (`Holding::carrying`). +//! +//! * Where the node stands goes in its STATUSes, keepalives and their replies, as +//! another kind's stamp (`HeadsSummary::Kind`); a peer's is given to the set, and what +//! the set says back goes to that peer. +//! * Everything else the set says goes as a SYNC's body (`SyncBody::Kind`). +//! * What the set took of a peer, or of this node's own, goes on at once to the node's +//! other neighbours, as units: a neighbour that has them takes them for held. +//! +//! Nothing is kept of a peer between messages, and a message lost is nothing to repair: +//! the next keepalive says where the node stands again. + +use std::time::Instant; + +use tracing::debug; + +use crate::federation::store::Id; +use crate::federation::store::passing::{self, Message, Took, Unit}; +use crate::state::AppState; +use crate::swarm::topology; +use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody}; + +/// Whether `peer` holds a set of events, as its handshakes said: what a node of both +/// kinds passes its set on to. A node that holds a set alone takes handshakes of no +/// other. +pub(crate) async fn holds_a_set(state: &AppState, peer: &str) -> bool { + match state.get_peer_state(peer).await { + Some(peer_state) => { + peer_state.lock().await.kind == Some(crate::federation::store::set::KIND) + } + None => false, + } +} + +/// Where this node's set stands, as its STATUSes say it to a peer that holds one +/// (`to_a_set`); none, where the node holds no set, or the peer doesn't. +pub(crate) fn stamp(state: &AppState, to_a_set: bool) -> Option<HeadsSummary> { + if !state.holding.has_a_set() || !(to_a_set || state.holding.of_a_set()) { + return None; + } + // A node still gathering what its set begins from stands nowhere yet. + let stamp = state + .holding + .with_set(|set| rmp_serde::to_vec(&passing::stamp(set)).expect("a stamp encodes")) + .unwrap_or_default(); + Some(HeadsSummary::Kind(stamp)) +} + +/// What a STATUS of `peer` says, where a set carries this node's store: where the +/// peer's set stands is given to this node's, off the caller's task; and the status is +/// handed on saying this node's own stamp, so that what compares stamps for an +/// Automerge document's sake finds nothing to do. +pub(crate) fn heard_status( + state: &AppState, + peer: &str, + mut remote: transport::Status, +) -> transport::Status { + // A peer that says where a set stands holds one. + let of_a_set = matches!(remote.heads, HeadsSummary::Kind(_)); + let Some(ours) = stamp(state, of_a_set) else { + return remote; + }; + if !of_a_set && !state.holding.of_a_set() { + return remote; + } + if let HeadsSummary::Kind(bytes) = std::mem::replace(&mut remote.heads, ours) + && let Ok(stamp) = rmp_serde::from_slice::<passing::Stamp>(&bytes) + { + let (state, peer) = (state.clone(), peer.to_owned()); + tokio::spawn(async move { + handle(&state, &peer, Message::Stamp(stamp)).await; + }); + } + remote +} + +/// What a SYNC of `peer` carries of its set, where a set carries this node's store. +pub(crate) async fn received(state: &AppState, peer: &str, body: Vec<u8>) { + let message = match rmp_serde::from_slice::<Message>(&body) { + Ok(message) => message, + Err(error) => { + debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read"); + return; + } + }; + // Started with nothing: what was asked for, to begin the set from (`ask_to_start`). + if !state.holding.start_wants().is_empty() { + if let Message::Units(units) = message { + let holding = std::sync::Arc::clone(&state.holding); + let begun = tokio::task::spawn_blocking(move || holding.start_take(units)) + .await + .unwrap_or(false); + if begun { + state.notify_store_changed(); + state.topology_changed.notify_one(); + } else { + ask(state, peer).await; + } + } + return; + } + handle(state, peer, message).await; +} + +/// Asks `peer` for what this node's set begins from, where the node started with +/// nothing and still gathers it. +async fn ask(state: &AppState, peer: &str) { + let wants = state.holding.start_wants(); + if !wants.is_empty() { + send(state, peer, &Message::Wants(wants)).await; + } +} + +/// Asks every peer whose handshake this node took for what its set begins from, where +/// the node started with nothing and still gathers it. +pub(crate) async fn ask_to_start(state: &AppState) { + if state.holding.start_wants().is_empty() { + return; + } + for (peer, peer_state) in state.peers_snapshot().await { + let established = + peer_state.lock().await.hello_state == crate::state::HelloState::Established; + if established { + ask(state, &peer).await; + } + } +} + +/// Gives `message` of `peer` to this node's set, sends the peer what the set says back, +/// and passes on what it took. +async fn handle(state: &AppState, peer: &str, message: Message) { + let holding = std::sync::Arc::clone(&state.holding); + // Taking events judges them: off the tasks that read messages. + let made = tokio::task::spawn_blocking(move || { + holding.change_set(|set| passing::receive(set, message, Instant::now())) + }) + .await; + let Ok(Some((replies, took))) = made else { + return; + }; + for reply in replies { + send(state, peer, &reply).await; + } + pass_on(state, Some(peer), took).await; +} + +/// Sends `peer` what this node's set says. +async fn send(state: &AppState, peer: &str, message: &Message) { + let (epoch, epoch_seq) = state.epoch_stamp(); + let envelope = transport::SyncEnvelope { + epoch: transport::EpochTag::of(epoch), + epoch_seq, + body: SyncBody::Kind(rmp_serde::to_vec(message).expect("a message encodes")), + ready: state.is_ready().await && !state.is_closing(), + writer: None, + delivered: false, + sent: state.clock.now_millis(), + signatures: serde_bytes::ByteBuf::new(), + }; + if let Err(error) = state + .transport + .send_message(peer, &ParsedMessage::Sync(envelope)) + .await + { + debug!(peer = %peer, error = %format!("{error:#}"), "Saying of our set failed"); + } +} + +/// Passes on what this node's set took, of `from` or of the node's own: to its other +/// neighbours, as units; and tells what waits on the store, or on who is a member. +async fn pass_on(state: &AppState, from: Option<&str>, took: Took) { + if took.is_empty() { + return; + } + state.notify_store_changed(); + // Entries are where members are reached, and events may change who is one. + state.topology_changed.notify_one(); + let names = took + .events + .iter() + .map(|id| id.0) + .chain(entry_names(state, &took.entries)); + let units: Vec<Unit> = state + .holding + .with_set(|set| names.filter_map(|name| passing::unit(set, &name)).collect()) + .unwrap_or_default(); + if units.is_empty() { + return; + } + let message = Message::Units(units); + for peer in state.active_peers_on_local_epoch().await { + if Some(peer.as_str()) != from + && topology::is_neighbour(state, &peer) + && holds_a_set(state, &peer).await + { + send(state, &peer, &message).await; + } + } +} + +/// The names of the entries this node's set holds of `nodes`. +fn entry_names(state: &AppState, nodes: &[String]) -> Vec<[u8; 32]> { + state + .holding + .with_set(|set| { + nodes + .iter() + .filter_map(|node| set.entry(node).map(|entry| entry.name())) + .collect() + }) + .unwrap_or_default() +} + +/// Passes on events this node's set took of the node itself (the API, its own votes): +/// `taken`, by their names. +pub(crate) async fn wrote(state: &AppState, taken: Vec<Id>) { + pass_on( + state, + None, + Took { + events: taken, + entries: Vec::new(), + }, + ) + .await; +} + +/// Passes on this node's own entry, which its set just took. +pub(crate) async fn registered(state: &AppState) { + pass_on( + state, + None, + Took { + events: Vec::new(), + entries: vec![state.local_id().to_owned()], + }, + ) + .await; +} + +/// On a node of both kinds, puts its entry as the document it holds has it as its entry +/// in the set, where the two differ, and passes it on: what the node says of itself, +/// it says to the peers of either kind. +pub(crate) async fn mirror_entry(state: &AppState) { + use crate::federation::store::entry::Entry; + use crate::federation::store::set::Put; + + if !state.holding.has_a_set() || state.holding.of_a_set() { + return; + } + let Some(key) = state.node_key.clone() else { + return; + }; + let node = state.local_id().to_owned(); + let own = crate::swarm::members::member_path(&node); + let written = crate::document::view::read_path(&state.doc.read().await.doc, &own); + let Ok(Some(serde_json::Value::Object(written))) = written else { + return; + }; + let put = state.holding.change_set(|set| { + let held = set.entry(&node); + if held.and_then(|entry| entry.value()).as_ref() == Some(&written) { + return None; + } + let count = held.map_or(1, |entry| entry.count() + 1); + Some(set.put_entry(Entry::new( + &set.store().id(), + &key, + count, + &serde_json::Value::Object(written), + ))) + }); + if put.flatten() == Some(Put::Taken) { + registered(state).await; + } +} diff --git a/src/swarm/stability.rs b/src/swarm/stability.rs index 8163e06..c163778 100644 --- a/src/swarm/stability.rs +++ b/src/swarm/stability.rs @@ -178,7 +178,11 @@ pub(crate) async fn tick(state: &AppState) { return; } let local = state.local_id().to_owned(); - let current = members::tier(&state.doc.read().await.doc, &local); + let entries = state.entries(); + let current = members::tier( + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &local, + ); let desired = { let mut stability = lock(state); diff --git a/src/swarm/state_file.rs b/src/swarm/state_file.rs index 415fb1a..51b00cc 100644 --- a/src/swarm/state_file.rs +++ b/src/swarm/state_file.rs @@ -133,8 +133,9 @@ pub(crate) async fn update(state: &AppState, now: bool) { let seeds = { let replica = state.doc.read().await; + let entries = state.entries(); seeds( - &replica.doc, + &crate::document::view::members_of(&entries, &replica.doc), state.local_id(), state.electorate_window, state.clock.now_millis().as_u64(), @@ -185,7 +186,12 @@ pub(crate) async fn update(state: &AppState, now: bool) { /// Where to rejoin through: the addresses of members alive within the electorate /// window, stable ones first, of at most `MAX_SEEDS` members, sorted. Changes only when /// members join, leave, move or change tier, so the file rarely does. -fn seeds(doc: &crate::document::Document, me: &str, window: Duration, now: u64) -> Vec<String> { +fn seeds( + doc: &dyn crate::document::view::Read, + me: &str, + window: Duration, + now: u64, +) -> Vec<String> { let (mut stable, transient): (Vec<String>, Vec<String>) = members::electorate(doc, now, window) .into_iter() .filter(|pk| pk != me) diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index 65a02ea..3939377 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -63,6 +63,13 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> { } } + // 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(state, peer).await { + return Ok(()); + } + let we_ready = state.is_ready().await; let validated_swarm = { @@ -405,6 +412,9 @@ pub(crate) async fn handle_sync( // 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 } => { diff --git a/src/swarm/topology/mod.rs b/src/swarm/topology/mod.rs index df9a27e..1f99cd8 100644 --- a/src/swarm/topology/mod.rs +++ b/src/swarm/topology/mod.rs @@ -382,7 +382,7 @@ pub(crate) fn with_recorded( #[cfg(feature = "federation")] fn of_the_store( state: &AppState, - doc: &crate::document::Document, + doc: &dyn crate::document::view::Read, listed: Vec<String>, ) -> Vec<String> { if !state.holding.tells_members() { @@ -411,11 +411,13 @@ async fn nearby(state: &AppState, inputs: &Inputs<'_>) -> BTreeSet<String> { } let group: BTreeMap<String, BTreeSet<String>> = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); inputs .transports .iter() .filter(|(member, _)| { - members::party(&replica.doc, member) + members::party(listed, member) .is_some_and(|party| parties.contains(&party.as_str())) }) .map(|(member, transports)| (member.clone(), transports.clone())) @@ -738,32 +740,31 @@ pub(crate) async fn refresh(state: &AppState) -> Option<NeighbourChange> { } let (current, stable, transports, alive, k, recorded) = { let replica = state.doc.read().await; - members::apply(state, &replica.doc); + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + members::apply(state, listed); let k = swarm_neighbours(&replica.doc, state.neighbours_k); switch_ways(state, swarm_ways(&replica.doc, state.configured_ways)); - let current = members::members(&replica.doc); + let current = members::members(listed); #[cfg(feature = "federation")] - let current = of_the_store(state, &replica.doc, current); + let current = of_the_store(state, listed, current); // Those that said they are alive within the electorate window. - let alive: BTreeSet<String> = members::electorate( - &replica.doc, - state.clock.now_millis().0, - state.electorate_window, - ) - .into_iter() - .collect(); + let alive: BTreeSet<String> = + members::electorate(listed, state.clock.now_millis().0, state.electorate_window) + .into_iter() + .collect(); let stable: BTreeSet<String> = current .iter() - .filter(|m| members::tier(&replica.doc, m) == members::Tier::Stable) + .filter(|m| members::tier(listed, m) == members::Tier::Stable) .cloned() .collect(); let transports: BTreeMap<String, BTreeSet<String>> = current .iter() - .map(|m| (m.clone(), schemes(&members::addresses(&replica.doc, m)))) + .map(|m| (m.clone(), schemes(&members::addresses(listed, m)))) .collect(); let recorded: BTreeMap<String, members::RecordedLinks> = current .iter() - .map(|m| (m.clone(), members::links(&replica.doc, m))) + .map(|m| (m.clone(), members::links(listed, m))) .filter(|(_, links)| *links != members::RecordedLinks::default()) .collect(); (current, stable, transports, alive, k, recorded) diff --git a/src/swarm/working_links.rs b/src/swarm/working_links.rs index b384919..ca3a22b 100644 --- a/src/swarm/working_links.rs +++ b/src/swarm/working_links.rs @@ -182,11 +182,13 @@ pub(crate) async fn check(state: &AppState) { // would leave none. let (recorded, links) = { let replica = state.doc.read().await; - let recorded = members::links(&replica.doc, &me); + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + let recorded = members::links(listed, &me); let mut links = links; links.unreached.retain(|member| { recorded.unreached.contains(member) - || !members::links(&replica.doc, member).unreached.contains(&me) + || !members::links(listed, member).unreached.contains(&me) }); (recorded, links) }; |
