rings_node/native/bootstrap/mod.rs
1//! Run-owned bootstrap reachability supervision for `rings run`.
2//!
3//! `rings connect node` and `rings connect seed` establish a connection once. This module gives
4//! the native daemon a set of *managed* bootstrap targets that it keeps reachable for the life
5//! of the process: whenever a target stops being reachable through the overlay, the supervisor
6//! redials it through its HTTP endpoint, first in a bounded rapid burst and then on a slow
7//! jittered cadence, and resets once the target is reachable again. Ordinary neighbour and
8//! finger edges stay under Chord stabilization; only the configured targets are supervised, and
9//! a target reachable through other peers is never forced into a direct edge.
10//!
11//! The design splits into a pure core and an effect shell:
12//!
13//! - `schedule::BootstrapSchedule` (private) — the retry state machine, a function of explicit
14//! time; its module docs carry the phase diagram and laws.
15//! - `BootstrapPort` (crate-private) — the two effects a turn needs: assess reachability and
16//! dial; `ProcessorPort` is the production port over a live processor.
17//! - [`BootstrapSupervisor`] — the shell: wakes on deadlines, target losses and finished turns;
18//! runs at most one turn per target; exits on the run's stop token.
19//! - `evidence::ReachabilityEvidence` (crate-private) — what the swarm reports about the
20//! targets: admissions the dial waits for and retirements the supervisor reads as losses;
21//! written by the [`Backend`] through [`BackendObserver`], which the supervisor hands out as
22//! [`BootstrapSupervisor::observer`].
23//!
24//! ```text
25//! ┌────────────────────────── run loop ──────────────────────────┐
26//! StopToken ──stop─▶│ drain losses ─▶ notice_loss ─▶ ∀ due target: begin ─▶ push turn│
27//! Losses ─────wake─▶│ wait { stop | wake | turn finished | next deadline } ─▶ settle │
28//! └──────────────────────────────────────────────────────────────┘
29//!
30//! turn(t) := reachable(t) ? Reachable : dial(t) = Ok ? Reachable : Unreachable
31//! ```
32//!
33//! Lost-wakeup freedom: every wait is preceded by a drain of the loss record, and a loss
34//! recorded between the drain and the wait leaves a stored permit, so no loss is missed. A turn
35//! is bounded: the port bounds its probe, the endpoint's resolution, each of its two HTTP
36//! requests and the admission wait with a timeout of its own, and the core bounds the offer
37//! (ICE gathering) and the routed send it performs on the port's behalf; the one await without
38//! a bound of its own is the transport close a cancelled handshake performs.
39//!
40//! Shutdown: the loop returns on the first stop observation and its in-flight turns are
41//! dropped with it, cancelling any probe or handshake in progress. A pending connection attempt
42//! the core already reserved expires under the core's own pending timeout. Transient failures
43//! stay inside the loop; only configuration is validated up front and fails fast.
44//!
45//! [`Backend`]: crate::extension::Backend
46//! [`BackendObserver`]: crate::extension::BackendObserver
47
48use std::collections::BTreeMap;
49use std::sync::Arc;
50use std::time::Duration;
51
52use async_trait::async_trait;
53use futures::future::BoxFuture;
54use futures::stream::FuturesUnordered;
55use futures::StreamExt;
56use rings_core::dht::Did;
57use tokio::time::Instant;
58
59use self::evidence::PeerLosses;
60use self::schedule::BootstrapSchedule;
61use self::schedule::TurnOutcome;
62use crate::error::Error;
63use crate::error::Result;
64use crate::extension::BackendObserver;
65use crate::native::config::BootstrapConfig;
66use crate::prelude::StopToken;
67use crate::processor::Processor;
68use crate::seed::validate_seed_peers;
69use crate::seed::ValidatedSeedPeer;
70
71mod evidence;
72mod probe;
73mod schedule;
74#[cfg(test)]
75mod tests;
76
77pub(crate) use self::evidence::ReachabilityEvidence;
78pub(crate) use self::probe::ProcessorPort;
79
80/// Validated managed targets: one per DID, one per endpoint, none of them the local node.
81#[derive(Debug)]
82pub struct BootstrapTargets(Vec<ValidatedSeedPeer>);
83
84impl BootstrapTargets {
85 /// Validate `config` for the node `local`: the entries validate as a seed set (every entry
86 /// validates, a verbatim repeat is merged, a DID with conflicting entries or an endpoint
87 /// under two DIDs is refused). An entry naming `local` itself is skipped with a log line,
88 /// as `connect seed` skips it: the shared seed document a seed node supervises the other
89 /// seeds from lists that node too.
90 pub fn from_config(config: BootstrapConfig, local: Did) -> Result<Self> {
91 let mut targets = validate_seed_peers(config.peers)?;
92 if targets.iter().any(|target| target.did() == local) {
93 tracing::info!(peer = %local, "bootstrap target is this node; skipped");
94 targets.retain(|target| target.did() != local);
95 }
96 Ok(Self(targets))
97 }
98
99 /// Whether there is nothing to supervise.
100 pub fn is_empty(&self) -> bool {
101 self.0.is_empty()
102 }
103
104 /// Number of managed targets.
105 #[cfg(test)]
106 pub(crate) fn len(&self) -> usize {
107 self.0.len()
108 }
109}
110
111/// Why a dial did not connect the target.
112#[derive(Debug)]
113pub(crate) enum DialFailure {
114 /// The target's slot is owned by another attempt (a handshake in flight, whichever side
115 /// started it, or an admission being committed): refused before any request when the
116 /// local core already holds an unadmitted handshake, or by the local core during the
117 /// exchange. A refusal by the remote core arrives as an RPC error and is a failure.
118 InFlight,
119 /// The handshake or its admission failed.
120 Failed(Error),
121}
122
123/// Effects one supervisor turn performs on a target.
124#[async_trait]
125pub(crate) trait BootstrapPort: Send + Sync {
126 /// Whether `target` is reachable through the overlay right now.
127 async fn reachable(&self, target: Did) -> bool;
128
129 /// Redial `target` through its HTTP endpoint; `Ok` once the peer is admitted.
130 async fn dial(&self, target: &ValidatedSeedPeer) -> std::result::Result<(), DialFailure>;
131}
132
133/// The run-owned supervisor; see the module diagram.
134pub struct BootstrapSupervisor {
135 targets: BTreeMap<Did, Arc<ValidatedSeedPeer>>,
136 port: Arc<dyn BootstrapPort>,
137 evidence: Arc<ReachabilityEvidence>,
138 schedule: BootstrapSchedule,
139 origin: Instant,
140}
141
142/// In-flight turns, each resolving to the target it served and its outcome.
143type Turns = FuturesUnordered<BoxFuture<'static, (Did, TurnOutcome)>>;
144
145/// What woke the run loop.
146enum Wake {
147 /// The run's stop token was observed.
148 Stop,
149 /// A target loss was recorded.
150 Loss,
151 /// A turn finished for the target.
152 Turn(Did, TurnOutcome),
153 /// The next scheduled deadline passed.
154 Deadline,
155}
156
157impl BootstrapSupervisor {
158 /// Supervision of `targets` over a live processor, or `None` when there is nothing to
159 /// supervise, in which case no observer is needed either.
160 pub fn over_processor(targets: BootstrapTargets, processor: Arc<Processor>) -> Option<Self> {
161 if targets.is_empty() {
162 return None;
163 }
164 let evidence = Arc::new(ReachabilityEvidence::default());
165 let port = Arc::new(ProcessorPort::new(processor, evidence.clone()));
166 Some(Self::new(targets, port, evidence, rand::random()))
167 }
168
169 /// Supervisor over `port` reading `evidence`, with every target due immediately and jitter
170 /// seeded by `jitter_seed`.
171 pub(crate) fn new(
172 targets: BootstrapTargets,
173 port: Arc<dyn BootstrapPort>,
174 evidence: Arc<ReachabilityEvidence>,
175 jitter_seed: u64,
176 ) -> Self {
177 let targets: BTreeMap<Did, Arc<ValidatedSeedPeer>> = targets
178 .0
179 .into_iter()
180 .map(|target| (target.did(), Arc::new(target)))
181 .collect();
182 let schedule = BootstrapSchedule::new(targets.keys().copied(), jitter_seed);
183 Self {
184 targets,
185 port,
186 evidence,
187 schedule,
188 origin: Instant::now(),
189 }
190 }
191
192 /// The observer the daemon installs on its backend so the swarm's reports reach this
193 /// supervisor.
194 pub fn observer(&self) -> Arc<dyn BackendObserver> {
195 self.evidence.clone()
196 }
197
198 /// Run until `stop` is observed; never returns otherwise.
199 pub async fn run(mut self, stop: StopToken) {
200 let mut turns = Turns::new();
201 loop {
202 self.drain_losses();
203 self.start_due_turns(&mut turns);
204 let deadline = self.schedule.next_deadline_ms().and_then(|deadline_ms| {
205 self.origin.checked_add(Duration::from_millis(deadline_ms))
206 });
207 match wait_for_wake(&stop, self.evidence.losses(), &mut turns, deadline).await {
208 Wake::Stop => return,
209 Wake::Loss | Wake::Deadline => {}
210 Wake::Turn(target, outcome) => {
211 self.schedule.settle(target, outcome, self.now_ms());
212 }
213 }
214 }
215 }
216
217 /// Milliseconds since the supervisor started, saturating.
218 fn now_ms(&self) -> u64 {
219 schedule::duration_ms(self.origin.elapsed())
220 }
221
222 /// Fold every recorded target loss into the schedule.
223 fn drain_losses(&mut self) {
224 let lost = match self.evidence.losses().take() {
225 Ok(lost) => lost,
226 Err(error) => {
227 tracing::error!(%error, "bootstrap loss record unavailable");
228 return;
229 }
230 };
231 let now_ms = self.now_ms();
232 for target in lost {
233 if self.schedule.notice_loss(target, now_ms) {
234 tracing::info!(peer = %target, "bootstrap target left the local DHT; reassessing");
235 }
236 }
237 }
238
239 /// Push one turn for every target that is due.
240 fn start_due_turns(&mut self, turns: &mut Turns) {
241 let now_ms = self.now_ms();
242 for (did, target) in &self.targets {
243 if self.schedule.begin_if_due(*did, now_ms) {
244 turns.push(Box::pin(turn(self.port.clone(), target.clone())));
245 }
246 }
247 }
248}
249
250/// Block until the run should act again.
251///
252/// An empty turn set yields `None` at once, which disables its branch rather than completing
253/// it, so an idle supervisor sleeps until its deadline, a loss, or the stop token. Every future
254/// here is cancel-safe: the stop wait registers before re-checking, the loss wait consumes a
255/// permit `notify_one` stores when nobody waits, the turn stream hands back completed turns one
256/// at a time, and the sleep holds no state.
257async fn wait_for_wake(
258 stop: &StopToken,
259 losses: &PeerLosses,
260 turns: &mut Turns,
261 deadline: Option<Instant>,
262) -> Wake {
263 tokio::select! {
264 _ = stop.stopped() => Wake::Stop,
265 _ = losses.woken() => Wake::Loss,
266 Some((target, outcome)) = turns.next() => Wake::Turn(target, outcome),
267 _ = sleep_until_or_forever(deadline) => Wake::Deadline,
268 }
269}
270
271/// Sleep until `deadline`, or forever when no target has one.
272async fn sleep_until_or_forever(deadline: Option<Instant>) {
273 match deadline {
274 Some(deadline) => tokio::time::sleep_until(deadline).await,
275 None => std::future::pending().await,
276 }
277}
278
279/// One turn: assess reachability and, only when unreachable, redial. A refused dial is logged
280/// as such and, like a failed one, is a miss for the schedule.
281async fn turn(port: Arc<dyn BootstrapPort>, target: Arc<ValidatedSeedPeer>) -> (Did, TurnOutcome) {
282 let did = target.did();
283 if port.reachable(did).await {
284 tracing::debug!(peer = %did, "bootstrap target reachable");
285 return (did, TurnOutcome::Reachable);
286 }
287 match port.dial(target.as_ref()).await {
288 Ok(()) => {
289 tracing::info!(peer = %did, endpoint = %target.endpoint(), "bootstrap target redialed");
290 (did, TurnOutcome::Reachable)
291 }
292 Err(DialFailure::InFlight) => {
293 tracing::debug!(peer = %did, "bootstrap redial refused: the target's slot is owned by another attempt");
294 (did, TurnOutcome::Unreachable)
295 }
296 Err(DialFailure::Failed(error)) => {
297 tracing::warn!(peer = %did, endpoint = %target.endpoint(), %error, "bootstrap redial failed");
298 (did, TurnOutcome::Unreachable)
299 }
300 }
301}