//! The sync cycle (M10.7c). //! //! Deliberately the ONLY way the UI can sync. Push and pull are each usable on their //! own inside this crate, but exposing them separately would let a caller pull //! without pushing, which quietly overwrites unsent local edits. use chrono::{SecondsFormat, Utc}; use serde::Serialize; use super::blobs::BlobStore; use super::pull; use super::push; use super::state; use crate::local::Db; #[derive(Debug, Serialize)] pub struct SyncOutcome { pub push: push::PushSummary, pub pull: pull::PullSummary, /// The state after the cycle, so the UI updates from one round-trip instead of /// following every sync with a status call. pub status: state::Status, } /// Push, then pull — in that order, always. /// /// Pull writes the server's version straight over the local row, so anything not yet /// sent would be lost to it. Pushing first is what puts the local edit in front of /// the server's last-write-wins comparison, and it's the reason /// `PullSummary::clobbered_dirty` should be zero on every healthy cycle. /// /// A failed push aborts before the pull. Pulling anyway would take the exact rows we /// just failed to save and overwrite them — turning a recoverable network error into /// lost work. pub async fn run_cycle( db: &Db, blobs: &BlobStore, base_url: &str, token: &str, ) -> Result { let push = push::run(db, base_url, token).await?; let pull = pull::run(db, blobs, base_url, token).await?; if pull.clobbered_dirty > 0 { // Push ran first and reported success, so nothing should still have been // dirty. Reaching here means something wrote to the store mid-cycle, or a // change never got collected — worth a loud line either way. log::warn!( "sync cycle overwrote {} locally-edited note(s) despite pushing first", pull.clobbered_dirty ); } // While we're already talking to this server, re-read what it says about itself. // Today that's the trash-retention window the Trash view counts down against, and // it can change under us whenever an admin edits the setting. Best-effort on // purpose: a config blip must not fail a cycle whose actual work already // succeeded, and the stored value simply stays as it was. let retention = super::client::probe(base_url) .await .ok() .and_then(|p| p.server.trash_retention_days); let status = { let conn = db.0.lock().map_err(|e| e.to_string())?; if let Some(days) = retention { state::set_server_retention(&conn, days as i64).map_err(|e| e.to_string())?; } // Stamped only here, after BOTH halves succeeded. A timestamp written after a // partial cycle would tell the user they're up to date when they aren't. let now = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true); state::mark_synced(&conn, &now).map_err(|e| e.to_string())?; state::status(&conn).map_err(|e| e.to_string())? }; Ok(SyncOutcome { push, pull, status }) }