diff options
Diffstat (limited to 'src/swarm')
| -rw-r--r-- | src/swarm/bootstrap.rs | 81 | ||||
| -rw-r--r-- | src/swarm/set.rs | 59 |
2 files changed, 108 insertions, 32 deletions
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; } } } |
