diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/config/mod.rs | 13 | ||||
| -rw-r--r-- | src/federation/held.rs | 71 | ||||
| -rw-r--r-- | src/federation/store/passing.rs | 179 | ||||
| -rw-r--r-- | src/lib.rs | 11 | ||||
| -rw-r--r-- | src/simtest/holding.rs | 57 | ||||
| -rw-r--r-- | src/swarm/bootstrap.rs | 81 | ||||
| -rw-r--r-- | src/swarm/set.rs | 59 |
7 files changed, 416 insertions, 55 deletions
diff --git a/src/config/mod.rs b/src/config/mod.rs index 9c82673..5a723c7 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -220,7 +220,7 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ Kind::Text, "PATH", None, - "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Can't be combined with store-file, which the file stands for, nor with store-checkpoint.", + "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Without the file yet, the node begins it from the root where it is given one (store-root) and pins no checkpoint; else it joins with nothing, and gathers of the members it reaches what its set begins from, by name: the root, or the checkpoint store-checkpoint names. Can't be combined with store-file, which the file stands for.", ), #[cfg(feature = "federation")] option( @@ -1384,15 +1384,8 @@ impl Settings { return Ok(()); } }; - if self.store_document.is_some() { - if self.store_file.is_some() { - bail!("store-document holds what store-file would: unset store-file"); - } - if self.store_checkpoint.is_some() { - bail!( - "store-document: a set of events starts from its root or from its file, from no pinned checkpoint: unset store-checkpoint" - ); - } + if self.store_document.is_some() && self.store_file.is_some() { + bail!("store-document holds what store-file would: unset store-file"); } match &self.store_party { None => bail!( diff --git a/src/federation/held.rs b/src/federation/held.rs index bb34407..51d8ef0 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -130,6 +130,13 @@ pub(crate) struct Voter { pub(crate) rules: Rules, } +/// A set of events as a node starts with it: held, from its file or begun from the +/// root; or still to be gathered of its peers, where the node was given neither. +pub(crate) enum Begun { + Set(Box<Set<Federation>>), + Start(super::store::passing::Start<Federation>), +} + /// What carries the store: a document it is read from, or a set of events, which is /// the store's own document (`store::set`). enum Carried { @@ -175,6 +182,9 @@ impl Carried { struct Inner { /// None until a document holding a store holds its root. store: Option<Carried>, + /// A set of events to be, where the node started with nothing of its store and + /// gathers what its set begins from of its peers (`store::passing::Start`). + starting: Option<super::store::passing::Start<Federation>>, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option<u32>, read: HashSet<Id>, @@ -1040,18 +1050,65 @@ impl Holding { self } - /// Itself, its store carried by `set` and kept in the file at `path`, where the node - /// is given a set. + /// Itself, its store to be carried by a set of events it has nothing of yet: what + /// `start` gathers of its peers (`swarm::set`). + pub(crate) fn awaiting(mut self, start: super::store::passing::Start<Federation>) -> Self { + self.of_a_set = true; + self.inner.lock_or_recover().starting = Some(start); + self + } + + /// The names a node that started with nothing asks a peer for, to begin its set + /// from; none, once it holds one. + pub(crate) fn start_wants(&self) -> Vec<crate::document::ranges::Name> { + self.inner + .lock_or_recover() + .starting + .as_ref() + .map(|start| start.wants()) + .unwrap_or_default() + } + + /// Takes what a peer sent a node that started with nothing. Whether it holds its + /// set by it. + pub(crate) fn start_take(&self, units: Vec<super::store::passing::Unit>) -> bool { + let mut inner = self.inner.lock_or_recover(); + let Some(set) = inner.starting.as_mut().and_then(|start| start.take(units)) else { + return false; + }; + info!(store = %set.store().id(), "Begun the store's set from what peers gave by name"); + inner.starting = None; + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + true + } + + /// The store the node holds, or is to hold once it has gathered its set: by its ID. + pub(crate) fn store_id(&self) -> Option<Id> { + let inner = self.inner.lock_or_recover(); + inner + .store + .as_ref() + .map(|store| store.id()) + .or_else(|| inner.starting.as_ref().map(|start| start.store())) + } + + /// Itself, its store carried by the set `begun`, held or to be, and kept in the + /// file at `path`; itself, where the node is given no set. pub(crate) fn carrying_if( self, - set: Option<Set<Federation>>, + begun: Option<Begun>, path: Option<PathBuf>, files: Arc<Files>, ) -> Self { - match (set, path) { - (Some(set), Some(path)) => self.carrying(set).kept_in(path, files), - (Some(set), None) => self.carrying(set), - (None, _) => self, + let holding = match begun { + Some(Begun::Set(set)) => self.carrying(*set), + Some(Begun::Start(start)) => self.awaiting(start), + None => return self, + }; + match path { + Some(path) => holding.kept_in(path, files), + None => holding, } } diff --git a/src/federation/store/passing.rs b/src/federation/store/passing.rs index 5a6e2af..88e66a4 100644 --- a/src/federation/store/passing.rs +++ b/src/federation/store/passing.rs @@ -15,12 +15,15 @@ //! the store, or put as an entry; and for what the store then waits on and doesn't //! hold, the node asks in turn, back to what both hold. -use std::time::Instant; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; use super::entry::Entry; +use super::Refused; +use super::memory::Store; use super::set::{Put, Set}; use super::{Fold, Id}; use crate::document::ranges::{self, Name}; @@ -45,6 +48,9 @@ pub(crate) struct Stamp { pub(crate) enum Unit { Event(#[serde(with = "serde_bytes")] Vec<u8>), Entry(#[serde(with = "serde_bytes")] Vec<u8>), + /// The checkpoint the sender's store holds, a root among them: for a node that + /// starts with nothing but its name (`Start`). + Checkpoint(#[serde(with = "serde_bytes")] Vec<u8>), } /// What one node says to another of its set. @@ -62,6 +68,100 @@ pub(crate) enum Message { Units(Vec<Unit>), } +/// A set to be: what a node that starts with nothing gathers of its peers, to begin +/// its store's set from (`docs/document.md`, A set of events, Passing on). It knows its +/// store by its ID, and where it starts by a name: the store's root, which is the +/// store's ID, or a checkpoint its operator pins. It asks for the checkpoint of that +/// name, then for the events that one keeps; each is what its name says, or not +/// taken. +pub(crate) struct Start<F: Fold> { + store: Id, + at: Id, + keeps_forgotten: Duration, + /// The checkpoint named `at`, once it came, and the events it keeps, by name. + checkpoint: Option<(Vec<u8>, Vec<Id>)>, + kept: BTreeMap<Id, Vec<u8>>, + fold: std::marker::PhantomData<F>, +} + +impl<F: Fold> Start<F> { + /// A set of the store `store` to be, starting at the checkpoint named `at`. + pub(crate) fn new(store: Id, at: Id, keeps_forgotten: Duration) -> Self { + Self { + store, + at, + keeps_forgotten, + checkpoint: None, + kept: BTreeMap::new(), + fold: std::marker::PhantomData, + } + } + + /// The store it is to hold. + pub(crate) fn store(&self) -> Id { + self.store + } + + /// The names it asks a peer for now. + pub(crate) fn wants(&self) -> Vec<Name> { + match &self.checkpoint { + None => vec![self.at.0], + Some((_, keeps)) => keeps + .iter() + .filter(|id| !self.kept.contains_key(id)) + .map(|id| id.0) + .take(NAMES) + .collect(), + } + } + + /// Takes what a peer sent of what it asked for. The set, once it has all it + /// begins from; a checkpoint that is none of the fold's, or that the store doesn't + /// begin from, is let go of, to be asked for again. + pub(crate) fn take(&mut self, units: Vec<Unit>) -> Option<Set<F>> { + for unit in units { + match unit { + Unit::Checkpoint(bytes) + if self.checkpoint.is_none() && Id::of(&bytes) == self.at => + { + if let Some((_, keeps)) = F::parts(&bytes) { + self.checkpoint = Some((bytes, keeps)); + } + } + Unit::Event(bytes) if bytes.len() <= F::LARGEST => { + let id = Id::of(&bytes); + let kept = self + .checkpoint + .as_ref() + .is_some_and(|(_, keeps)| keeps.contains(&id)); + if kept { + self.kept.insert(id, bytes); + } + } + _ => {} + } + } + let (checkpoint, keeps) = self.checkpoint.as_ref()?; + if keeps.iter().any(|id| !self.kept.contains_key(id)) { + return None; + } + let kept: Vec<Vec<u8>> = self.kept.values().cloned().collect(); + let store: Result<Store<F>, Refused> = if self.at == self.store { + Store::new(checkpoint.clone(), kept) + } else { + Store::pinned(self.store, checkpoint.clone(), kept) + }; + match store { + Ok(store) => Some(Set::new(store, self.keeps_forgotten)), + Err(_) => { + self.checkpoint = None; + self.kept.clear(); + None + } + } + } +} + /// What a node took of a message. #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Took { @@ -85,8 +185,13 @@ pub(crate) fn stamp<F: Fold>(set: &Set<F>) -> Stamp { } } -/// The unit named `name`, where `set` holds it. +/// The unit named `name`, where `set` holds it: an event, an entry, or the checkpoint +/// its store holds. pub(crate) fn unit<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> { + let checkpoint = set.store().checkpoint(); + if Id::of(checkpoint).0 == *name { + return Some(Unit::Checkpoint(checkpoint.to_vec())); + } set.get(&Id(*name)) .map(|bytes| Unit::Event(bytes.to_vec())) .or_else(|| { @@ -130,7 +235,9 @@ pub(crate) fn receive<F: Fold>( continue; }; let size = match &unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => { + bytes.len() + } }; // What doesn't fit, the peer asks for again. if bytes + size > BYTES && !units.is_empty() { @@ -152,6 +259,8 @@ pub(crate) fn receive<F: Fold>( match unit { Unit::Event(bytes) => events.push(bytes), Unit::Entry(bytes) => entries.push(bytes), + // A node holding a set built its checkpoint itself. + Unit::Checkpoint(_) => {} } } took.events = set.offer_all(events, now); @@ -375,7 +484,7 @@ mod tests { let sizes: Vec<usize> = units .iter() .map(|unit| match unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => bytes.len(), }) .collect(); assert!(sizes.iter().sum::<usize>() <= BYTES); @@ -430,4 +539,66 @@ mod tests { ); } } + + #[test] + fn a_node_with_nothing_begins_its_set_from_what_peers_give_by_name() { + // A store that moved to a checkpoint, which keeps an event. + let mut ahead = set(); + let now = Instant::now(); + let root = ahead.store().id(); + let first = testfold::put(&[root], "a", "1"); + let first_id = Id::of(&first); + let second = testfold::put(&[first_id], "a", "2"); + let second_id = Id::of(&second); + let lock = testfold::lock(&[second_id], "b"); + let lock_id = Id::of(&lock); + let cut = testfold::cut(&[lock_id], 1, &[lock_id]); + for event in [first, second, lock, cut.clone()] { + assert!(matches!(ahead.offer(event, now), Offered::Taken(_))); + } + let pinned = Id::of(ahead.store().checkpoint()); + assert_ne!(pinned, root); + + // From the root: the checkpoint named by the store's ID, were it still held. + let mut from_root = Start::<TestFold>::new(root, root, KEEPS); + assert_eq!(from_root.wants(), vec![root.0]); + assert_eq!(unit(&ahead, &root.0), None); + let fresh = set(); + let Some(Unit::Checkpoint(bytes)) = unit(&fresh, &root.0) else { + panic!("no root"); + }; + let begun = from_root + .take(vec![Unit::Checkpoint(bytes)]) + .expect("a set, the root keeping nothing"); + assert_eq!(begun.store().id(), root); + + // From a checkpoint its operator pins: that, then what it keeps. + let mut start = Start::<TestFold>::new(root, pinned, KEEPS); + assert_eq!(start.wants(), vec![pinned.0]); + // What isn't what its name says isn't taken. + assert!( + start + .take(vec![Unit::Checkpoint(b"another".to_vec())]) + .is_none() + ); + assert_eq!(start.wants(), vec![pinned.0]); + let checkpoint = unit(&ahead, &pinned.0).expect("its checkpoint"); + assert!(matches!(checkpoint, Unit::Checkpoint(_))); + assert!(start.take(vec![checkpoint]).is_none()); + let wanted = start.wants(); + assert!(!wanted.is_empty() && !wanted.contains(&pinned.0)); + let kept: Vec<Unit> = wanted + .iter() + .map(|name| unit(&ahead, name).expect("kept")) + .collect(); + let begun = start.take(kept).expect("a set"); + assert_eq!(begun.store().id(), root); + assert_eq!(begun.store().checkpoint(), ahead.store().checkpoint()); + // And it goes on as any set: what the other holds after the checkpoint comes. + let mut sets = [ahead, begun]; + let mut rng = Rng::new(9); + settle(&mut sets, &mut rng, now); + assert!(sets[1].store().get(&Id::of(&cut)).is_some()); + assert_eq!(sets[1].store().taken(), sets[0].store().taken()); + } } @@ -225,7 +225,16 @@ pub async fn run() -> Result<()> { // or from the root. #[cfg(feature = "federation")] let set = match (&store, &args.store_document) { - (Some(store), Some(path)) => Some(store.set(path, &files, args.store_keeps_forgotten)?), + (Some(store), Some(path)) => Some( + store.set( + path, + &files, + args.store_checkpoint + .as_deref() + .and_then(federation::store::Id::from_hex), + args.store_keeps_forgotten, + )?, + ), _ => None, }; #[cfg(feature = "federation")] diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 6da7a90..66d5d15 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1822,7 +1822,11 @@ fn start_on_a_set( let party = party.to_owned(); let adjust = move |config: &mut NodeConfig| { config.store = Some(id); - config.holding = holding(&party).carrying_if(Some(set), path, Arc::new(Files::default())); + config.holding = holding(&party).carrying_if( + Some(held::Begun::Set(Box::new(set))), + path, + Arc::new(Files::default()), + ); }; if restart { sim.restart_with(name, &seeds, Start::FromDocument(Origin::Root), adjust) @@ -1928,3 +1932,54 @@ async fn a_node_of_a_set_goes_on_from_its_file() { }) .await; } + +/// a and b hold the store and a write; c is given the store's ID alone, and nothing of +/// the store: it asks the members it reaches for the root by its name, begins its set +/// from it, and catches up as any node behind. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_joins_with_nothing_but_the_stores_id() { + use crate::federation::store::passing; + + let sim = Sim::with_identity(94); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]); + let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false); + let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), None, false); + sim.wait_ready(&[&a, &b], SOON).await; + let write = tv.write(&[id], "home/tv/x", s("1")); + let ids = [Id::of(&write)]; + put(&a, &[&write]).await; + + let c = sim.start_with( + "c", + &["a"], + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("lass").carrying_if( + Some(held::Begun::Start(passing::Start::new( + id, + id, + Duration::from_secs(600), + ))), + None, + Arc::new(Files::default()), + ); + }, + ); + assert_eq!(c.kind(), crate::federation::store::set::KIND); + assert!(read(&c, |_| ()).is_none()); + sim.wait_ready(&[&c], SOON).await; + let (all, ids) = (&[&a, &b, &c], &ids); + sim.wait_until( + "c holds the store, the write and the entries", + SOON, + move || async move { holds(all[2], ids) && all.iter().all(|node| entries(node) == 3) }, + ) + .await; + sim.wait_until("all stand alike", SOON, move || async move { + let first = stands(all[0]); + first.is_some() && all.iter().all(|node| stands(node) == first) + }) + .await; +} diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 9d29c5b..bc27239 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -54,11 +54,24 @@ 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() - && let Some(swarm_id) = state.holding.with(|store| store.id().to_string()) - { - state.set_expected_swarm_id(swarm_id).await?; + 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 { @@ -324,16 +337,19 @@ 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, which the node must be given then. What a checkpoint - /// forgot is kept for `keeps`. + /// 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. 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, - ) -> Result<crate::federation::store::set::Set<crate::federation::fold::Federation>> { + ) -> Result<crate::federation::held::Begun> { use crate::federation::fold::Federation; - use crate::federation::store::{memory::Store, set::Set}; + 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) @@ -341,7 +357,7 @@ impl StoreStart { 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 from the root, and may take what it refused", + "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 ) @@ -355,18 +371,23 @@ impl StoreStart { ); } info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); - return Ok(set); + return Ok(Begun::Set(Box::new(set))); + } + 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(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(Begun::Start(Start::new(self.id, at, keeps))) + } } - let Some((root, kept)) = &self.root else { - bail!( - "store-document {} doesn't exist, and store-id names no root to begin it from: give the store's root (store-root)", - path.display() - ); - }; - 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(Set::new(store, keeps)) } /// The swarm's ID: the root's, in hex. @@ -717,9 +738,17 @@ mod tests { let path = dir.join("store.events"); let files = Files::default(); let keeps = Duration::from_secs(60); - // No file: from the root, which joining by the ID alone doesn't give. - assert!(joining.set(&path, &files, keeps).is_err()); - let mut set = store.set(&path, &files, keeps).unwrap(); + use crate::federation::held::Begun; + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps) { + Ok(Begun::Set(set)) => Some(*set), + Ok(Begun::Start(_)) => 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()), @@ -728,7 +757,7 @@ mod tests { 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 = start.set(&path, &files, keeps).unwrap(); + 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. @@ -737,9 +766,9 @@ mod tests { id: Id::of(&other_root), root: Some((other_root, Vec::new())), }; - assert!(other.set(&path, &files, keeps).is_err()); + assert!(other.set(&path, &files, None, keeps).is_err()); std::fs::write(&path, b"something else").unwrap(); - assert!(store.set(&path, &files, keeps).is_err()); + assert!(store.set(&path, &files, None, keeps).is_err()); } /// A fork's root, and the event it keeps on a line of its own: the swarm starts from diff --git a/src/swarm/set.rs b/src/swarm/set.rs index ec2415e..6df78ba 100644 --- a/src/swarm/set.rs +++ b/src/swarm/set.rs @@ -25,10 +25,15 @@ 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"), - )) + if !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 @@ -56,10 +61,52 @@ pub(crate) fn heard_status( /// 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, + 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; } } } |
