zebra_network/address_book_updater.rs
1//! The address book updater: an actor-style task that owns the address book
2//! write path, wrapped in a [`tower::buffer::Buffer`] service handle.
3
4use std::{
5 cmp::max,
6 net::SocketAddr,
7 sync::Arc,
8 task::{Context, Poll},
9 time::Instant,
10};
11
12use chrono::Utc;
13use futures::future;
14use thiserror::Error;
15use tokio::{
16 sync::{mpsc, oneshot, watch},
17 task::JoinHandle,
18};
19use tower::{buffer::Buffer, util::BoxService, Service};
20use tracing::{Instrument, Level, Span};
21
22use crate::{
23 address_book::AddressMetrics,
24 address_book_peers::AddressBookPeers,
25 meta_addr::{MetaAddr, MetaAddrChange},
26 AddressBook, BanList, BoxError, Config,
27};
28
29#[cfg(test)]
30mod tests;
31
32/// The minimum size of the address book updater channel.
33pub const MIN_CHANNEL_SIZE: usize = 10;
34
35/// The `AddressBookUpdater` hooks into incoming message streams for each peer
36/// and lets the owner of the sender handle update the address book. For
37/// example, it can be used to record per-connection last-seen timestamps, or
38/// add new initial peers to the address book.
39///
40/// It also serves [`AddressBookRequest`]s through a [`Buffer`]-wrapped
41/// [`AddressBookService`]. Each request holds the address book mutex while it
42/// runs, which makes compound operations like
43/// [`AddressBookRequest::NextReconnectPeer`] atomic. Change events use a
44/// separate queue, so they aren't ordered with service requests.
45#[derive(Debug, Eq, PartialEq)]
46pub struct AddressBookUpdater;
47
48#[derive(Copy, Clone, Debug, Error, Eq, PartialEq, Hash)]
49#[error("all address book updater senders are closed")]
50pub struct AllAddressBookUpdaterSendersClosed;
51
52/// A request to the address book updater task.
53#[derive(Clone, Debug)]
54pub enum AddressBookRequest {
55 /// Apply a single [`MetaAddrChange`] to the address book.
56 Change(MetaAddrChange),
57
58 /// Extend the address book with a batch of validated gossiped changes.
59 ///
60 /// The address book handles duplicate addresses internally.
61 ExtendGossiped(Vec<MetaAddrChange>),
62
63 /// Atomically choose the next reconnection candidate, and mark it as
64 /// [`AttemptPending`](crate::PeerAddrState::AttemptPending).
65 ///
66 /// Because the address book updater serves one request at a time,
67 /// concurrent `NextReconnectPeer` requests never return the same peer.
68 NextReconnectPeer,
69
70 /// Return the peers that are considered alive, in connection order.
71 //
72 // Hot reads like `getpeerinfo` currently use the shared address book
73 // handle instead of this request, so they stay off the write queue.
74 #[allow(dead_code)]
75 RecentlyLivePeers,
76
77 /// Return the peers that should be written to the peer cache on disk.
78 CacheablePeers,
79
80 /// Return the number of candidate peers that are currently ready for a
81 /// connection attempt.
82 ///
83 /// The returned count is a snapshot: candidates can become ready or be
84 /// attempted by other tasks immediately afterwards.
85 ReadyPeerCount,
86}
87
88/// A response from the address book updater task.
89#[derive(Clone, Debug)]
90pub enum AddressBookResponse {
91 /// The updated address book entry,
92 /// or `None` if the change was rejected or delayed.
93 //
94 // Production changes are fire-and-forget, so the updated entry is
95 // currently only read by tests.
96 Updated(#[allow(dead_code)] Option<MetaAddr>),
97
98 /// The address book was extended with the gossiped changes.
99 Extended,
100
101 /// The next reconnection candidate, already marked as
102 /// [`AttemptPending`](crate::PeerAddrState::AttemptPending),
103 /// or `None` if no peers are ready for a connection attempt.
104 NextReconnectPeer(Option<MetaAddr>),
105
106 /// A list of peers, in response to
107 /// [`RecentlyLivePeers`](AddressBookRequest::RecentlyLivePeers) or
108 /// [`CacheablePeers`](AddressBookRequest::CacheablePeers).
109 Peers(Vec<MetaAddr>),
110
111 /// The number of candidate peers that are currently ready for a
112 /// connection attempt.
113 ReadyPeerCount(usize),
114}
115
116/// A queued call to the address book updater task.
117///
118/// Fire-and-forget change events don't have a response sender.
119#[derive(Debug)]
120pub struct AddressBookCall {
121 /// The request to serve.
122 request: AddressBookRequest,
123
124 /// The channel used to send the response, if the caller wants one.
125 rsp_tx: Option<oneshot::Sender<AddressBookResponse>>,
126}
127
128/// A cheap cloneable handle that sends fire-and-forget [`MetaAddrChange`]
129/// events to the address book updater task.
130///
131/// Changes aren't ordered with [`AddressBookService`] requests. Send a
132/// [`AddressBookRequest::Change`] to the service when a later request must
133/// see the change.
134#[derive(Clone, Debug)]
135pub struct AddressBookChangeSender(mpsc::Sender<AddressBookCall>);
136
137impl AddressBookChangeSender {
138 /// Sends `change` to the address book updater task,
139 /// waiting until the queue has spare capacity.
140 ///
141 /// Returns an error if the address book updater task has exited.
142 pub async fn send(
143 &self,
144 change: MetaAddrChange,
145 ) -> Result<(), AllAddressBookUpdaterSendersClosed> {
146 self.0
147 .send(AddressBookCall {
148 request: AddressBookRequest::Change(change),
149 rsp_tx: None,
150 })
151 .await
152 .map_err(|_| AllAddressBookUpdaterSendersClosed)
153 }
154}
155
156/// Creates an [`AddressBookChangeSender`] and the receiving half of its
157/// channel, without spawning an updater task.
158///
159/// Used to create stub change senders in tests, and for isolated connections
160/// that don't have an address book.
161pub fn change_channel(size: usize) -> (AddressBookChangeSender, mpsc::Receiver<AddressBookCall>) {
162 let (tx, rx) = mpsc::channel(size);
163 (AddressBookChangeSender(tx), rx)
164}
165
166/// Serves [`AddressBookRequest`]s directly from the address book it holds.
167///
168/// Used both as the inner service behind [`AddressBookService`], and by the
169/// updater task that drains fire-and-forget [`AddressBookChangeSender`] events.
170#[derive(Clone)]
171struct AddressBookHandler {
172 /// The address book to read and update.
173 address_book: Arc<std::sync::Mutex<AddressBook>>,
174
175 /// The channel used to publish the ban list when it changes.
176 bans_sender: Arc<watch::Sender<BanList>>,
177}
178
179impl AddressBookHandler {
180 /// Serves a single `request`.
181 ///
182 /// # Correctness
183 ///
184 /// Briefly holds the address book threaded mutex, with no awaits while it is
185 /// held. External tasks must only use that mutex for hot reads, so this never
186 /// blocks for long.
187 fn handle(&self, request: AddressBookRequest) -> AddressBookResponse {
188 trace!(?request, "got address book request");
189
190 // Every arm needs the address book, so take the lock once, up front. The clock is
191 // then sampled while the lock is already held: sampling it first would let the
192 // timestamps go stale by however long the lock was contended, which makes
193 // `reconnection_peers` under-report how many peers are ready to reconnect.
194 let mut address_book = self
195 .address_book
196 .lock()
197 .expect("mutex should be unpoisoned");
198
199 match request {
200 AddressBookRequest::Change(event) => {
201 let event_ip = event.addr().ip();
202 let updated = address_book.update(event);
203
204 // `UpdateMisbehavior` events should only be passed to `update()` here,
205 // so that this channel is always updated when new addresses are banned.
206 //
207 let bans = updated
208 .is_none()
209 .then(|| address_book.bans())
210 .filter(|bans| bans.is_banned(event_ip));
211
212 // Don't hold the lock while sending the list of `bans`
213 drop(address_book);
214
215 if let Some(bans) = bans {
216 let _ = self.bans_sender.send(bans);
217 }
218
219 AddressBookResponse::Updated(updated)
220 }
221
222 AddressBookRequest::ExtendGossiped(changes) => {
223 // Extend handles duplicate addresses internally.
224 address_book.extend(changes);
225
226 AddressBookResponse::Extended
227 }
228
229 AddressBookRequest::NextReconnectPeer => {
230 // Choose the next candidate, and mark it as `AttemptPending`,
231 // in a single atomic request.
232 let next_peer = address_book
233 .reconnection_peers(Instant::now(), Utc::now())
234 .next()
235 .map(|next_peer| MetaAddr::new_reconnect(next_peer.addr));
236 let next_peer = next_peer.and_then(|change| address_book.update(change));
237
238 AddressBookResponse::NextReconnectPeer(next_peer)
239 }
240
241 AddressBookRequest::RecentlyLivePeers => {
242 AddressBookResponse::Peers(address_book.recently_live_peers(Utc::now()))
243 }
244
245 AddressBookRequest::CacheablePeers => {
246 AddressBookResponse::Peers(address_book.cacheable(Utc::now()))
247 }
248
249 AddressBookRequest::ReadyPeerCount => {
250 let ready_peer_count = address_book
251 .reconnection_peers(Instant::now(), Utc::now())
252 .count();
253
254 AddressBookResponse::ReadyPeerCount(ready_peer_count)
255 }
256 }
257 }
258}
259
260impl Service<AddressBookRequest> for AddressBookHandler {
261 type Response = AddressBookResponse;
262 type Error = BoxError;
263 type Future = future::Ready<Result<Self::Response, Self::Error>>;
264
265 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
266 Poll::Ready(Ok(()))
267 }
268
269 fn call(&mut self, request: AddressBookRequest) -> Self::Future {
270 future::ready(Ok(self.handle(request)))
271 }
272}
273
274/// A shared [`Buffer`]-wrapped service handle to the address book.
275///
276/// Requests are served one at a time, directly from the address book. Writes are
277/// serialised with fire-and-forget [`AddressBookChangeSender`] events by the
278/// address book mutex.
279pub type AddressBookService =
280 Buffer<BoxService<AddressBookRequest, AddressBookResponse, BoxError>, AddressBookRequest>;
281
282impl AddressBookUpdater {
283 /// Spawn a new [`AddressBookUpdater`] task, updating a new [`AddressBook`]
284 /// configured with Zebra's actual `local_listener` address.
285 ///
286 /// Returns handles for:
287 /// - the address book, which should only be used for hot reads,
288 /// - a watch channel for the ban list,
289 /// - the transmission channel for address book update events,
290 /// - a buffered service for address book requests,
291 /// - a watch channel for address book metrics, and
292 /// - the address book updater task join handle.
293 ///
294 /// The task exits with an error when all the returned
295 /// [`AddressBookChangeSender`]s and [`AddressBookService`]s are closed.
296 pub fn spawn(
297 config: &Config,
298 local_listener: SocketAddr,
299 ) -> (
300 Arc<std::sync::Mutex<AddressBook>>,
301 watch::Receiver<BanList>,
302 AddressBookChangeSender,
303 AddressBookService,
304 watch::Receiver<AddressMetrics>,
305 JoinHandle<Result<(), BoxError>>,
306 ) {
307 let address_book = AddressBook::new(
308 local_listener,
309 &config.network,
310 config.max_connections_per_ip,
311 span!(Level::TRACE, "address book"),
312 );
313
314 // Use an update channel and buffer based on the maximum number of
315 // inbound and outbound peers.
316 let channel_size = max(config.peerset_total_connection_limit(), MIN_CHANNEL_SIZE);
317
318 Self::spawn_with_address_book(address_book, channel_size)
319 }
320
321 /// Spawn a new [`AddressBookUpdater`] task for an existing `address_book`,
322 /// using `channel_size` for the update channel and service buffer.
323 ///
324 /// See [`AddressBookUpdater::spawn`] for details.
325 pub fn spawn_with_address_book(
326 address_book: AddressBook,
327 channel_size: usize,
328 ) -> (
329 Arc<std::sync::Mutex<AddressBook>>,
330 watch::Receiver<BanList>,
331 AddressBookChangeSender,
332 AddressBookService,
333 watch::Receiver<AddressMetrics>,
334 JoinHandle<Result<(), BoxError>>,
335 ) {
336 // Create an mpsc channel for fire-and-forget address book update events.
337 // Service requests are queued separately by the `Buffer` below.
338 let (worker_tx, mut worker_rx) = mpsc::channel::<AddressBookCall>(channel_size);
339
340 let address_metrics = address_book.address_metrics_watcher();
341 let address_book = Arc::new(std::sync::Mutex::new(address_book));
342
343 #[cfg(feature = "progress-bar")]
344 let (mut address_info, address_bar, never_bar, failed_bar) = {
345 let address_bar = howudoin::new_root().label("Known Peers");
346 let never_bar =
347 howudoin::new_with_parent(address_bar.id()).label("Never Attempted Peers");
348 let failed_bar = howudoin::new_with_parent(never_bar.id()).label("Failed Peers");
349
350 (address_metrics.clone(), address_bar, never_bar, failed_bar)
351 };
352
353 let (bans_sender, bans_receiver) = tokio::sync::watch::channel(
354 address_book
355 .lock()
356 .expect("mutex should be unpoisoned")
357 .bans(),
358 );
359
360 let handler = AddressBookHandler {
361 address_book: address_book.clone(),
362 bans_sender: Arc::new(bans_sender),
363 };
364 let worker_handler = handler.clone();
365
366 let worker = async move {
367 info!("starting the address book updater");
368
369 while let Some(AddressBookCall { request, rsp_tx }) = worker_rx.recv().await {
370 let response = worker_handler.handle(request);
371
372 if let Some(rsp_tx) = rsp_tx {
373 // The caller might have been cancelled, so ignore send errors.
374 let _ = rsp_tx.send(response);
375 }
376
377 #[cfg(feature = "progress-bar")]
378 if matches!(howudoin::cancelled(), Some(true)) {
379 address_bar.close();
380 never_bar.close();
381 failed_bar.close();
382 } else if address_info.has_changed()? {
383 // We don't track:
384 // - attempt pending because it's always small
385 // - responded because it's the remaining attempted-but-not-failed peers
386 // - recently live because it's similar to the connected peer counts
387
388 let address_info = *address_info.borrow_and_update();
389
390 address_bar
391 .set_pos(u64::try_from(address_info.num_addresses).expect("fits in u64"));
392 // .set_len(u64::try_from(address_info.address_limit).expect("fits in u64"));
393
394 never_bar.set_pos(
395 u64::try_from(address_info.never_attempted_gossiped).expect("fits in u64"),
396 );
397 // .set_len(u64::try_from(address_info.address_limit).expect("fits in u64"));
398
399 failed_bar.set_pos(u64::try_from(address_info.failed).expect("fits in u64"));
400 // .set_len(u64::try_from(address_info.address_limit).expect("fits in u64"));
401 }
402 }
403
404 #[cfg(feature = "progress-bar")]
405 {
406 address_bar.close();
407 never_bar.close();
408 failed_bar.close();
409 }
410
411 let error = Err(AllAddressBookUpdaterSendersClosed.into());
412 info!(?error, "stopping address book updater");
413 error
414 };
415
416 // # Correctness
417 //
418 // The updater task is an async task, not a blocking thread:
419 // - each request only briefly locks the address book mutex, with no
420 // awaits while it is held, so the task never blocks for long, and
421 // - a long-lived blocking task would inhibit auto-advance in tests
422 // that pause the tokio clock.
423 let span = Span::current();
424 let address_book_updater_task_handle = tokio::spawn(worker.instrument(span));
425
426 let change_sender = AddressBookChangeSender(worker_tx.clone());
427
428 let address_book_service = Buffer::new(BoxService::new(handler), channel_size);
429
430 (
431 address_book,
432 bans_receiver,
433 change_sender,
434 address_book_service,
435 address_metrics,
436 address_book_updater_task_handle,
437 )
438 }
439}