Skip to main content

zebra_network/
peer_cache_updater.rs

1//! An async task that regularly updates the peer cache on disk from the current address book.
2
3use std::{io, time::Duration};
4
5use futures::FutureExt;
6use tokio::time::sleep;
7use tower::ServiceExt;
8
9use crate::{
10    address_book_updater::{AddressBookRequest, AddressBookResponse, AddressBookService},
11    constants::{DNS_LOOKUP_TIMEOUT, PEER_DISK_CACHE_UPDATE_INTERVAL},
12    meta_addr::MetaAddr,
13    BoxError, Config,
14};
15
16/// An ongoing task that regularly caches the current peers to disk, based on `config`.
17#[instrument(skip(config, address_book_service))]
18pub async fn peer_cache_updater(
19    config: Config,
20    mut address_book_service: AddressBookService,
21) -> Result<(), BoxError> {
22    let initial_interval = initial_update_interval(&config).await;
23
24    // Wait until we've queried DNS and (hopefully) sent peers to the address book.
25    sleep(initial_interval).await;
26
27    let mut wrote_cache = false;
28
29    loop {
30        // Ignore errors because updating the cache is optional.
31        // Errors are already logged by the functions we're calling.
32        wrote_cache |= update_peer_cache_once(&config, &mut address_book_service)
33            .await
34            .unwrap_or(false);
35
36        // Right after a cold start, the address book can still be empty at the first attempt,
37        // and the cache is only written once there are cacheable peers. Unsuccessful retries
38        // keep the fixed `DNS_LOOKUP_TIMEOUT * 4` delay so short crawl intervals don't spin.
39        let interval = if wrote_cache {
40            PEER_DISK_CACHE_UPDATE_INTERVAL
41        } else {
42            DNS_LOOKUP_TIMEOUT * 4
43        };
44
45        sleep(interval).await;
46    }
47}
48
49/// Returns how long to wait before the first peer cache update attempt.
50///
51/// When no peer cache file exists on disk yet, shortens the initial wait to at most
52/// `config.crawl_new_peer_interval` so newly started nodes can populate the initial cache promptly.
53/// When a peer cache file already exists (or its existence cannot be verified), keeps the full
54/// `DNS_LOOKUP_TIMEOUT * 4` delay so discovery settles before overwriting cached fallback peers.
55async fn initial_update_interval(config: &Config) -> Duration {
56    let default_delay = DNS_LOOKUP_TIMEOUT * 4;
57
58    let Some(peer_cache_file) = config.cache_dir.peer_cache_file_path(&config.network) else {
59        return default_delay;
60    };
61
62    if tokio::fs::try_exists(peer_cache_file).await.unwrap_or(true) {
63        default_delay
64    } else {
65        default_delay.min(config.crawl_new_peer_interval)
66    }
67}
68
69/// Caches the current cacheable peers to disk, based on `config`.
70///
71/// Returns `true` if the cache was written, and `false` if the cacheable peer list was empty,
72/// keeping any previous cache.
73pub async fn update_peer_cache_once(
74    config: &Config,
75    address_book_service: &mut AddressBookService,
76) -> io::Result<bool> {
77    let peer_list: std::collections::HashSet<_> = cacheable_peers(address_book_service)
78        .await?
79        .iter()
80        .map(|meta_addr| meta_addr.addr)
81        .collect();
82    let has_peers = !peer_list.is_empty();
83
84    config.update_peer_cache(peer_list).await?;
85
86    Ok(has_peers)
87}
88
89/// Returns a list of cacheable peers from the address book updater task.
90async fn cacheable_peers(
91    address_book_service: &mut AddressBookService,
92) -> io::Result<Vec<MetaAddr>> {
93    // Correctness: box the request future, so its captured types don't leak
94    // into generic callers (rustc's async Send inference struggles with
95    // boxed trait objects inside generic spawned tasks).
96    match address_book_service
97        .oneshot(AddressBookRequest::CacheablePeers)
98        .boxed()
99        .await
100    {
101        Ok(AddressBookResponse::Peers(peers)) => Ok(peers),
102        Ok(_) => unreachable!("CacheablePeers requests always return Peers"),
103        Err(error) => Err(io::Error::other(format!(
104            "error requesting cacheable peers, is Zebra shutting down? {error}"
105        ))),
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::config::CacheDir;
113
114    #[tokio::test]
115    async fn initial_update_interval_respects_cache_file_presence() {
116        let default_delay = DNS_LOOKUP_TIMEOUT * 4;
117        let short_crawl = Duration::from_secs(1);
118
119        let tempdir = tempfile::tempdir().expect("tempdir creation succeeds");
120        let enabled_cache_dir = CacheDir::custom_path(tempdir.path());
121
122        let config_without_cache = Config {
123            cache_dir: enabled_cache_dir.clone(),
124            crawl_new_peer_interval: short_crawl,
125            ..Config::default()
126        };
127        assert_eq!(
128            initial_update_interval(&config_without_cache).await,
129            short_crawl
130        );
131
132        let cache_file = enabled_cache_dir
133            .peer_cache_file_path(&config_without_cache.network)
134            .expect("enabled cache dir returns peer cache file path");
135        std::fs::create_dir_all(
136            cache_file
137                .parent()
138                .expect("peer cache file path has parent directory"),
139        )
140        .expect("cache parent directory creation succeeds");
141        std::fs::write(&cache_file, b"").expect("cache file creation succeeds");
142
143        assert_eq!(
144            initial_update_interval(&config_without_cache).await,
145            default_delay
146        );
147
148        let config_default_crawl = Config {
149            cache_dir: CacheDir::custom_path(
150                tempfile::tempdir()
151                    .expect("tempdir creation succeeds")
152                    .path(),
153            ),
154            ..Config::default()
155        };
156        assert_eq!(
157            initial_update_interval(&config_default_crawl).await,
158            default_delay
159        );
160
161        let config_disabled_cache = Config {
162            cache_dir: CacheDir::disabled(),
163            crawl_new_peer_interval: short_crawl,
164            ..Config::default()
165        };
166        assert_eq!(
167            initial_update_interval(&config_disabled_cache).await,
168            default_delay
169        );
170    }
171}