zebrad/components/sync/
diagnostics.rs1use std::{
4 collections::BTreeMap,
5 sync::{Arc, Mutex, MutexGuard},
6 time::{Duration, Instant},
7};
8
9use tokio::task::AbortHandle;
10
11use zebra_chain::block;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum RestartReason {
16 ExhaustedTips,
18 ObtainTipsTimeout,
20 ObtainTipsError,
22 ExtendTipsError,
24 SyncStepTimeout,
27 BlockError,
29}
30
31impl RestartReason {
32 pub fn as_str(self) -> &'static str {
34 match self {
35 RestartReason::ExhaustedTips => "exhausted_tips",
36 RestartReason::ObtainTipsTimeout => "obtain_tips_timeout",
37 RestartReason::ObtainTipsError => "obtain_tips_error",
38 RestartReason::ExtendTipsError => "extend_tips_error",
39 RestartReason::SyncStepTimeout => "sync_step_timeout",
40 RestartReason::BlockError => "block_error",
41 }
42 }
43}
44
45#[derive(Clone, Debug, Default)]
47pub struct SyncDiagnostics {
48 pub last_restart: Option<RestartReason>,
50
51 pub restarts_without_progress: u32,
53
54 pub in_flight: usize,
56
57 pub in_flight_blocks: InFlightBlocks,
59}
60
61impl SyncDiagnostics {
62 pub fn oldest_in_flight_age(&self, now: Instant) -> Option<Duration> {
65 self.in_flight_blocks
66 .oldest_running_since()
67 .map(|queued_at| now.saturating_duration_since(queued_at))
68 }
69}
70
71#[derive(Clone, Debug, Default)]
78pub struct InFlightBlocks(Arc<Mutex<BTreeMap<(Instant, [u8; 32]), AbortHandle>>>);
79
80impl InFlightBlocks {
81 pub fn insert(&self, queued_at: Instant, hash: block::Hash, task: AbortHandle) {
83 self.tasks().insert((queued_at, hash.0), task);
84 }
85
86 pub fn remove(&self, queued_at: Instant, hash: block::Hash) {
88 self.tasks().remove(&(queued_at, hash.0));
89 }
90
91 pub fn clear(&self) {
93 self.tasks().clear();
94 }
95
96 pub fn oldest_running_since(&self) -> Option<Instant> {
99 let mut tasks = self.tasks();
100 while let Some(oldest) = tasks.first_entry() {
101 if !oldest.get().is_finished() {
102 return Some(oldest.key().0);
103 }
104 oldest.remove();
105 }
106
107 None
108 }
109
110 fn tasks(&self) -> MutexGuard<'_, BTreeMap<(Instant, [u8; 32]), AbortHandle>> {
111 self.0
112 .lock()
113 .expect("no code panics while holding the in-flight blocks lock")
114 }
115}