diff options
Diffstat (limited to 'src/swarm/bootstrap.rs')
| -rw-r--r-- | src/swarm/bootstrap.rs | 179 |
1 files changed, 174 insertions, 5 deletions
diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 7626d53..45c86e6 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -39,6 +39,11 @@ const BOOTSTRAP_REPORT: Duration = Duration::from_secs(300); /// Retrying seeds that didn't resolve: first after this, doubling up to the maximum. const RESOLVE_RETRY: Duration = Duration::from_secs(5); const RESOLVE_RETRY_MAX: Duration = Duration::from_secs(300); +/// A seed that resolved, and whose HELLO failed, is said HELLO again this soon, a few +/// times (`HELLO_SOON`): what a node speaks is mostly known a moment after it proved +/// where it is, and a HELLO in a version that can't say this node's kind didn't go. +const HELLO_AGAIN: Duration = Duration::from_millis(250); +const HELLO_SOON: u32 = 4; /// How this node starts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -52,6 +57,27 @@ 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() { + 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 { bail!("starting on a document without a swarm ID"); @@ -314,6 +340,68 @@ 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, 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; of `both` kinds, none without a file. 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, + both: bool, + ) -> Result<Option<crate::federation::held::Begun>> { + use crate::federation::fold::Federation; + 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) + .with_context(|| format!("Reading the store's document {}", path.display()))?; + 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 anew, and may take what it refused", + path.display(), + refused.0 + ) + })?; + if set.store().id() != self.id { + bail!( + "The store's document {} is of store {}, not {}", + path.display(), + set.store().id(), + self.id + ); + } + info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); + return Ok(Some(Begun::Set(Box::new(set)))); + } + // A node of both kinds makes its set of the store as it reads it of its + // document (`Holding::of_both`). + if both { + return Ok(None); + } + 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(Some(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(Some(Begun::Start(Start::new(self.id, at, keeps)))) + } + } + } + /// The swarm's ID: the root's, in hex. pub(crate) fn swarm_id(&self) -> String { self.id.to_string() @@ -512,7 +600,7 @@ fn load_backup(path: &Path, files: &Files) -> Result<Document> { async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut unresolved = seeds.to_vec(); let mut failing = HashSet::new(); - resolve_seeds(state, &mut unresolved, &mut failing).await; + let mut unsaid = resolve_seeds(state, &mut unresolved, &mut failing).await; if unresolved.is_empty() { return; } @@ -520,13 +608,18 @@ async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut closing = state.closing.subscribe(); tokio::spawn(async move { let mut retry = RESOLVE_RETRY; + let mut soon = 0; while !unresolved.is_empty() { tokio::select! { - () = tokio::time::sleep(retry) => {} + () = tokio::time::sleep(if unsaid && soon < HELLO_SOON { HELLO_AGAIN } else { retry }) => {} _ = closing.wait_for(|closing| *closing) => return, } - resolve_seeds(&state, &mut unresolved, &mut failing).await; - retry = (retry * 2).min(RESOLVE_RETRY_MAX); + if unsaid && soon < HELLO_SOON { + soon += 1; + } else { + retry = (retry * 2).min(RESOLVE_RETRY_MAX); + } + unsaid = resolve_seeds(&state, &mut unresolved, &mut failing).await; } }); } @@ -535,7 +628,9 @@ async fn resolve_seeds( state: &AppState, unresolved: &mut Vec<String>, failing: &mut HashSet<String>, -) { +) -> bool { + // Whether a seed resolved and its HELLO failed. + let mut unsaid = false; let mut still = Vec::new(); for seed in unresolved.drain(..) { match state.transport.resolve_seed(&seed).await { @@ -549,6 +644,19 @@ async fn resolve_seeds( crate::swarm::roots::seed_found(state, &peer); if let Err(error) = send_hello_once(state, &peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "Initial HELLO failed; will retry"); + // Again with the seeds that don't resolve yet: nothing else says + // HELLO again to a node that is no neighbour (`peer::worker`). + if let Some(peer_state) = state.get_peer_state(&peer).await { + let mut peer_state = peer_state.lock().await; + if matches!( + peer_state.hello_state, + crate::state::HelloState::AwaitingReply { .. } + ) { + peer_state.hello_state = crate::state::HelloState::NotSent; + } + } + unsaid = true; + still.push(seed); } } Err(error) => { @@ -562,6 +670,7 @@ async fn resolve_seeds( } } *unresolved = still; + unsaid } /// Why the node is still joining, for the log. @@ -631,6 +740,66 @@ mod tests { assert!(joining.starting(None, None).unwrap().is_none()); } + #[cfg(feature = "federation")] + #[test] + fn a_stores_document_is_begun_from_the_root_or_gone_on_with() { + use crate::federation::harness::{self, Party, Spec}; + use crate::federation::store::memory::Offered; + use std::time::{Duration, Instant}; + + let tv = Party::new("tv", 1); + let root = Spec::first(&[&tv], &[]).root(); + let id = Id::of(&root); + let store = StoreStart { + id, + root: Some((root.clone(), Vec::new())), + }; + let joining = StoreStart { id, root: None }; + let dir = crate::files::scratch_dir("store-document"); + let path = dir.join("store.events"); + let files = Files::default(); + let keeps = Duration::from_secs(60); + use crate::federation::held::Begun; + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps, false) { + Ok(Some(Begun::Set(set))) => Some(*set), + Ok(Some(Begun::Start(_)) | None) => 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()), + Offered::Taken(_) + )); + 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 = set_of(start, None).expect("from the file"); + assert_eq!(read.store().taken(), &[Id::of(&write)]); + } + // Of another store, or no document: refused. + let other_root = Spec::first(&[&Party::new("lass", 2)], &[]).root(); + let other = StoreStart { + id: Id::of(&other_root), + root: Some((other_root, Vec::new())), + }; + assert!(other.set(&path, &files, None, keeps, false).is_err()); + std::fs::write(&path, b"something else").unwrap(); + assert!(store.set(&path, &files, None, keeps, false).is_err()); + // A node of both kinds: the file, where there is one; else none here. + std::fs::remove_file(&path).unwrap(); + assert!( + store + .set(&path, &files, None, keeps, true) + .unwrap() + .is_none() + ); + } + /// A fork's root, and the event it keeps on a line of its own: the swarm starts from /// the changes founding it. Without that event: no store's root. #[test] |
