1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
//! The peer worker: keepalives due, dormancy, HELLO retries, overdue sync replies and
//! answers (`PeerState::answer_overdue`, `swarm::reach`), when the earliest of them is
//! due (or something may have made one due sooner, `Due`); and, after something
//! happened that they may have to act on, every `FORGET_CHECK_INTERVAL` while
//! something of them is under way, else every `QUIET_CHECK_INTERVAL` (and at once
//! when the node becomes ready), forget records,
//! the member registry, stability, measurements and the state file; forget records
//! also at once when they changed.
use std::time::Duration;
use tokio::time::Instant;
use tracing::{debug, info, warn};
use super::forget::{AppliedForgets, apply_forget_records, forget_strangers};
use super::handshake::retry_hello_if_due;
use super::keepalive::{send_ping, send_status};
use crate::locks::MutexExt;
use crate::state::{AppState, Keepalive};
use crate::swarm::topology;
/// The least time between two passes, however often something is due.
const MIN_PASS_GAP: Duration = Duration::from_millis(20);
/// The least time between two looks at what is kept in order beside the peers
/// (forget records, the member registry, stability, whom this node reaches, its
/// links, clock, measurements, the state file): so often while something of it is
/// under way (`under_way`), and after something happened that it may have to act on
/// (`AppState::housekeeping`).
const FORGET_CHECK_INTERVAL: Duration = Duration::from_secs(5);
/// How often it looks at those while nothing happens: what they go by also changes
/// with time alone (a round trip going stale, a stamp to renew, an address learned).
const QUIET_CHECK_INTERVAL: Duration = Duration::from_secs(60);
/// When the peer worker is next due. What makes something of its due sooner than it
/// knows (a HELLO sent, a sync message waiting for its answer, a keepalive received, a
/// new peer, new neighbours) says so (`by`); what only puts things off needn't.
#[derive(Default)]
pub(crate) struct Due {
/// Its next pass while it waits; None while it runs.
next: std::sync::Mutex<Option<Instant>>,
wake: tokio::sync::Notify,
}
impl Due {
/// Something is due at `at`: a pass then at the latest.
pub(crate) fn by(&self, at: Instant) {
if self.next.lock_or_recover().is_none_or(|next| at < next) {
self.wake.notify_one();
}
}
/// A pass now.
pub(crate) fn now(&self) {
self.wake.notify_one();
}
fn passing(&self) {
*self.next.lock_or_recover() = None;
}
/// Until `at`, or until something is due sooner.
async fn until(&self, at: Instant) {
*self.next.lock_or_recover() = Some(at);
tokio::select! {
() = self.wake.notified() => {}
() = tokio::time::sleep_until(at) => {}
}
}
}
/// Whether something the periodic checks keep in order is under way, so that they
/// look again soon: the node not ready or still catching up, a forget record not
/// acted on, a link's change not settled, its tier after a restart not decided, a
/// neighbour not reached (what looks for it again goes with these checks).
async fn under_way(state: &AppState, applied: &AppliedForgets) -> bool {
!state.is_ready().await
|| crate::swarm::source::catching_up(state)
|| !crate::swarm::working_links::quiet(state)
|| !crate::swarm::stability::settled(state)
|| super::forget::unapplied(state, applied).await
|| {
let reached = crate::swarm::reach::reached_members(state, Instant::now()).await;
let neighbours = topology::our_neighbours(state);
neighbours.iter().any(|peer| !reached.contains(peer))
}
}
pub(crate) async fn run_peer_worker(state: AppState) {
info!("Starting peer maintenance worker");
let mut last_forget_check: Option<Instant> = None;
// Something happened that the periodic checks may have to act on, since the last.
let mut happened = false;
// How long until they are next looked at by themselves.
let mut again = FORGET_CHECK_INTERVAL;
let mut forgets_applied = AppliedForgets::new();
let mut was_ready = false;
let mut awake = crate::swarm::suspend::Awake::default();
loop {
state.peers_due.passing();
if let Some(gap) = awake.check() {
crate::swarm::suspend::asleep(&state, gap).await;
}
let mut next = Instant::now() + FORGET_CHECK_INTERVAL;
// While joining, keep handshakes fast; dormancy would slow probes to minutes.
let ready = state.is_ready().await;
if ready && !was_ready {
// Just became ready: register in the member list (and do the other periodic
// checks) now rather than at the next check. Until it is registered, other
// members don't count this node as a neighbour.
last_forget_check = None;
}
was_ready = ready;
let peers = state.peers_snapshot().await;
// A member we said we reach stopped answering: tell our neighbours now.
let mut reach_changed = false;
for (peer, peer_state_mutex) in &peers {
let now = Instant::now();
// Only neighbours are kept alive and judged; others we only answer.
let neighbour = topology::is_neighbour(&state, peer);
let (became_dormant, keepalive, unanswered, ask_again, hello_due, sending) = {
let mut peer_state = peer_state_mutex.lock().await;
let sending = peer_state.worker_sending;
let became_dormant = ready
&& neighbour
&& topology::change_peer(&state, &mut peer_state, |p| {
p.check_dormancy(&state.timing, now)
});
let keepalive = if neighbour && !sending {
peer_state.take_keepalive_due(&state.timing, now)
} else {
None
};
if !neighbour {
peer_state.stop_hello_retries(topology::is_listed(&state, peer));
}
let unanswered = peer_state.take_overdue_sync_reply(&state.timing, now);
let ask_again = peer_state.take_ask_again_due(now);
reach_changed |= peer_state.answer_overdue(now)
&& crate::swarm::reach::reached_stops_answering(&state, peer);
let hello_due = matches!(
peer_state.hello_state,
crate::state::HelloState::AwaitingReply { next_attempt } if now >= next_attempt
);
(
became_dormant,
keepalive,
unanswered,
ask_again,
hello_due,
sending,
)
};
// Unanswered: the path in use may drop what it takes. Its others first, and
// all of them pinged now (`Transport::suspect`).
if unanswered.is_some() || ask_again {
state.transport.suspect(peer);
}
if let Some(changes) = unanswered {
debug!(peer = %peer, changes, "No answer to our sync message; sending again");
crate::swarm::source::reply_timed_out(&state, peer);
crate::swarm::relay::pull_unanswered(&state, peer);
state.request_sync(peer);
}
if became_dormant {
warn!(
peer = %peer,
silent_secs = state.timing.dormant_after.as_secs(),
probe_secs = state.timing.dormant_probe.as_secs(),
"Peer went dormant"
);
}
// The catch-up source gets STATUSes: we need its readiness, and whether it
// syncs with us.
let keepalive = match keepalive {
None if crate::swarm::source::probe_due(&state, peer, Instant::now()) => {
Some(Keepalive::Status)
}
keepalive => keepalive,
};
// Nothing answered us for a while: once more before it counts as not reached.
let keepalive = keepalive.or(ask_again.then_some(Keepalive::Ping));
// Off the pass: a send may take a dial (seconds on libp2p, a minute and more
// on Tor, to a peer that is gone), and every other peer's keepalives would
// wait for it. One at a time per peer, so a dial that hangs doesn't pile up.
if !sending && (keepalive.is_some() || hello_due) {
peer_state_mutex.lock().await.worker_sending = true;
let (state, peer, peer_state_mutex) = (
state.clone(),
peer.clone(),
std::sync::Arc::clone(peer_state_mutex),
);
tokio::spawn(async move {
// The HELLO first: it is marked as being sent at once, so it isn't
// due again meanwhile.
if let Err(error) = retry_hello_if_due(&state, &peer).await {
warn!(peer = %peer, error = %format!("{error:#}"), "HELLO retry failed");
}
let sent = match keepalive {
Some(Keepalive::Ping) => send_ping(&state, &peer).await,
Some(Keepalive::Status) => send_status(&state, &peer).await,
None => Ok(()),
};
if let Err(error) = sent {
debug!(peer = %peer, kind = ?keepalive, error = %format!("{error:#}"), "Keepalive failed");
}
peer_state_mutex.lock().await.worker_sending = false;
// What fell due meanwhile.
state.peers_due.now();
});
}
let due = peer_state_mutex
.lock()
.await
.next_due(&state.timing, neighbour, ready);
let probe = crate::swarm::source::probe_at(&state, peer);
next = [Some(next), due, probe]
.into_iter()
.flatten()
.min()
.unwrap_or(next);
}
let records_changed = state
.forget_records_changed
.swap(false, std::sync::atomic::Ordering::AcqRel);
let periodic = last_forget_check.is_none_or(|checked| {
let since = checked.elapsed();
since >= again || (happened && since >= FORGET_CHECK_INTERVAL)
});
if records_changed || periodic {
apply_forget_records(&state, &mut forgets_applied).await;
}
if reach_changed && !periodic {
crate::swarm::reach::check(&state).await;
}
if periodic {
forget_strangers(&state).await;
crate::swarm::members::ensure_registered(&state).await;
crate::swarm::stability::tick(&state).await;
crate::swarm::reach::check(&state).await;
crate::swarm::working_links::check(&state).await;
crate::swarm::skew::check(&state).await;
crate::swarm::stats::measure_saved_size(&state);
crate::swarm::source::warn_if_stalled(&state);
crate::swarm::state_file::update(&state, false).await;
{
let known = state.peer_states.read().await;
// And their addresses, where the layers below the node count
// (`Traffic::node`).
let addresses: std::collections::HashSet<String> = known
.keys()
.flat_map(|peer| state.transport.identities_of(peer))
.collect();
state
.traffic
.retain(|peer| known.contains_key(peer) || addresses.contains(peer));
state
.throughput
.lock_or_recover()
.retain(|peer| known.contains_key(peer));
state.lock_rtt().retain(|peer| known.contains_key(peer));
}
// Fallback for what doesn't notify (`topology::run_worker`).
state.topology_changed.notify_one();
last_forget_check = Some(Instant::now());
happened = false;
again = if under_way(&state, &forgets_applied).await {
FORGET_CHECK_INTERVAL
} else {
QUIET_CHECK_INTERVAL
};
}
if let Some(checked) = last_forget_check {
let wait = if happened {
FORGET_CHECK_INTERVAL
} else {
again
};
next = next.min(checked + wait);
}
let passed = Instant::now();
// Until something of the peers is due, or of the periodic checks; what happens
// meanwhile that those may have to act on brings them forward.
loop {
tokio::select! {
() = state.peers_due.until(next) => break,
() = state.housekeeping.notified(), if !happened => {
happened = true;
if let Some(checked) = last_forget_check {
next = next.min(checked + FORGET_CHECK_INTERVAL);
}
}
}
}
tokio::time::sleep_until(passed + MIN_PASS_GAP).await;
}
}
|