use crate::io::docs::LocalDocuments;
use crate::io::server::Server;
use basic_human_duration::ChronoHumanDuration;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use time::Duration;
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::{Mutex, RwLock};
use uuid::Uuid;
use web_time::Instant;
use crate::model::clock;
use crate::model::errors::{LbErrKind, LbResult, Unexpected};
use crate::service::events::{Event, SyncIncrement};
use crate::service::usage::UsageMetrics;
use crate::{Lb, tokio_spawn};
#[derive(Clone, Default)]
pub struct StatusUpdater {
current_status: Arc<RwLock<Status>>,
usage: Arc<Mutex<UsageUpdater>>,
}
#[derive(Default)]
pub struct UsageUpdater {
data_cap: Option<u64>,
cap_fetch_spawned: bool,
cap_fetched_at: Option<Instant>,
recompute_spawned: bool,
}
impl StatusUpdater {
pub(crate) async fn data_cap(&self) -> Option<u64> {
self.usage.lock().await.data_cap
}
pub(crate) async fn set_data_cap(&self, data_cap: u64) {
self.usage.lock().await.data_cap = Some(data_cap);
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Status {
pub offline: bool,
pub syncing: bool,
pub out_of_space: bool,
pub pending_shares: bool,
pub update_required: bool,
pub pushing_files: Vec<Uuid>,
pub dirty_locally: Vec<Uuid>,
pub pulling_files: Vec<Uuid>,
pub usage: UsageMetrics,
pub sync_status: Option<String>,
pub unexpected_sync_problem: Option<String>,
}
impl Status {
pub fn msg(&self) -> Option<String> {
if self.syncing {
return Some("Syncing...".to_string());
}
if self.offline {
if !self.dirty_locally.is_empty() {
let len = self.dirty_locally.len();
return Some(format!(
"Offline, {} change{} unsynced.",
len,
if len > 1 { "s" } else { "" }
));
}
if let Some(last_synced) = &self.sync_status {
return Some(format!("Offline, last synced: {last_synced}"));
}
return Some("Offline.".to_string());
}
if self.out_of_space {
return Some("You're out of space!".to_string());
}
if self.update_required {
return Some("An update is required to continue.".to_string());
}
if let Some(err) = &self.unexpected_sync_problem {
return Some(err.to_string());
}
if !self.dirty_locally.is_empty() {
let dirty_locally = self.dirty_locally.len();
return Some(format!("{dirty_locally} changes unsynced"));
}
if let Some(last_synced) = &self.sync_status {
return Some(format!("Last synced: {last_synced}"));
}
None
}
}
impl<S: Server, D: LocalDocuments> Lb<S, D> {
pub async fn status(&self) -> Status {
self.status.current_status.read().await.clone()
}
pub async fn set_initial_state(&self) -> LbResult<()> {
if self.get_account().is_ok() {
self.spawn_refresh_cap().await;
let usage = self.get_usage().await.log_and_ignore();
let mut current = self.status.current_status.write().await;
if let Some(usage) = usage {
current.usage = usage;
}
current.dirty_locally = self.local_changes().await;
if current.dirty_locally.is_empty() {
current.sync_status = self.get_last_synced_human().await.log_and_ignore();
}
current.pending_shares = !self.get_pending_shares().await?.is_empty();
}
Ok(())
}
pub async fn setup_status(&self) -> LbResult<()> {
self.set_initial_state().await?;
let mut rx = self.subscribe();
let bg = self.clone();
tokio_spawn!(async move {
loop {
let evt = match rx.recv().await {
Ok(evt) => evt,
Err(RecvError::Lagged(_)) => {
bg.catch_up().await.log_and_ignore();
continue;
}
Err(RecvError::Closed) => return,
};
bg.process_event(evt).await.log_and_ignore();
}
});
Ok(())
}
pub async fn get_last_synced(&self) -> LbResult<i64> {
let tx = self.ro_tx().await;
let db = tx.db();
Ok(db.last_synced.as_ref().copied().unwrap_or(0))
}
pub async fn get_last_synced_human(&self) -> LbResult<String> {
let last_synced = self.get_last_synced().await?;
Ok(self.get_timestamp_human_string(last_synced))
}
pub fn get_timestamp_human_string(&self, timestamp: i64) -> String {
if timestamp != 0 {
Duration::milliseconds(clock::get_time().0 - timestamp)
.format_human()
.to_string()
} else {
"never".to_string()
}
}
async fn catch_up(&self) -> LbResult<()> {
if self.syncer.try_lock().is_ok() {
let mut status = self.status.current_status.write().await;
self.reset_in_flight_sync(&mut status);
}
self.process_event(Event::IpcChangesApplied).await
}
async fn process_event(&self, e: Event) -> LbResult<()> {
let current = self.status.current_status.read().await.clone();
match e {
Event::IpcChangesApplied => {
let mut current = current;
current.dirty_locally = self.local_changes().await;
current.pending_shares = !self.get_pending_shares().await?.is_empty();
current.sync_status = if current.dirty_locally.is_empty() {
self.get_last_synced_human().await.ok()
} else {
None
};
self.set_status(current).await?;
self.spawn_recompute_usage().await;
}
Event::MetadataChanged(_) | Event::DocumentWritten(_, _) => {
self.compute_dirty_locally(current).await?;
self.spawn_recompute_usage().await;
}
Event::Sync(s) => {
let finished = matches!(s, SyncIncrement::SyncFinished(_));
self.update_sync(s, current).await?;
if finished {
self.recompute_usage().await;
}
}
Event::UserSignedIn => {
self.recompute_usage().await;
self.spawn_refresh_cap().await;
}
_ => {}
}
Ok(())
}
async fn set_status(&self, mut status: Status) -> LbResult<()> {
let mut current = self.status.current_status.write().await;
status.usage = current.usage.clone();
*current = status;
drop(current);
self.events.status_updated();
Ok(())
}
pub(crate) async fn set_status_usage(&self, usage: UsageMetrics) {
let mut current = self.status.current_status.write().await;
if current.usage == usage {
return;
}
current.usage = usage;
drop(current);
self.events.status_updated();
}
async fn recompute_usage(&self) {
if let Some(usage) = self.get_usage().await.log_and_ignore() {
self.set_status_usage(usage).await;
}
}
async fn compute_dirty_locally(&self, mut status: Status) -> LbResult<()> {
let new = self.local_changes().await;
if new != status.dirty_locally {
status.dirty_locally = self.local_changes().await;
self.set_status(status).await?;
}
Ok(())
}
async fn spawn_recompute_usage(&self) {
let mut lock = self.status.usage.lock().await;
if lock.recompute_spawned {
return;
}
lock.recompute_spawned = true;
drop(lock);
let bg = self.clone();
tokio_spawn!(async move {
tokio::time::sleep(web_time::Duration::from_millis(250)).await;
bg.status.usage.lock().await.recompute_spawned = false;
bg.recompute_usage().await;
});
}
async fn spawn_refresh_cap(&self) {
let mut lock = self.status.usage.lock().await;
if lock.cap_fetch_spawned {
return;
}
lock.cap_fetch_spawned = true;
let fetched_at = lock.cap_fetched_at;
drop(lock);
let bg = self.clone();
tokio_spawn!(async move {
if let Some(fetched_at) = fetched_at {
let wait = web_time::Duration::from_secs(60).saturating_sub(fetched_at.elapsed());
tokio::time::sleep(wait).await;
}
bg.refresh_usage().await.log_and_ignore();
let mut lock = bg.status.usage.lock().await;
lock.cap_fetch_spawned = false;
lock.cap_fetched_at = Some(Instant::now());
});
}
async fn update_sync(&self, s: SyncIncrement, mut status: Status) -> LbResult<()> {
match s {
SyncIncrement::SyncStarted => {
self.reset_in_flight_sync(&mut status);
status.syncing = true;
}
SyncIncrement::PullingDocument(id, in_progress) => {
if in_progress {
status.pulling_files.push(id);
} else {
status.pulling_files.retain(|fid| id != *fid);
}
}
SyncIncrement::PushingDocument(id, in_progress) => {
if in_progress {
status.pushing_files.push(id);
} else {
status.pushing_files.retain(|fid| id != *fid);
}
}
SyncIncrement::SyncFinished(maybe_problem) => {
self.reset_sync_outcome(&mut status);
self.reset_in_flight_sync(&mut status);
self.spawn_refresh_cap().await;
status.dirty_locally = self.local_changes().await;
if status.dirty_locally.is_empty() {
status.sync_status = self.get_last_synced_human().await.ok();
}
status.pending_shares = !self.get_pending_shares().await?.is_empty();
match maybe_problem {
Some(LbErrKind::ClientUpdateRequired) => {
status.update_required = true;
}
Some(LbErrKind::ServerUnreachable) => {
status.offline = true;
}
Some(LbErrKind::UsageIsOverDataCap) => {
status.out_of_space = true;
}
None => {}
Some(e) => {
status.unexpected_sync_problem =
Some(format!("unexpected error {e:?}: {e}"));
error!("unexpected error {e:?}: {e}");
}
}
}
}
self.set_status(status).await?;
Ok(())
}
fn reset_in_flight_sync(&self, status: &mut Status) {
status.syncing = false;
status.pulling_files.clear();
status.pushing_files.clear();
status.sync_status = None;
status.unexpected_sync_problem = None;
}
fn reset_sync_outcome(&self, status: &mut Status) {
status.offline = false;
status.update_required = false;
status.out_of_space = false;
}
}