From af9de78d7de36848f6ff115c9710fb90d2468af2 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 13:58:03 +0000 Subject: swarm: a node says the kind of the document it holds In its handshakes, and checks a peer's against it (AppState::kind): a set of events where one carries its store (Holding::of_a_set), else Automerge's, as it was for every node. --- src/state/mod.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/state') diff --git a/src/state/mod.rs b/src/state/mod.rs index 604f6ae..36dab9d 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -377,6 +377,16 @@ impl AppState { *self.closing.borrow() } + /// The kind of this node's document (`document::KIND`, or a set of events where + /// one carries its store). + pub(crate) fn kind(&self) -> &'static str { + #[cfg(feature = "federation")] + if self.holding.of_a_set() { + return self.holding.kind(); + } + crate::document::KIND + } + pub(crate) fn local_id(&self) -> &str { self.transport.local_id() } -- cgit v1.3.1 From 362633603e9fc1912fd35807da5653dc1273a5be Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:31:03 +0000 Subject: swarm: members read of where the node's document keeps them The swarm reads its members, their addresses, aliases, parties, tiers and links, at _continuum/members of the document the node holds. Where the node's document keeps them apart and hands them over as a tree (AppState::entries: a set of events, Holding::entries), they are read of that (view::members_of): by the topology, the node's registration, stability, working links, the state file's seeds, reach, and the API's aliases, dashboards and tier. No node's document does so yet but one whose store a set carries, which none starts as. --- src/api/cors.rs | 6 ++++-- src/api/dashboard/mod.rs | 8 +++++--- src/api/events.rs | 6 +++++- src/api/peers.rs | 6 +++++- src/api/stats.rs | 8 +++----- src/document/view.rs | 17 ++++++++++++++++- src/state/mod.rs | 24 ++++++++++++++++++++++++ src/swarm/members.rs | 22 ++++++++++++++-------- src/swarm/reach.rs | 4 +++- src/swarm/stability.rs | 6 +++++- src/swarm/state_file.rs | 10 ++++++++-- src/swarm/topology/mod.rs | 31 ++++++++++++++++--------------- src/swarm/working_links.rs | 6 ++++-- 13 files changed, 112 insertions(+), 42 deletions(-) (limited to 'src/state') diff --git a/src/api/cors.rs b/src/api/cors.rs index 287daf1..652a53e 100644 --- a/src/api/cors.rs +++ b/src/api/cors.rs @@ -50,8 +50,10 @@ async fn allowed(state: &AppState, origin: &str) -> bool { return true; } let replica = state.doc.read().await; - members::members(&replica.doc).iter().any(|member| { - members::dashboard(&replica.doc, member) + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); + members::members(listed).iter().any(|member| { + members::dashboard(listed, member) .and_then(|url| origin_of(&url)) .is_some_and(|theirs| theirs == origin) }) diff --git a/src/api/dashboard/mod.rs b/src/api/dashboard/mod.rs index f5a91ac..4d9f3f4 100644 --- a/src/api/dashboard/mod.rs +++ b/src/api/dashboard/mod.rs @@ -354,6 +354,8 @@ async fn build(state: &AppState, graph: &Graph) -> JsonValue { let peers = serde_json::to_value(&list).unwrap_or_default(); let (aliases, dashboards, remakes) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); // The remakes of our epoch, with who voted: the map shows them. let remakes = crate::remake::current( &state.remake, @@ -362,11 +364,11 @@ async fn build(state: &AppState, graph: &Graph) -> JsonValue { state.clock.now_millis(), state.timing.dormant_after.as_millis() as u64, ); - let dashboards: std::collections::HashMap = members::members(&replica.doc) + let dashboards: std::collections::HashMap = members::members(listed) .into_iter() - .filter_map(|pk| members::dashboard(&replica.doc, &pk).map(|url| (pk, url))) + .filter_map(|pk| members::dashboard(listed, &pk).map(|url| (pk, url))) .collect(); - (members::aliases(&replica.doc), dashboards, remakes) + (members::aliases(listed), dashboards, remakes) }; let local = state.local_id(); let intended: Map = graph diff --git a/src/api/events.rs b/src/api/events.rs index 1c4b826..e711eac 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -235,7 +235,11 @@ async fn heard(state: &AppState) -> std::collections::HashMap { /// checkpoint, what its parties signed that moving there /// refuses (`beside`, `signed_beside`). async fn counts(State(state): State) -> Response { - let aliases = crate::swarm::members::aliases(&state.doc.read().await.doc); + let entries = state.entries(); + let aliases = crate::swarm::members::aliases(crate::document::view::members_of( + &entries, + &state.doc.read().await.doc, + )); let heard = heard(&state).await; with_store(&state, |store| { let read = store.state(); diff --git a/src/api/peers.rs b/src/api/peers.rs index 586c32d..2282e6c 100644 --- a/src/api/peers.rs +++ b/src/api/peers.rs @@ -171,7 +171,11 @@ pub(crate) async fn peer_list(state: &AppState) -> PeerListResponse { let now = Instant::now(); let local_epoch = state.local_epoch(); - let mut aliases = crate::swarm::members::aliases(&state.doc.read().await.doc); + let entries = state.entries(); + let mut aliases = crate::swarm::members::aliases(crate::document::view::members_of( + &entries, + &state.doc.read().await.doc, + )); let names = crate::swarm::reach::names(&state).await; let named = |keys: Vec| -> Vec { let mut named: Vec = keys diff --git a/src/api/stats.rs b/src/api/stats.rs index a5fe0d8..86b93d5 100644 --- a/src/api/stats.rs +++ b/src/api/stats.rs @@ -308,13 +308,11 @@ pub(crate) async fn collect(state: &AppState, list: &PeerListResponse) -> StatsR let (heads, tier, remakes) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); let heads = replica.heads().len(); let remakes = crate::remake::summary(&state.remake, &replica.doc, replica.epoch); - ( - heads, - members::tier(&replica.doc, state.local_id()), - remakes, - ) + (heads, members::tier(listed, state.local_id()), remakes) }; let now_ms = state.clock.now_millis(); let saved = state.stats.saved_size(); diff --git a/src/document/view.rs b/src/document/view.rs index d8819d2..ff93ae6 100644 --- a/src/document/view.rs +++ b/src/document/view.rs @@ -121,11 +121,17 @@ pub(crate) fn delete_path( /// a kind that keeps what the node reads at paths otherwise (a set of events its /// members' entries), and hands it over so; and for what writes there through `Write`, /// which then looks at what the tree holds after. -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(not(feature = "federation"), allow(dead_code))] pub(crate) struct Tree(pub(crate) JsonValue); #[cfg_attr(not(feature = "federation"), allow(dead_code))] +impl Default for Tree { + fn default() -> Self { + Self::new() + } +} + impl Tree { /// A tree holding nothing. pub(crate) fn new() -> Self { @@ -221,6 +227,15 @@ impl Write for Tree { } } +/// Where the node reads its members: `entries`, where its document keeps them apart +/// and hands them over as a tree (`AppState::entries`); else `doc` itself. +pub(crate) fn members_of<'a>(entries: &'a Option, doc: &'a dyn Read) -> &'a dyn Read { + match entries { + Some(tree) => tree, + None => doc, + } +} + #[cfg(test)] mod tree_tests { use serde_json::json; diff --git a/src/state/mod.rs b/src/state/mod.rs index 36dab9d..5fefe11 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -387,6 +387,30 @@ impl AppState { crate::document::KIND } + /// Whether this node's document is a set of events (`federation::store::set`): + /// the Automerge document it holds is empty then, and nothing passes it on. + pub(crate) fn of_a_set(&self) -> bool { + #[cfg(feature = "federation")] + { + self.holding.of_a_set() + } + #[cfg(not(feature = "federation"))] + { + false + } + } + + /// The members' entries as a document has them, where this node's document keeps + /// them apart (a set of events, `Holding::entries`): none, where they are in the + /// document it holds. + pub(crate) fn entries(&self) -> Option { + #[cfg(feature = "federation")] + if self.of_a_set() { + return self.holding.entries(); + } + None + } + pub(crate) fn local_id(&self) -> &str { self.transport.local_id() } diff --git a/src/swarm/members.rs b/src/swarm/members.rs index eac4d55..60d7e06 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/reach.rs b/src/swarm/reach.rs index 760bcb5..2e8c151 100644 --- a/src/swarm/reach.rs +++ b/src/swarm/reach.rs @@ -196,7 +196,9 @@ pub(crate) fn of(said: Option<&(Instant, Vec)>) -> Option> { /// The members of our member list by pair key, to name what neighbours say they reach. pub(crate) async fn names(state: &AppState) -> HashMap { 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/stability.rs b/src/swarm/stability.rs index 8163e06..aae96d6 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..a8c371c 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 { +fn seeds( + doc: &dyn crate::document::view::Read, + me: &str, + window: Duration, + now: u64, +) -> Vec { let (mut stable, transient): (Vec, Vec) = members::electorate(doc, now, window) .into_iter() .filter(|pk| pk != me) diff --git a/src/swarm/topology/mod.rs b/src/swarm/topology/mod.rs index df9a27e..ef778d0 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, ) -> Vec { if !state.holding.tells_members() { @@ -411,11 +411,13 @@ async fn nearby(state: &AppState, inputs: &Inputs<'_>) -> BTreeSet { } let group: BTreeMap> = { 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 { } 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 = members::electorate( - &replica.doc, - state.clock.now_millis().0, - state.electorate_window, - ) - .into_iter() - .collect(); + let alive: BTreeSet = + members::electorate(listed, state.clock.now_millis().0, state.electorate_window) + .into_iter() + .collect(); let stable: BTreeSet = 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> = 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 = 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..9e9022a 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) }; -- cgit v1.3.1 From 8e97bcfa65e92da21df912cc5e19cf18027b82b8 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:33:09 +0000 Subject: swarm: a node whose store a set of events carries Such a node (Holding::carrying) holds an Automerge document with nothing in it, which nothing passes on, and its set is its document: * swarm::set passes the set on. Where it stands goes in the node's STATUSes as another kind's stamp, and a peer's is given to the set; what the set says besides goes as a SYNC's body; what the set took, of a peer or of the node itself, goes on to the node's other neighbours. What compares stamps for an Automerge document's sake is handed the node's own, and finds nothing to do; the Automerge sync isn't begun. * The node writes its own entry (AppState::mutate_set): what writes protocol data through a view writes to the members' entries as a tree, and what the node's own reads as after is put as its next entry, signed and passed on. Anything else is refused, and so is a write to an Automerge document as such. * An event the node writes (held::write) is offered to the set and passed on; a set lacks nothing of its store to put again. * The node's swarm is its store's, said at its start. A simulation: three such nodes of two parties register, and each holds the others' entries; events put on two of them reach all three, and they come to stand alike, the documents they hold beside empty. --- src/federation/held.rs | 15 ++++ src/simtest/holding.rs | 80 ++++++++++++++++++++ src/state/mod.rs | 67 +++++++++++++++++ src/swarm/bootstrap.rs | 8 ++ src/swarm/mod.rs | 2 + src/swarm/peer/inbound.rs | 13 ++++ src/swarm/peer/keepalive.rs | 3 + src/swarm/set.rs | 174 ++++++++++++++++++++++++++++++++++++++++++++ src/swarm/sync.rs | 7 ++ 9 files changed, 369 insertions(+) create mode 100644 src/swarm/set.rs (limited to 'src/state') 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)> { + // 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 = 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, ) -> 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::::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 { + 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 = [("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 + 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 + 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 + 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(&self, f: impl FnOnce(&mut dyn Write) -> Result) -> Result + where + E: From, + { + 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 { + 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::(&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) { + match rmp_serde::from_slice::(&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 = 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) { + 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 = { -- cgit v1.3.1 From bb860d2cf0adad80016edb7a7baed4df291b828c Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:59:37 +0000 Subject: federation: what a set hands the node to read is as a store's document Beside its members' entries, the policy of a swarm holding a store and the swarm's ID (Holding::entries): what reads a document for them reads the same of a node on a set. Tokens are checked against it (api::login): their issuer's entry is there, and a node takes none another issued, as the policy says; read of the empty Automerge document beside, every token was refused. --- src/api/login.rs | 26 ++++++++++++++------------ src/federation/held.rs | 27 +++++++++++++++++++++++---- src/state/mod.rs | 3 ++- 3 files changed, 39 insertions(+), 17 deletions(-) (limited to 'src/state') diff --git a/src/api/login.rs b/src/api/login.rs index e442ea2..a5bfde5 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -115,10 +115,12 @@ pub(crate) async fn bearer( let now = state.clock.now_millis().as_u64(); let verified = { let replica = state.doc.read().await; - let verified = token::verify(&replica.doc, &text, &swarm, now); + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); + let verified = token::verify(listed, &text, &swarm, now); #[cfg(feature = "federation")] let verified = - verified.and_then(|claims| token::issued_here(&replica.doc, state.local_id(), claims)); + verified.and_then(|claims| token::issued_here(listed, state.local_id(), claims)); verified } .and_then(|claims| { @@ -559,17 +561,17 @@ async fn credentials_end( /// sessions. async fn refused_now(state: &AppState, who: &Credentials) -> Option { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); match who { - Credentials::Token(claims) => { - token::still_taken(&replica.doc, claims).err().or_else(|| { - state - .ended_sessions - .lock_or_recover() - .contains_key(&claims.session) - .then_some(token::Refused::Ended) - }) - } - Credentials::User(user) => token::user_taken(&replica.doc, user).err(), + Credentials::Token(claims) => token::still_taken(listed, claims).err().or_else(|| { + state + .ended_sessions + .lock_or_recover() + .contains_key(&claims.session) + .then_some(token::Refused::Ended) + }), + Credentials::User(user) => token::user_taken(listed, user).err(), } } diff --git a/src/federation/held.rs b/src/federation/held.rs index fd43062..bb34407 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1108,13 +1108,23 @@ impl Holding { } } - /// The members' entries as the node reads them of a document, each at - /// `_continuum/members/`, where a set of events carries the store: the - /// document's place for them, which a set keeps apart. + /// What the node reads of its document at paths, where a set of events carries the + /// store: what a document holding a store has there. The members' entries, each at + /// `_continuum/members/`, which a set keeps apart; the policy of a swarm + /// holding a store; and the swarm's ID, the store's. pub(crate) fn entries(&self) -> Option { use crate::document::view::{Tree, Write}; self.with_set(|set| { let mut tree = Tree::new(); + // Into a tree of maps alone: nothing is in the way of any of it. + let _ = tree.write_path( + &crate::access::policy::path(), + &events::policy(Federation::NAME), + ); + let _ = tree.write_path( + &meta::path(&[meta::SWARM]), + &serde_json::Value::String(set.store().id().to_string()), + ); for entry in set.entries() { if let Some(value) = entry.value() { let path = [ @@ -1122,7 +1132,6 @@ impl Holding { meta::MEMBERS.to_owned(), entry.node(), ]; - // Into a tree of maps alone: nothing is in the way. let _ = tree.write_path(&path, &serde_json::Value::Object(value)); } } @@ -2966,6 +2975,16 @@ mod tests { Some("tv".to_owned()) ); assert!(holding.member(&key.id(), Some("tv")) == Some(true)); + // And the rest a document holding a store has for the node to read: the + // policy, by which a node takes no token another issued, and the swarm's ID. + assert!(matches!( + crate::access::policy::of(&tree), + crate::access::policy::Policy::Store(_) + )); + assert_eq!( + crate::document::view::read_path(&tree, &meta::path(&[meta::SWARM])).unwrap(), + Some(serde_json::Value::String(Id::of(&root).to_string())) + ); assert!(Holding::default().entries().is_none()); } } diff --git a/src/state/mod.rs b/src/state/mod.rs index d512b2b..21478de 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -404,7 +404,8 @@ impl AppState { } } - /// The members' entries as a document has them, where this node's document keeps + /// What the node reads of a document at paths (its members, the policy, the swarm's + /// ID), where this node's document keeps /// them apart (a set of events, `Holding::entries`): none, where they are in the /// document it holds. pub(crate) fn entries(&self) -> Option { -- cgit v1.3.1 From 93defc68f9b99da921f4746e91e5cee9e6e3f1b9 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 17:39:23 +0000 Subject: swarm: a node says to each peer the kind that peer holds, of those it holds A node holds one kind of document, or, to come, its store in both (Holding::kinds, of_both). The kind a peer's handshakes say is kept with the peer, where the node holds it too, and is what the node says to it in turn; to a peer that said none yet, a node of more than one kind says each in turn, HELLO by HELLO, until one is answered. A node of one kind says and takes that one, as before. --- src/federation/held.rs | 33 +++++++++++++++++++++++++++------ src/simtest/holding.rs | 4 ++-- src/state/mod.rs | 15 +++++++++------ src/state/peer.rs | 4 ++++ src/swarm/peer/handshake.rs | 18 ++++++++++++++++-- src/swarm/peer/inbound.rs | 22 ++++++++++++++++------ 6 files changed, 74 insertions(+), 22 deletions(-) (limited to 'src/state') diff --git a/src/federation/held.rs b/src/federation/held.rs index 51d8ef0..154544f 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -117,6 +117,9 @@ pub(crate) struct Holding { written: Mutex>, /// Whether a set of events carries the store (`carrying`), from the node's start on. of_a_set: bool, + /// Whether the node holds the store in the document a swarm syncs otherwise too + /// (`of_both`): a node of both kinds, by which a running swarm moves to sets. + both: bool, // A std mutex: never held while waiting for the document. inner: Mutex, } @@ -278,6 +281,7 @@ impl Holding { members: RwLock::default(), voter: None, of_a_set: false, + both: false, document: None, written: Mutex::default(), inner: Mutex::new(Inner { @@ -1145,18 +1149,35 @@ impl Holding { /// The kind of the document that carries the store: a set of events, or the /// document the node holds, which the store is read from. pub(crate) fn kind(&self) -> &'static str { - if self.of_a_set { - super::store::set::KIND - } else { - crate::document::KIND - } + self.kinds()[0] } - /// Whether a set of events carries the store. + /// Whether a set of events carries the store, and nothing else does. pub(crate) fn of_a_set(&self) -> bool { + self.of_a_set && !self.both + } + + /// Whether the node holds a set of events, alone or beside the Automerge document. + pub(crate) fn has_a_set(&self) -> bool { self.of_a_set } + /// Itself, holding its store in the Automerge document too, beside the set. + pub(crate) fn of_both(mut self) -> Self { + self.both = true; + self + } + + /// The kinds of document the node holds its store in, which it says in + /// handshakes: the one it says first, first. + pub(crate) fn kinds(&self) -> &'static [&'static str] { + match (self.of_a_set, self.both) { + (true, true) => &[crate::document::KIND, super::store::set::KIND], + (true, false) => &[super::store::set::KIND], + (false, _) => &[crate::document::KIND], + } + } + /// What `f` makes of the set of events carrying the store, where one does. pub(crate) fn with_set(&self, f: impl FnOnce(&Set) -> T) -> Option { match &self.inner.lock_or_recover().store { diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index ebc7528..0841a75 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1778,7 +1778,7 @@ async fn a_swarm_of_sets_passes_entries_and_events_on() { let members = &members; sim.wait_ready(members, SOON).await; for node in members.iter() { - assert_eq!(node.kind(), crate::federation::store::set::KIND); + assert_eq!(node.kinds(), [crate::federation::store::set::KIND]); assert!(node.holding.tells_members()); } sim.wait_until("each holds the three entries", SOON, move || async move { @@ -1967,7 +1967,7 @@ async fn a_node_of_a_set_joins_with_nothing_but_the_stores_id() { ); }, ); - assert_eq!(c.kind(), crate::federation::store::set::KIND); + assert_eq!(c.kinds(), [crate::federation::store::set::KIND]); assert!(read(&c, |_| ()).is_none()); sim.wait_ready(&[&c], SOON).await; let (all, ids) = (&[&a, &b, &c], &ids); diff --git a/src/state/mod.rs b/src/state/mod.rs index 21478de..0ffa91e 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -381,14 +381,17 @@ impl AppState { *self.closing.borrow() } - /// The kind of this node's document (`document::KIND`, or a set of events where - /// one carries its store). - pub(crate) fn kind(&self) -> &'static str { + /// The kinds of document this node holds, which it says in handshakes: more than + /// one where it holds its store in both (`Holding::kinds`). + pub(crate) fn kinds(&self) -> &'static [&'static str] { #[cfg(feature = "federation")] - if self.holding.of_a_set() { - return self.holding.kind(); + { + self.holding.kinds() + } + #[cfg(not(feature = "federation"))] + { + &[crate::document::KIND] } - crate::document::KIND } /// Whether this node's document is a set of events (`federation::store::set`): diff --git a/src/state/peer.rs b/src/state/peer.rs index 721a754..356736a 100644 --- a/src/state/peer.rs +++ b/src/state/peer.rs @@ -92,6 +92,9 @@ pub(crate) struct PeerState { /// The party its handshakes name, in a swarm holding a store (`swarm::peer::members`). #[cfg(feature = "federation")] pub(crate) party: Option, + /// The kind of document its handshakes say it holds, of those this node holds: what + /// this node says to it in turn, and passes on to it (`swarm::peer::inbound`). + pub(crate) kind: Option<&'static str>, pub(crate) hello_state: HelloState, /// Wait between unanswered HELLOs; reset whenever a new handshake starts. pub(crate) hello_backoff: Backoff, @@ -339,6 +342,7 @@ impl PeerState { tree_writer: None, left: false, hello_attempts: 0, + kind: None, last_hello_at: None, unreachable_since: None, incidents: Incidents::default(), diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs index fc1bc86..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: state.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: state.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 0354356..35d67c8 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 != state.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", - state.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 -- cgit v1.3.1 From 00e88cd983766abec32b5a14a8cbf20932a27f3c Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 17:57:55 +0000 Subject: swarm: members read of a set's entries over the document's What a set hands the node to read was read in the document's place; it is read over it now (view::Listed): at a path, what the set's tree holds, else what the document does, and maps of both as one. A node on a set alone reads the same as before, its document being empty; one holding its store in both, to come, reads the members of both. --- src/api/cors.rs | 2 +- src/api/dashboard/mod.rs | 2 +- src/api/events.rs | 2 +- src/api/login.rs | 4 +- src/api/peers.rs | 2 +- src/api/stats.rs | 2 +- src/document/view.rs | 161 +++++++++++++++++++++++++++++++++++++++++++-- src/state/mod.rs | 2 +- src/swarm/members.rs | 4 +- src/swarm/reach.rs | 2 +- src/swarm/stability.rs | 2 +- src/swarm/state_file.rs | 2 +- src/swarm/topology/mod.rs | 4 +- src/swarm/working_links.rs | 2 +- 14 files changed, 171 insertions(+), 22 deletions(-) (limited to 'src/state') diff --git a/src/api/cors.rs b/src/api/cors.rs index 652a53e..6ead19f 100644 --- a/src/api/cors.rs +++ b/src/api/cors.rs @@ -51,7 +51,7 @@ async fn allowed(state: &AppState, origin: &str) -> bool { } let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); members::members(listed).iter().any(|member| { members::dashboard(listed, member) .and_then(|url| origin_of(&url)) diff --git a/src/api/dashboard/mod.rs b/src/api/dashboard/mod.rs index 4d9f3f4..5d74df4 100644 --- a/src/api/dashboard/mod.rs +++ b/src/api/dashboard/mod.rs @@ -355,7 +355,7 @@ async fn build(state: &AppState, graph: &Graph) -> JsonValue { let (aliases, dashboards, remakes) = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); // The remakes of our epoch, with who voted: the map shows them. let remakes = crate::remake::current( &state.remake, diff --git a/src/api/events.rs b/src/api/events.rs index e711eac..3fece6e 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -236,7 +236,7 @@ async fn heard(state: &AppState) -> std::collections::HashMap { /// refuses (`beside`, `signed_beside`). async fn counts(State(state): State) -> Response { let entries = state.entries(); - let aliases = crate::swarm::members::aliases(crate::document::view::members_of( + let aliases = crate::swarm::members::aliases(&crate::document::view::members_of( &entries, &state.doc.read().await.doc, )); diff --git a/src/api/login.rs b/src/api/login.rs index a5bfde5..09c68df 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -116,7 +116,7 @@ pub(crate) async fn bearer( let verified = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); let verified = token::verify(listed, &text, &swarm, now); #[cfg(feature = "federation")] let verified = @@ -562,7 +562,7 @@ async fn credentials_end( async fn refused_now(state: &AppState, who: &Credentials) -> Option { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); match who { Credentials::Token(claims) => token::still_taken(listed, claims).err().or_else(|| { state diff --git a/src/api/peers.rs b/src/api/peers.rs index 2282e6c..ed7d97f 100644 --- a/src/api/peers.rs +++ b/src/api/peers.rs @@ -172,7 +172,7 @@ pub(crate) async fn peer_list(state: &AppState) -> PeerListResponse { let now = Instant::now(); let local_epoch = state.local_epoch(); let entries = state.entries(); - let mut aliases = crate::swarm::members::aliases(crate::document::view::members_of( + let mut aliases = crate::swarm::members::aliases(&crate::document::view::members_of( &entries, &state.doc.read().await.doc, )); diff --git a/src/api/stats.rs b/src/api/stats.rs index 86b93d5..651d6ba 100644 --- a/src/api/stats.rs +++ b/src/api/stats.rs @@ -309,7 +309,7 @@ pub(crate) async fn collect(state: &AppState, list: &PeerListResponse) -> StatsR let (heads, tier, remakes) = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); let heads = replica.heads().len(); let remakes = crate::remake::summary(&state.remake, &replica.doc, replica.epoch); (heads, members::tier(listed, state.local_id()), remakes) diff --git a/src/document/view.rs b/src/document/view.rs index ff93ae6..8df88b3 100644 --- a/src/document/view.rs +++ b/src/document/view.rs @@ -227,12 +227,96 @@ impl Write for Tree { } } -/// Where the node reads its members: `entries`, where its document keeps them apart -/// and hands them over as a tree (`AppState::entries`); else `doc` itself. -pub(crate) fn members_of<'a>(entries: &'a Option, doc: &'a dyn Read) -> &'a dyn Read { - match entries { - Some(tree) => tree, - None => doc, +/// Where the node reads its members, the policy and the swarm's ID: of what its +/// document keeps apart and hands over as a tree (`AppState::entries`), where it does, +/// over the document it holds. A node holding its store in a set of events alone reads +/// the tree, the document beside being empty; one holding it in both reads the members +/// of both. +pub(crate) fn members_of<'a>(entries: &'a Option, doc: &'a dyn Read) -> Listed<'a> { + Listed { + over: entries.as_ref(), + under: doc, + } +} + +/// A tree over a document (`members_of`): at a path, what the tree holds there, else +/// what the document does; where both hold maps, the two as one, the tree's values over +/// the document's. +pub(crate) struct Listed<'a> { + over: Option<&'a Tree>, + under: &'a dyn Read, +} + +/// `over` on `under`: maps as one, key by key; anything else, `over`. +fn laid(over: JsonValue, under: JsonValue) -> JsonValue { + match (over, under) { + (JsonValue::Object(mut over), JsonValue::Object(under)) => { + for (key, below) in under { + let merged = match over.remove(&key) { + Some(above) => laid(above, below), + None => below, + }; + over.insert(key, merged); + } + JsonValue::Object(over) + } + (over, _) => over, + } +} + +impl Listed<'_> { + fn read( + &self, + path: &[String], + under: impl FnOnce(&dyn Read) -> Result, StoreError>, + ) -> Result, StoreError> { + let Some(over) = self.over else { + return under(self.under); + }; + // The tree first: where it holds a value that is no map, the document isn't + // asked, nor is what it holds on the way in the way. + match over.read_path(path) { + Ok(Some(above)) if !above.is_object() => Ok(Some(above)), + Ok(above) => match (above, under(self.under)) { + (Some(above), Ok(Some(below))) => Ok(Some(laid(above, below))), + (Some(above), _) => Ok(Some(above)), + (None, below) => below, + }, + Err(_) => under(self.under), + } + } +} + +impl Read for Listed<'_> { + fn read_path(&self, path: &[String]) -> Result, StoreError> { + self.read(path, |doc| doc.read_path(path)) + } + + fn read_plain(&self, path: &[String]) -> Result, StoreError> { + self.read(path, |doc| doc.read_plain(path)) + } + + fn read_typed(&self, path: &[String]) -> Result, StoreError> { + self.read(path, |doc| doc.read_typed(path)) + } + + fn keys_at(&self, path: &[String]) -> Result>, StoreError> { + let below = self.under.keys_at(path); + let Some(over) = self.over else { + return below; + }; + match (over.keys_at(path)?, below) { + (Some(mut above), Ok(Some(below))) => { + for key in below { + if !above.contains(&key) { + above.push(key); + } + } + Ok(Some(above)) + } + (Some(above), _) => Ok(Some(above)), + (None, below) => below, + } } } @@ -309,4 +393,69 @@ mod tree_tests { tree.delete_path(&path(&["a", "d"]), true).unwrap(); assert_eq!(tree.read_path(&[]).unwrap(), Some(json!({}))); } + + #[test] + fn a_tree_over_a_document_reads_as_both() { + let mut under = Tree::new(); + under + .write_path(&path(&["m", "a"]), &json!({"alias": "a", "tier": 1})) + .unwrap(); + under + .write_path(&path(&["m", "b"]), &json!({"alias": "b"})) + .unwrap(); + under + .write_path(&path(&["only", "under"]), &json!(1)) + .unwrap(); + let mut over = Tree::new(); + over.write_path(&path(&["m", "a"]), &json!({"alias": "A"})) + .unwrap(); + over.write_path(&path(&["m", "c"]), &json!({"alias": "c"})) + .unwrap(); + over.write_path(&path(&["policy"]), &json!("p")).unwrap(); + let entries = Some(over); + let listed = members_of(&entries, &under); + // Keys of both; a map of both as one, the tree's values over the document's. + let mut keys = listed.keys_at(&path(&["m"])).unwrap().expect("a map"); + keys.sort(); + assert_eq!(keys, path(&["a", "b", "c"])); + assert_eq!( + listed.read_path(&path(&["m", "a"])).unwrap(), + Some(json!({"alias": "A", "tier": 1})) + ); + assert_eq!( + listed.read_path(&path(&["m", "a", "alias"])).unwrap(), + Some(json!("A")) + ); + assert_eq!( + listed.read_path(&path(&["m", "b", "alias"])).unwrap(), + Some(json!("b")) + ); + assert_eq!( + listed.read_plain(&path(&["m", "c", "alias"])).unwrap(), + Some(json!("c")) + ); + assert_eq!( + listed.read_typed(&path(&["policy"])).unwrap(), + Some(json!("p")) + ); + assert_eq!( + listed.read_path(&path(&["only", "under"])).unwrap(), + Some(json!(1)) + ); + assert_eq!(listed.read_path(&path(&["nowhere"])).unwrap(), None); + // No tree: the document as it is. + let none = None; + let listed = members_of(&none, &under); + assert_eq!( + listed.read_path(&path(&["m", "a", "alias"])).unwrap(), + Some(json!("a")) + ); + assert_eq!( + listed + .keys_at(&path(&["m"])) + .unwrap() + .map(|keys| keys.len()), + Some(2) + ); + } } diff --git a/src/state/mod.rs b/src/state/mod.rs index 0ffa91e..c3bb4e8 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -413,7 +413,7 @@ impl AppState { /// document it holds. pub(crate) fn entries(&self) -> Option { #[cfg(feature = "federation")] - if self.of_a_set() { + if self.holding.has_a_set() { return self.holding.entries(); } None diff --git a/src/swarm/members.rs b/src/swarm/members.rs index 60d7e06..5a54593 100644 --- a/src/swarm/members.rs +++ b/src/swarm/members.rs @@ -369,7 +369,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { ) = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); ( registered(listed, &local), alias(listed, &local), @@ -458,7 +458,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { if let Some(ours) = state.holding.party() { let entries = state.entries(); let recorded = party( - crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), &local, ); if recorded.as_deref() != Some(ours) { diff --git a/src/swarm/reach.rs b/src/swarm/reach.rs index 2e8c151..20961ad 100644 --- a/src/swarm/reach.rs +++ b/src/swarm/reach.rs @@ -197,7 +197,7 @@ pub(crate) fn of(said: Option<&(Instant, Vec)>) -> Option> { pub(crate) async fn names(state: &AppState) -> HashMap { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); members::members(listed) .into_iter() .map(|member| (topology::pair_key(&member), member)) diff --git a/src/swarm/stability.rs b/src/swarm/stability.rs index aae96d6..c163778 100644 --- a/src/swarm/stability.rs +++ b/src/swarm/stability.rs @@ -180,7 +180,7 @@ pub(crate) async fn tick(state: &AppState) { let local = state.local_id().to_owned(); let entries = state.entries(); let current = members::tier( - crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), &local, ); diff --git a/src/swarm/state_file.rs b/src/swarm/state_file.rs index a8c371c..51b00cc 100644 --- a/src/swarm/state_file.rs +++ b/src/swarm/state_file.rs @@ -135,7 +135,7 @@ pub(crate) async fn update(state: &AppState, now: bool) { let replica = state.doc.read().await; let entries = state.entries(); seeds( - crate::document::view::members_of(&entries, &replica.doc), + &crate::document::view::members_of(&entries, &replica.doc), state.local_id(), state.electorate_window, state.clock.now_millis().as_u64(), diff --git a/src/swarm/topology/mod.rs b/src/swarm/topology/mod.rs index ef778d0..1f99cd8 100644 --- a/src/swarm/topology/mod.rs +++ b/src/swarm/topology/mod.rs @@ -412,7 +412,7 @@ async fn nearby(state: &AppState, inputs: &Inputs<'_>) -> BTreeSet { let group: BTreeMap> = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); inputs .transports .iter() @@ -741,7 +741,7 @@ pub(crate) async fn refresh(state: &AppState) -> Option { let (current, stable, transports, alive, k, recorded) = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + 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)); diff --git a/src/swarm/working_links.rs b/src/swarm/working_links.rs index 9e9022a..ca3a22b 100644 --- a/src/swarm/working_links.rs +++ b/src/swarm/working_links.rs @@ -183,7 +183,7 @@ pub(crate) async fn check(state: &AppState) { let (recorded, links) = { let replica = state.doc.read().await; let entries = state.entries(); - let listed = crate::document::view::members_of(&entries, &replica.doc); + let listed = &crate::document::view::members_of(&entries, &replica.doc); let recorded = members::links(listed, &me); let mut links = links; links.unreached.retain(|member| { -- cgit v1.3.1