aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/federation/held.rs15
-rw-r--r--src/simtest/holding.rs80
-rw-r--r--src/state/mod.rs67
-rw-r--r--src/swarm/bootstrap.rs8
-rw-r--r--src/swarm/mod.rs2
-rw-r--r--src/swarm/peer/inbound.rs13
-rw-r--r--src/swarm/peer/keepalive.rs3
-rw-r--r--src/swarm/set.rs174
-rw-r--r--src/swarm/sync.rs7
9 files changed, 369 insertions, 0 deletions
diff --git a/src/federation/held.rs b/src/federation/held.rs
index fec21ab..cd53727 100644
--- a/src/federation/held.rs
+++ b/src/federation/held.rs
@@ -538,6 +538,10 @@ impl Holding {
/// what its store's checkpoint keeps, then what it took after it, then what it holds
/// back, stopped (`Store::held_back`).
pub(crate) fn lacking(&self, doc: &impl ReadDoc) -> Vec<(Id, Vec<u8>)> {
+ // A set of events is the store's own document: it lacks none of it.
+ if self.of_a_set {
+ return Vec::new();
+ }
let mut held: HashSet<Id> = events::ids(doc).into_iter().collect();
let mut inner = self.inner.lock_or_recover();
inner.left.retain(|(id, _)| !held.contains(id));
@@ -1344,6 +1348,17 @@ pub(crate) async fn write(
bytes: Vec<u8>,
) -> Result<(), store::StoreError> {
let id = Id::of(&bytes);
+ // Into a set of events it goes as the store takes it, where it didn't yet; and is
+ // passed on, as written.
+ if state.of_a_set() {
+ let holding = Arc::clone(&state.holding);
+ let _ = tokio::task::spawn_blocking(move || holding.offer(bytes)).await;
+ let held = state.holding.with(|store| store.get(&id).is_some());
+ if held == Some(true) {
+ crate::swarm::set::wrote(state, vec![id]).await;
+ }
+ return Ok(());
+ }
state
.mutate_doc_for(
user,
diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs
index 16158b1..4a8098b 100644
--- a/src/simtest/holding.rs
+++ b/src/simtest/holding.rs
@@ -1726,3 +1726,83 @@ async fn store_attack_31() {
)
.await;
}
+
+/// A store carried by a set of events on `root`, for a node of `party`.
+fn of_a_set(party: &str, root: &[u8]) -> Holding {
+ use crate::federation::store::set::Set;
+ holding(party).carrying(Set::new(
+ Store::<Federation>::new(root.to_vec(), Vec::new()).expect("a root"),
+ Duration::from_secs(600),
+ ))
+}
+
+/// How many members' entries `node`'s set holds.
+fn entries(node: &AppState) -> usize {
+ node.holding
+ .with_set(|set| set.entries().count())
+ .unwrap_or(0)
+}
+
+/// Where `node`'s set stands.
+fn stands(node: &AppState) -> Option<crate::federation::store::passing::Stamp> {
+ node.holding
+ .with_set(crate::federation::store::passing::stamp)
+}
+
+/// tv lists a and b, lass lists c: each node's store is carried by a set of events,
+/// its own document, and nothing is in the Automerge document it holds. Each registers,
+/// and its entry reaches the others; events put on a and on c reach all three; and they
+/// come to stand alike.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_swarm_of_sets_passes_entries_and_events_on() {
+ let sim = Sim::with_identity(91);
+ let (tv, lass, _) = three();
+ let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]);
+ let nodes: Vec<AppState> = [("a", "tv"), ("b", "tv"), ("c", "lass")]
+ .into_iter()
+ .map(|(name, party)| {
+ let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] };
+ let root = root.clone();
+ sim.start_with(
+ name,
+ &seeds,
+ Start::FromDocument(Origin::Root),
+ move |config| {
+ config.store = Some(id);
+ config.holding = of_a_set(party, &root);
+ },
+ )
+ })
+ .collect();
+ let members: Vec<&AppState> = nodes.iter().collect();
+ let members = &members;
+ sim.wait_ready(members, SOON).await;
+ for node in members.iter() {
+ assert_eq!(node.kind(), crate::federation::store::set::KIND);
+ assert!(node.holding.tells_members());
+ }
+ sim.wait_until("each holds the three entries", SOON, move || async move {
+ members.iter().all(|node| entries(node) == 3)
+ })
+ .await;
+
+ let on_a = tv.write(&[id], "home/tv/x", s("1"));
+ let on_c = lass.write(&[id], "home/lass/y", s("2"));
+ let ids = [Id::of(&on_a), Id::of(&on_c)];
+ put(members[0], &[&on_a]).await;
+ put(members[2], &[&on_c]).await;
+ sim.wait_until("a, b and c hold both events", SOON, move || async move {
+ members.iter().all(|node| holds(node, &ids))
+ })
+ .await;
+ sim.wait_until("they stand alike", SOON, move || async move {
+ let first = stands(members[0]);
+ first.is_some() && members.iter().all(|node| stands(node) == first)
+ })
+ .await;
+ for node in members.iter() {
+ assert_eq!(read(node, |store| store.state().values().len()), Some(2));
+ // Nothing went into the document it holds beside.
+ assert!(node.doc.read().await.heads().is_empty());
+ }
+}
diff --git a/src/state/mod.rs b/src/state/mod.rs
index 5fefe11..d512b2b 100644
--- a/src/state/mod.rs
+++ b/src/state/mod.rs
@@ -50,6 +50,10 @@ use crate::swarm::throughput::ThroughputTable;
use crate::transport;
use crate::transport::firewall::Firewall;
+/// Why a write is refused where a set of events carries the node's store.
+#[cfg(feature = "federation")]
+const NOT_A_SETS: &str = "this node's document is a set of events: what is written to it is events, and of its members' entries the node's own";
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum NodeLifecycle {
// TODO maybe rename discovered_swarm_id to swarm_id if that doesn't impair readability.
@@ -636,6 +640,10 @@ impl AppState {
T: Send + 'static,
E: From<StoreError> + Send + 'static,
{
+ #[cfg(feature = "federation")]
+ if self.of_a_set() {
+ return self.mutate_set(f).await;
+ }
self.mutate_doc_as(None, Sign::Protocol, false, move |write| f(write))
.await
.map(|(out, _)| out)
@@ -654,6 +662,10 @@ impl AppState {
T: Send + 'static,
E: From<StoreError> + Send + 'static,
{
+ #[cfg(feature = "federation")]
+ if self.of_a_set() {
+ return self.mutate_set(f).await;
+ }
self.mutate_doc_as(user, sign, true, move |write| f(write))
.await
.map(|(out, _)| out)
@@ -673,9 +685,64 @@ impl AppState {
T: Send + 'static,
E: From<StoreError> + Send + 'static,
{
+ #[cfg(feature = "federation")]
+ if self.of_a_set() {
+ return Err(E::from(StoreError::Refused(NOT_A_SETS.to_owned())));
+ }
self.mutate_doc_as(user, sign, true, f).await
}
+ /// A write where a set of events carries this node's store (`federation::store::
+ /// set`): to the members' entries as a document has them (`Holding::entries`), of
+ /// which the node writes its own alone. What its own reads as after is put as its
+ /// next entry, signed, and passed on (`swarm::set`).
+ #[cfg(feature = "federation")]
+ async fn mutate_set<T, E>(&self, f: impl FnOnce(&mut dyn Write) -> Result<T, E>) -> Result<T, E>
+ where
+ E: From<StoreError>,
+ {
+ use crate::document::view::Read;
+ use crate::federation::store::entry::Entry;
+ use crate::federation::store::set::Put;
+
+ let refused = || E::from(StoreError::Refused(NOT_A_SETS.to_owned()));
+ let own = crate::swarm::members::member_path(self.local_id());
+ let before = self.holding.entries().unwrap_or_default();
+ let mut after = before.clone();
+ let out = f(&mut after)?;
+ let was = before.read_path(&own).map_err(E::from)?;
+ let is = after.read_path(&own).map_err(E::from)?;
+ // Nothing but its own entry, which it doesn't take away.
+ let (mut rest_before, mut rest_after) = (before, after);
+ let _ = rest_before.delete_path(&own, true);
+ let _ = rest_after.delete_path(&own, true);
+ if rest_before != rest_after {
+ return Err(refused());
+ }
+ let Some(is) = is else {
+ return if was.is_some() {
+ Err(refused())
+ } else {
+ Ok(out)
+ };
+ };
+ if Some(&is) == was.as_ref() {
+ return Ok(out);
+ }
+ let Some(key) = self.node_key.clone() else {
+ return Err(refused());
+ };
+ let node = self.local_id().to_owned();
+ let put = self.holding.change_set(|set| {
+ let count = set.entry(&node).map_or(1, |entry| entry.count() + 1);
+ set.put_entry(Entry::new(&set.store().id(), &key, count, &is))
+ });
+ if put == Some(Put::Taken) {
+ crate::swarm::set::registered(self).await;
+ }
+ Ok(out)
+ }
+
/// [`mutate_doc_for`](Self::mutate_doc_for); with `registering_first`, after this
/// node's registration if the policy needs it first. While writes are held
/// (`writes_held`), after they no longer are.
diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs
index a0e4db7..24da958 100644
--- a/src/swarm/bootstrap.rs
+++ b/src/swarm/bootstrap.rs
@@ -52,6 +52,14 @@ 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.
+ #[cfg(feature = "federation")]
+ if state.of_a_set()
+ && let Some(swarm_id) = state.holding.with(|store| store.id().to_string())
+ {
+ state.set_expected_swarm_id(swarm_id).await?;
+ }
if let Start::FromDocument(origin) = start {
let Some(swarm_id) = state.swarm_id().await else {
bail!("starting on a document without a swarm ID");
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/inbound.rs b/src/swarm/peer/inbound.rs
index dbf1a2e..0354356 100644
--- a/src/swarm/peer/inbound.rs
+++ b/src/swarm/peer/inbound.rs
@@ -218,6 +218,15 @@ 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, where one carries this node's store: its own to
+ // take (`swarm::set`), and nothing of an Automerge document's.
+ #[cfg(feature = "federation")]
+ if state.of_a_set() {
+ if let transport::SyncBody::Kind(body) = envelope.body {
+ crate::swarm::set::received(state, &peer, body).await;
+ }
+ return Ok(());
+ }
if reactivated {
ensure_handshake(state, &peer).await;
}
@@ -251,6 +260,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 +301,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..6ab49d8 100644
--- a/src/swarm/peer/keepalive.rs
+++ b/src/swarm/peer/keepalive.rs
@@ -186,6 +186,9 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta
Some(peer_state) => peer_state.lock().await.syncs_on(epoch),
None => false,
};
+ // Where a set of events carries the store, where that stands (`swarm::set`).
+ #[cfg(feature = "federation")]
+ let heads = crate::swarm::set::stamp(state).unwrap_or(heads);
let (reaches, round_trips) = crate::swarm::reach::published_with_round_trips(state);
transport::Status {
heads,
diff --git a/src/swarm/set.rs b/src/swarm/set.rs
new file mode 100644
index 0000000..ec2415e
--- /dev/null
+++ b/src/swarm/set.rs
@@ -0,0 +1,174 @@
+//! 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};
+
+/// Where this node's set stands, as its STATUSes say it; none, where no set carries its
+/// store.
+pub(crate) fn stamp(state: &AppState) -> Option<HeadsSummary> {
+ let stamp = state.holding.with_set(passing::stamp)?;
+ Some(HeadsSummary::Kind(
+ rmp_serde::to_vec(&stamp).expect("a stamp encodes"),
+ ))
+}
+
+/// 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 {
+ let Some(ours) = stamp(state) else {
+ 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>) {
+ match rmp_serde::from_slice::<Message>(&body) {
+ Ok(message) => handle(state, peer, message).await,
+ Err(error) => {
+ debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read");
+ }
+ }
+}
+
+/// 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) {
+ 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;
+}
diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs
index c953752..5e736a1 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`): of the Automerge document
+ // a node holds beside one, nothing.
+ #[cfg(feature = "federation")]
+ if state.of_a_set() {
+ return Ok(());
+ }
+
let we_ready = state.is_ready().await;
let validated_swarm = {