Skip to main content

lb_rs/subscribers/
status.rs

1use crate::io::docs::LocalDocuments;
2use crate::io::server::Server;
3use basic_human_duration::ChronoHumanDuration;
4use serde::{Deserialize, Serialize};
5use std::sync::Arc;
6use time::Duration;
7
8use tokio::sync::broadcast::error::RecvError;
9use tokio::sync::{Mutex, RwLock};
10use uuid::Uuid;
11use web_time::Instant;
12
13use crate::model::clock;
14use crate::model::errors::{LbErrKind, LbResult, Unexpected};
15use crate::service::events::{Event, SyncIncrement};
16use crate::service::usage::UsageMetrics;
17use crate::{Lb, tokio_spawn};
18
19#[derive(Clone, Default)]
20pub struct StatusUpdater {
21    current_status: Arc<RwLock<Status>>,
22    usage: Arc<Mutex<UsageUpdater>>,
23}
24
25#[derive(Default)]
26pub struct UsageUpdater {
27    data_cap: Option<u64>,
28    cap_fetch_spawned: bool,
29    cap_fetched_at: Option<Instant>,
30    recompute_spawned: bool,
31}
32
33impl StatusUpdater {
34    pub(crate) async fn data_cap(&self) -> Option<u64> {
35        self.usage.lock().await.data_cap
36    }
37
38    pub(crate) async fn set_data_cap(&self, data_cap: u64) {
39        self.usage.lock().await.data_cap = Some(data_cap);
40    }
41}
42
43/// lb-rs may be used by multiple disconnected components which may
44/// not be able to seamlessly share state among one another. this struct
45/// provides a snapshot into what overall state of data and tasks are
46/// within lb-rs.
47///
48/// the fields are roughly in order of priority, if your UI has limited
49/// space to represent information (phones?) earlier fields are more
50/// important than later fields. Ideally anything with an ID is represented
51/// in the file tree itself.
52#[derive(Default, Clone, Debug, Serialize, Deserialize)]
53pub struct Status {
54    /// some recent server interaction failed due to network conditions
55    pub offline: bool,
56
57    /// a sync is in progress
58    pub syncing: bool,
59
60    /// at-least one document cannot be pushed due to a data cap
61    pub out_of_space: bool,
62
63    /// there are pending shares
64    pub pending_shares: bool,
65
66    /// you must update to be able to sync, see update_available below
67    pub update_required: bool,
68
69    /// metadata or content for this id is being sent to the server
70    pub pushing_files: Vec<Uuid>,
71
72    /// following files need to be pushed
73    pub dirty_locally: Vec<Uuid>,
74
75    /// metadata or content for this id is being from the server
76    /// callers should be prepared to handle ids they don't know
77    /// about yet.
78    pub pulling_files: Vec<Uuid>,
79
80    /// a mix of human readable and precise data for
81    /// used, and available space
82    pub usage: UsageMetrics,
83
84    /// if there is no pending work this will have a human readable
85    /// description of when we last synced successfully
86    pub sync_status: Option<String>,
87
88    pub unexpected_sync_problem: Option<String>,
89}
90
91impl Status {
92    pub fn msg(&self) -> Option<String> {
93        if self.syncing {
94            return Some("Syncing...".to_string());
95        }
96
97        if self.offline {
98            if !self.dirty_locally.is_empty() {
99                let len = self.dirty_locally.len();
100                return Some(format!(
101                    "Offline, {} change{} unsynced.",
102                    len,
103                    if len > 1 { "s" } else { "" }
104                ));
105            }
106
107            if let Some(last_synced) = &self.sync_status {
108                return Some(format!("Offline, last synced: {last_synced}"));
109            }
110
111            return Some("Offline.".to_string());
112        }
113
114        if self.out_of_space {
115            return Some("You're out of space!".to_string());
116        }
117
118        if self.update_required {
119            return Some("An update is required to continue.".to_string());
120        }
121
122        if let Some(err) = &self.unexpected_sync_problem {
123            return Some(err.to_string());
124        }
125
126        if !self.dirty_locally.is_empty() {
127            let dirty_locally = self.dirty_locally.len();
128            return Some(format!("{dirty_locally} changes unsynced"));
129        }
130
131        if let Some(last_synced) = &self.sync_status {
132            return Some(format!("Last synced: {last_synced}"));
133        }
134
135        None
136    }
137}
138
139impl<S: Server, D: LocalDocuments> Lb<S, D> {
140    pub async fn status(&self) -> Status {
141        self.status.current_status.read().await.clone()
142    }
143
144    pub async fn set_initial_state(&self) -> LbResult<()> {
145        if self.get_account().is_ok() {
146            self.spawn_refresh_cap().await;
147            let usage = self.get_usage().await.log_and_ignore();
148            let mut current = self.status.current_status.write().await;
149            if let Some(usage) = usage {
150                current.usage = usage;
151            }
152            current.dirty_locally = self.local_changes().await;
153            if current.dirty_locally.is_empty() {
154                current.sync_status = self.get_last_synced_human().await.log_and_ignore();
155            }
156            current.pending_shares = !self.get_pending_shares().await?.is_empty();
157        }
158
159        Ok(())
160    }
161
162    pub async fn setup_status(&self) -> LbResult<()> {
163        self.set_initial_state().await?;
164        let mut rx = self.subscribe();
165        let bg = self.clone();
166
167        tokio_spawn!(async move {
168            loop {
169                let evt = match rx.recv().await {
170                    Ok(evt) => evt,
171                    Err(RecvError::Lagged(_)) => {
172                        bg.catch_up().await.log_and_ignore();
173                        continue;
174                    }
175                    Err(RecvError::Closed) => return,
176                };
177                bg.process_event(evt).await.log_and_ignore();
178            }
179        });
180
181        Ok(())
182    }
183
184    pub async fn get_last_synced(&self) -> LbResult<i64> {
185        let tx = self.ro_tx().await;
186        let db = tx.db();
187        Ok(db.last_synced.as_ref().copied().unwrap_or(0))
188    }
189
190    pub async fn get_last_synced_human(&self) -> LbResult<String> {
191        let last_synced = self.get_last_synced().await?;
192        Ok(self.get_timestamp_human_string(last_synced))
193    }
194
195    pub fn get_timestamp_human_string(&self, timestamp: i64) -> String {
196        if timestamp != 0 {
197            Duration::milliseconds(clock::get_time().0 - timestamp)
198                .format_human()
199                .to_string()
200        } else {
201            "never".to_string()
202        }
203    }
204
205    /// After missed events: what is in flight from the sync lock, the rest from the database.
206    async fn catch_up(&self) -> LbResult<()> {
207        if self.syncer.try_lock().is_ok() {
208            let mut status = self.status.current_status.write().await;
209            self.reset_in_flight_sync(&mut status);
210        }
211        self.process_event(Event::IpcChangesApplied).await
212    }
213
214    async fn process_event(&self, e: Event) -> LbResult<()> {
215        let current = self.status.current_status.read().await.clone();
216        match e {
217            Event::IpcChangesApplied => {
218                let mut current = current;
219                current.dirty_locally = self.local_changes().await;
220                current.pending_shares = !self.get_pending_shares().await?.is_empty();
221                current.sync_status = if current.dirty_locally.is_empty() {
222                    self.get_last_synced_human().await.ok()
223                } else {
224                    None
225                };
226                self.set_status(current).await?;
227                self.spawn_recompute_usage().await;
228            }
229            Event::MetadataChanged(_) | Event::DocumentWritten(_, _) => {
230                self.compute_dirty_locally(current).await?;
231                self.spawn_recompute_usage().await;
232            }
233            Event::Sync(s) => {
234                let finished = matches!(s, SyncIncrement::SyncFinished(_));
235                self.update_sync(s, current).await?;
236                if finished {
237                    self.recompute_usage().await;
238                }
239            }
240            Event::UserSignedIn => {
241                self.recompute_usage().await;
242                self.spawn_refresh_cap().await;
243            }
244            _ => {}
245        }
246        Ok(())
247    }
248
249    async fn set_status(&self, mut status: Status) -> LbResult<()> {
250        let mut current = self.status.current_status.write().await;
251        status.usage = current.usage.clone();
252        *current = status;
253        drop(current);
254        self.events.status_updated();
255        Ok(())
256    }
257
258    pub(crate) async fn set_status_usage(&self, usage: UsageMetrics) {
259        let mut current = self.status.current_status.write().await;
260        if current.usage == usage {
261            return;
262        }
263        current.usage = usage;
264        drop(current);
265        self.events.status_updated();
266    }
267
268    async fn recompute_usage(&self) {
269        if let Some(usage) = self.get_usage().await.log_and_ignore() {
270            self.set_status_usage(usage).await;
271        }
272    }
273
274    async fn compute_dirty_locally(&self, mut status: Status) -> LbResult<()> {
275        let new = self.local_changes().await;
276        if new != status.dirty_locally {
277            status.dirty_locally = self.local_changes().await;
278            self.set_status(status).await?;
279        }
280        Ok(())
281    }
282
283    async fn spawn_recompute_usage(&self) {
284        let mut lock = self.status.usage.lock().await;
285        if lock.recompute_spawned {
286            return;
287        }
288        lock.recompute_spawned = true;
289        drop(lock);
290
291        let bg = self.clone();
292        tokio_spawn!(async move {
293            tokio::time::sleep(web_time::Duration::from_millis(250)).await;
294            bg.status.usage.lock().await.recompute_spawned = false;
295            bg.recompute_usage().await;
296        });
297    }
298
299    async fn spawn_refresh_cap(&self) {
300        let mut lock = self.status.usage.lock().await;
301        if lock.cap_fetch_spawned {
302            return;
303        }
304        lock.cap_fetch_spawned = true;
305        let fetched_at = lock.cap_fetched_at;
306        drop(lock);
307
308        let bg = self.clone();
309        tokio_spawn!(async move {
310            if let Some(fetched_at) = fetched_at {
311                let wait = web_time::Duration::from_secs(60).saturating_sub(fetched_at.elapsed());
312                tokio::time::sleep(wait).await;
313            }
314            bg.refresh_usage().await.log_and_ignore();
315            let mut lock = bg.status.usage.lock().await;
316            lock.cap_fetch_spawned = false;
317            lock.cap_fetched_at = Some(Instant::now());
318        });
319    }
320
321    async fn update_sync(&self, s: SyncIncrement, mut status: Status) -> LbResult<()> {
322        match s {
323            SyncIncrement::SyncStarted => {
324                self.reset_in_flight_sync(&mut status);
325                status.syncing = true;
326            }
327            SyncIncrement::PullingDocument(id, in_progress) => {
328                if in_progress {
329                    status.pulling_files.push(id);
330                } else {
331                    status.pulling_files.retain(|fid| id != *fid);
332                }
333            }
334            SyncIncrement::PushingDocument(id, in_progress) => {
335                if in_progress {
336                    status.pushing_files.push(id);
337                } else {
338                    status.pushing_files.retain(|fid| id != *fid);
339                }
340            }
341            SyncIncrement::SyncFinished(maybe_problem) => {
342                // Clear prior sync outcomes here (not at start) so errors persist until a new completed sync
343                self.reset_sync_outcome(&mut status);
344                self.reset_in_flight_sync(&mut status);
345
346                self.spawn_refresh_cap().await;
347                status.dirty_locally = self.local_changes().await;
348                if status.dirty_locally.is_empty() {
349                    status.sync_status = self.get_last_synced_human().await.ok();
350                }
351                // @smailbarkouch has requested that this be a Vec<Uuid> instead of a bool
352                // we also could consume the PendingSharesChanged event
353                status.pending_shares = !self.get_pending_shares().await?.is_empty();
354                match maybe_problem {
355                    Some(LbErrKind::ClientUpdateRequired) => {
356                        status.update_required = true;
357                    }
358                    Some(LbErrKind::ServerUnreachable) => {
359                        status.offline = true;
360                    }
361                    Some(LbErrKind::UsageIsOverDataCap) => {
362                        status.out_of_space = true;
363                    }
364                    None => {}
365                    Some(e) => {
366                        status.unexpected_sync_problem =
367                            Some(format!("unexpected error {e:?}: {e}"));
368                        error!("unexpected error {e:?}: {e}");
369                    }
370                }
371            }
372        }
373
374        self.set_status(status).await?;
375
376        Ok(())
377    }
378
379    fn reset_in_flight_sync(&self, status: &mut Status) {
380        status.syncing = false;
381        status.pulling_files.clear();
382        status.pushing_files.clear();
383        status.sync_status = None;
384        status.unexpected_sync_problem = None;
385    }
386
387    fn reset_sync_outcome(&self, status: &mut Status) {
388        status.offline = false;
389        status.update_required = false;
390        status.out_of_space = false;
391    }
392}