//! 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 { 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::(&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) { let message = match rmp_serde::from_slice::(&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 = 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) { 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; } }