kitchen_fridge/provider/
sync_progress.rs1use std::fmt::{Display, Error, Formatter};
4
5#[derive(Clone, Debug)]
7pub enum SyncEvent {
8 NotStarted,
10 Started,
12 InProgress{ calendar: String, items_done_already: usize, details: String},
14 Finished{ success: bool },
16}
17
18impl Display for SyncEvent {
19 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
20 match self {
21 SyncEvent::NotStarted => write!(f, "Not started"),
22 SyncEvent::Started => write!(f, "Sync has started..."),
23 SyncEvent::InProgress{calendar, items_done_already, details} => write!(f, "{} [{}/?] {}...", calendar, items_done_already, details),
24 SyncEvent::Finished{success} => match success {
25 true => write!(f, "Sync successfully finished"),
26 false => write!(f, "Sync finished with errors"),
27 }
28 }
29 }
30}
31
32impl Default for SyncEvent {
33 fn default() -> Self {
34 Self::NotStarted
35 }
36}
37
38
39
40pub type FeedbackSender = tokio::sync::watch::Sender<SyncEvent>;
42pub type FeedbackReceiver = tokio::sync::watch::Receiver<SyncEvent>;
44
45pub fn feedback_channel() -> (FeedbackSender, FeedbackReceiver) {
47 tokio::sync::watch::channel(SyncEvent::default())
48}
49
50
51
52
53pub struct SyncProgress {
55 n_errors: u32,
56 feedback_channel: Option<FeedbackSender>,
57 counter: usize,
58}
59impl SyncProgress {
60 pub fn new() -> Self {
61 Self { n_errors: 0, feedback_channel: None, counter: 0 }
62 }
63 pub fn new_with_feedback_channel(channel: FeedbackSender) -> Self {
64 Self { n_errors: 0, feedback_channel: Some(channel), counter: 0 }
65 }
66
67 pub fn reset_counter(&mut self) {
69 self.counter = 0;
70 }
71 pub fn increment_counter(&mut self, increment: usize) {
73 self.counter += increment;
74 }
75 pub fn counter(&self) -> usize {
79 self.counter
80 }
81
82
83
84 pub fn is_success(&self) -> bool {
85 self.n_errors == 0
86 }
87
88 pub fn error(&mut self, text: &str) {
90 log::error!("{}", text);
91 self.n_errors += 1;
92 }
93 pub fn warn(&mut self, text: &str) {
95 log::warn!("{}", text);
96 self.n_errors += 1;
97 }
98 pub fn info(&mut self, text: &str) {
100 log::info!("{}", text);
101 }
102 pub fn debug(&mut self, text: &str) {
104 log::debug!("{}", text);
105 }
106 pub fn trace(&mut self, text: &str) {
108 log::trace!("{}", text);
109 }
110 pub fn feedback(&mut self, event: SyncEvent) {
112 self.feedback_channel
113 .as_ref()
114 .map(|sender| {
115 sender.send(event)
116 });
117 }
118}