//! The sync loop: pull first, keep pulling, push what the sources wrote. //! //! PULL FIRST AND ALWAYS is not a preference. The import engine matches every //! message against the people and contacts this file already holds, so a Mac //! that pushed before it read would mint a second contact for somebody the //! phone identified last week — two contacts for one human is two DM threads, //! which is a conversation split down the middle. //! //! Everything here is the store's own client code (`drain_outbox`, //! `pull_catch_up`, `sync_backoff_ms`); this module is the SCHEDULE around it //! and holds no opinion about what a push means. //! //! The file names differ from the design's sketch in one place: `loop` is a //! Rust keyword, so the scheduling half is [`task`] and the one pass is //! [`cycle`]. pub mod backoff; pub mod cycle; pub mod line; pub mod task; pub mod time_box; pub use backoff::wait_ms_for; pub use cycle::{push_only, push_only_paged, run_cycle, run_cycle_paged, CycleFailure, CycleReport}; pub use time_box::TimeBox; pub use task::{ all_synced, HeldFiles, HeldReport, HeldReportListener, Reported, SyncLoop, SyncLoopInput, TableMoves, TransportFactory, }; use serde::Serialize; /// The pull cadence, and the floor the backoff ladder starts from. pub const PULL_INTERVAL_MS: u64 = 60_000; /// How many ops go in one push. /// /// The server refuses more than 1,000 (`MAX_OPS_PER_PUSH`), and an import of /// 32k messages is the first workload that ever reaches that ceiling — the /// phone's default of 200 would make the same import five times as many round /// trips for no benefit. pub const PUSH_BATCH_SIZE: i64 = 1_000; /// How long one cycle may be in flight before the loop presumes it dead and /// schedules the next one anyway. /// /// Comfortably past `transport::REQUEST_CEILING_MS` (60 s), because with that /// in place a cycle's individual requests cannot hang — this is the backstop /// for anything else that could fail to settle, and it must never fire on a /// slow but living catch-up. The abandoned cycle's own thread finishes on its /// own and releases the replica; what the ceiling buys back is the LOOP, which /// otherwise waits for ever on one dead pass. pub const CYCLE_CEILING_MS: u64 = 120_000; /// How long a new pass waits for the straggler it cut — the pass the loop /// stopped waiting for — to end. A cut pass ends at its next page boundary /// or as its shut socket errors, in milliseconds; this is the bound if a /// fold is still running. pub const STRAGGLER_WAIT_MS: u64 = 10_000; /// What the loop is doing. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum SyncState { Idle, Syncing, /// A backoff, not an idle. Waiting, Stopped, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct SyncStatus { /// Which database this line is about — one loop syncs every database the /// device holds in one cycle, so a screen showing several says which line /// is which. pub database: String, /// Did the server's last list of this device's databases name this one? /// `false` is "Not available right now": the loop keeps asking, nothing /// is pushed, and everything the database holds stays where it is. pub available: bool, pub state: SyncState, /// How many changes are not sent yet: the queue, and the writes held /// for the Mac's time ([`SyncStatus::held`]), which travel once it is /// known. Never the queue alone — a held write is unsent too. pub pending: i64, /// Of `pending`, the writes made before this device had the Mac's time /// this launch, held until an answer gives it ("N waiting for the Mac's /// time"). pub held: i64, pub last_pull_at: Option, pub last_push_at: Option, pub last_error: Option, /// Consecutive failures — what the backoff ladder is climbing. pub failures: i64, /// When the loop will try again while waiting, ISO-8601 UTC. pub next_attempt_at: Option, /// Why the loop stopped ON ITS OWN — a refusal of this device no retry can /// change (`device_not_approved`, `device_revoked`, a bad signature, no /// key). `None` after a person's own `stop()`. pub stopped_reason: Option, /// The server's code behind `stopped_reason` — `device_revoked` and its /// siblings — so a screen can tell a revocation from a key mismatch /// without parsing a sentence. `None` whenever `stopped_reason` is. pub stopped_code: Option, /// Which side is on the older schema, while one is — the ONE fact Home's /// update slip is drawn off. Never a stop and never read-only: the file /// stays open, every write lands here and queues, and the loop keeps its /// ladder, because the fix is an update on one machine and the next pass /// after it drains everything. `None` the moment a pass moves both ways. #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option, /// How many changes the serving Mac said still wait for this device after /// the last pass that reached it — on the device's own line, over every /// database the pass carried. What the Sync line says REMAINS; the Mac /// counts in full. The device row's figure, never the home's. #[serde(skip_serializing_if = "Option::is_none")] pub behind_by: Option, /// Why the serving Mac could not wake this device the last time it tried /// (the catch-up wake) — its own sentence, never key material. #[serde(skip_serializing_if = "Option::is_none")] pub wake_refusal: Option, /// What this device last heard from the Mac it syncs with — its name, its /// version and its file's schema — kept across failures, so the build /// line can say which Mac a refusal came from. Empty until a Mac has /// answered or refused with a schema. pub peer: PeerHeard, /// When the pass on the wire began, ISO-8601 UTC, while `state` is /// `syncing`; `None` otherwise. What lets a screen say a catch-up is /// running without flickering for a pass that ends within a second, and /// say for how long one has run (owner, 25 Nov 2026: "show some indicator /// that it is syncing"). #[serde(default, skip_serializing_if = "Option::is_none")] pub pass_started_at: Option, /// Whether the last pass that reached the server ended with nothing still to pull (`behind` false, nothing said /// to remain): a copy that only reached the server part way is not caught up (SITES ROWS, 26 Nov 2026). Kept /// across failures, as the last pass that answered left it. #[serde(skip)] pub caught_up: bool, } /// How many exchanges a device keeps for its Debug group. pub const EXCHANGES_KEPT: usize = 20; /// One exchange with the Mac, for the Debug group (phone diagnostics part 4, /// owner 12 Oct 2026): when, which way, what came back, how long, how many /// rows each way and how many bytes. Kept in memory, last /// [`EXCHANGES_KEPT`], newest last. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Exchange { pub at: String, /// "home network", "Tailscale", "over the relay" … — `None` when the Mac /// was not reached. pub way: Option, /// "ok", "ok · push", or the refusal's message. pub answer: String, pub ms: u64, pub pushed: u64, pub pulled: u64, pub sent_bytes: u64, pub received_bytes: u64, } impl Exchange { /// One plain line: `10:32:01Z · home network · ok · 412 ms · ↑3 ↓120 rows · ↑2.1 KB ↓88.0 KB`. #[must_use] pub fn line(&self) -> String { let at = self.at.get(11..19).map_or(self.at.as_str(), |time| time); format!( "{at}Z · {} · {} · {} ms · ↑{} ↓{} rows · ↑{} ↓{}", self.way.as_deref().unwrap_or("not reached"), self.answer, self.ms, self.pushed, self.pulled, kilobytes(self.sent_bytes), kilobytes(self.received_bytes), ) } } fn kilobytes(bytes: u64) -> String { format!("{:.1} KB", bytes as f64 / 1024.0) } /// The Mac across an exchange, as this device last heard it (phone /// diagnostics, 12 Oct 2026: "254 · c76d108 · schema 134 · Mac mac-c /// 0.29.37 · schema 132"). Built from the exchange answer and the refusal /// text only — what the Mac said, never what this device assumes. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PeerHeard { /// The Mac's name as it gave it (`ExchangeResponse::answered_by`). #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Its app's version label. #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, /// The schema its file is at: the answer's `schemaVersion`, or the number /// a schema refusal names (`400 schemaVersion must be N`, `426 … the file /// is at N`). #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option, /// The last answer in a word: "ok", or the refusal's own sentence /// ("server 400: schemaVersion must be 132", "offline: …"). #[serde(skip_serializing_if = "Option::is_none")] pub answer: Option, /// When that answer came, ISO-8601 UTC. #[serde(skip_serializing_if = "Option::is_none")] pub answered_at: Option, } impl PeerHeard { /// A pass the Mac answered: what the answer said, keeping what it did not. pub fn answered( &mut self, by: Option<&cotton_store::protocol::types::AnsweredBy>, schema: Option, at: &str, ) { self.answer = Some("ok".to_string()); self.answered_at = Some(at.to_string()); if let Some(by) = by { self.name = Some(by.name.clone()); self.version.clone_from(&by.version); } if schema.is_some() { self.schema = schema; } } /// A pass the Mac refused: the schema the refusal names, when it names /// one. The name and version stay as last heard. pub fn refused(&mut self, message: &str, at: &str) { self.answer = Some(message.to_string()); self.answered_at = Some(at.to_string()); if let Some(schema) = schema_in_refusal(message) { self.schema = Some(schema); } } } /// The Mac's file schema a schema refusal names: the 400 a device AHEAD of /// the file gets ("schemaVersion must be 132") and the 426 a device behind it /// gets ("… the file is at 135 — update the app"). `None` for every other /// sentence, and for "schemaVersion must be a u32 integer". pub fn schema_in_refusal(message: &str) -> Option { ["schemaVersion must be ", "the file is at "].iter().find_map(|lead| { let (_, after) = message.split_once(lead)?; let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); digits.parse().ok() }) } /// Who is behind, when the two builds on a sync disagree about the schema. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub enum SchemaStanding { /// This build folds a schema older than the file's: the server answered /// `426 upgrade_required`, and nothing moves until THIS app is updated. PhoneBehind, /// The server's build is older than this one: it held every write this /// device offered (`server_behind`), and they go the moment the Mac is /// updated. Pulls still land. ServerBehind, } impl Default for SyncStatus { fn default() -> Self { SyncStatus { database: String::new(), available: true, state: SyncState::Stopped, pending: 0, held: 0, last_pull_at: None, last_push_at: None, last_error: None, failures: 0, next_attempt_at: None, stopped_reason: None, stopped_code: None, schema: None, behind_by: None, wake_refusal: None, peer: PeerHeard::default(), pass_started_at: None, caught_up: false, } } }