coven_sync/
network_follow.rs1use crate::RetryWaits;
8use coven_database::StoreDatabase;
9use coven_foundation::network_watch::NetworkWatch;
10use std::sync::Arc;
11use tokio::sync::watch;
12
13pub struct NetworkFollow {
18 _watch: NetworkWatch,
19 stop: watch::Sender<bool>,
20 task: tokio::sync::Mutex<Option<coven_foundation::task::OwnedTask>>,
21 #[cfg(any(test, feature = "test-utils"))]
24 parks: crate::Parks,
25}
26
27impl NetworkFollow {
28 pub fn start(watched: NetworkWatch, waits: Arc<RetryWaits>, database: StoreDatabase) -> Self {
32 let mut network = watched.view();
33 let first = network.read();
34 database.record_network(first);
35 if first.usable == Some(true) {
36 waits.report_network();
37 }
38 let (stop, mut stopping) = watch::channel(false);
39 let bugs = database.bugs().clone();
40 let parks = crate::Parks::new();
41 #[cfg(any(test, feature = "test-utils"))]
42 let follower_parks = parks.clone();
43 let follow = async move {
46 let _running = parks.running();
47 let mut joined = first.joined;
48 loop {
49 tokio::select! {
50 biased;
51 never = parks.polling() => match never {},
52 _ = stopping.changed() => break,
53 () = network.changed() => {}
54 never = parks.parked() => match never {},
55 }
56 let state = network.read();
57 database.record_network(state);
58 if state.joined != joined {
61 joined = state.joined;
62 waits.report_network();
63 }
64 }
65 };
66 let task =
67 coven_foundation::task::spawn_owned("the network follower", bugs, follow, |_| async {});
68 Self {
69 _watch: watched,
70 stop,
71 task: tokio::sync::Mutex::new(Some(task)),
72 #[cfg(any(test, feature = "test-utils"))]
73 parks: follower_parks,
74 }
75 }
76
77 #[cfg(any(test, feature = "test-utils"))]
80 pub fn parked_from_now(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
81 self.parks.parked_from_now()
82 }
83
84 pub async fn close(&self) {
86 self.stop.send_replace(true);
87 if let Some(task) = self.task.lock().await.take() {
88 task.ended().await;
89 }
90 }
91}
92
93#[cfg(test)]
94#[path = "network_follow_tests.rs"]
95mod tests;