//! Which databases the server lets this device sync: the answer to //! `GET /v1/me/databases`, and what that answer changes. //! //! **The probe comes before any push.** A sync pass for a database asks this //! first, and a database the answer does not list sends nothing — its file is //! not even opened for the pass. A place that drops off the list keeps //! everything it holds; the device keeps asking, and when the id comes back //! the loop carries on from the kept replica. //! //! **The wire shapes here are the ONE place this client spells them**, and the //! route, the `database=` query and the `x-cotton-database` header are //! `cotton_core::device::database`'s spellings — the server reads the same //! constants, so the two ends cannot drift. use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; use crate::seams::Clock; use crate::transport::{ClientRequest, ServerFetch, ServerRefusal}; use super::{ConnectionFile, PlaceEntry}; /// The route that lists this device's databases (slice P3 serves it). pub const DATABASES_PATH: &str = cotton_core::device::database::DATABASES_PATH; /// The query parameter a signed request names its database with (slice P3). /// Inside the signed string, because the signature covers path and query. pub const DATABASE_QUERY: &str = cotton_core::device::database::DATABASE_PARAM; /// The header an answer names its database with (slice P3). A server older /// than P3 sends none. pub const DATABASE_HEADER: &str = cotton_core::device::database::DATABASE_HEADER; /// One database the server lists for this device. /// /// Wire: `{"id","name","kind","schemaVersion"}` (slice P3). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListedDatabase { pub id: String, pub name: String, pub kind: String, pub schema_version: u32, } /// The whole answer: `{"databases":[…]}` (slice P3). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Listing { pub databases: Vec, } impl Listing { pub fn lists(&self, id: &str) -> bool { self.databases.iter().any(|database| database.id == id) } } /// What one listing changes against the record. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ListChange { /// Mine is in the list. When it is not, the device is refused everywhere. pub mine_listed: bool, /// Places that WERE available and the list no longer names. Flagged /// unavailable, never removed. pub gone: Vec, /// Places that were unavailable and the list names again. pub back: Vec, /// Listed databases the record holds neither as Mine nor as a place. /// Handed up for the first fill; nothing here opens them. pub new: Vec, /// Databases this device MADE, or served until it stood down, that the /// list names for the first time: the server has taken them. pub taken: Vec, } /// Compare one listing with the record. Pure: it decides, the caller writes. pub fn reconcile(mine_id: Option<&str>, places: &[PlaceEntry], listing: &Listing) -> ListChange { let mut change = ListChange { mine_listed: mine_id.is_some_and(|id| listing.lists(id)), ..ListChange::default() }; // The household's list speaks for the databases at the household's own // address. One joined at another person's Mac is that Mac's to list. flags(places.iter().filter(|place| place.origin.is_none()), listing, &mut change); for database in &listing.databases { let held = Some(database.id.as_str()) == mine_id || places.iter().any(|place| place.id == database.id); if !held { change.new.push(database.clone()); } } change } /// Compare the listing of ANOTHER person's Mac at `origin` with the entries /// joined there. Nothing is ever `new` and Mine is never listed: that Mac's /// answer changes only whether the entries it was invited to are available. pub fn reconcile_at(origin: &str, places: &[PlaceEntry], listing: &Listing) -> ListChange { let mut change = ListChange::default(); flags( places .iter() .filter(|place| place.origin.as_deref() == Some(origin)), listing, &mut change, ); change } fn flags<'a>( places: impl Iterator, listing: &Listing, change: &mut ListChange, ) { for place in places { let listed = listing.lists(&place.id); if place.pending { // Made here and not yet taken by the server: a list without it // has lost nothing, and the first list with it has taken it. if listed { change.taken.push(place.id.clone()); } } else if place.available && !listed { change.gone.push(place.id.clone()); } else if !place.available && listed { change.back.push(place.id.clone()); } } } /// Ask the server which databases this device may sync. /// /// Sent with NO database named, so a refusal of it is filed against Mine — the /// list is a question about the device, not about one place. pub fn probe(fetch: &dyn ServerFetch) -> Result { fetch.call(ClientRequest::get(DATABASES_PATH))?.json::() } /// The route that makes a database, or takes one a device made. pub const MAKE_DATABASE_PATH: &str = "/v1/databases"; /// Hand the server every database this device made while it could not reach /// it: `POST /v1/databases {id}` for each pending place, signed into the /// device's own database. Answers how many the server took. /// /// Before the list is asked, so the listing of the same pass names what was /// just taken and the pass carries its first rows. A refusal leaves the /// place pending and is tried again next pass: the database is whole on this /// device either way. pub fn hand_over_made(fetch: &dyn ServerFetch, connection: &ConnectionFile, own: &str) -> usize { let Some(record) = connection.read_record() else { return 0; }; let mut taken = 0; for place in record.places.iter().filter(|place| place.pending) { let Some(root) = connection.path().parent().and_then(std::path::Path::parent) else { continue; }; let layout = crate::layout::Layout::new(root); let founder = (|| -> cotton_store::Result> { let db = cotton_store::Driver::open_reader(layout.replica(&place.id))?; let key = db.get("SELECT device_key FROM cotton_device_statements ORDER BY _hlc LIMIT 1", &[])?.and_then(|row| row.text("device_key").map(str::to_string)); key.map(|key| cotton_tools::founding::Founder::read(&db, &key)).transpose().map(Option::flatten) })(); let Ok(Some(founder)) = founder else { continue; }; let body = serde_json::json!({ "id": place.id, "name": place.name, "founder": founder }) .to_string() .into_bytes(); let request = ClientRequest::post_json(MAKE_DATABASE_PATH, body).for_database(own); match fetch.call(request) { Ok(_) => taken += 1, Err(refusal) => eprintln!( "[cotton-sync] the database {} made on this device was not taken yet: {}", place.id, refusal.message ), } } taken } /// The last listing this process saw, shared by every database's transport. /// /// In memory only: the record keeps the availability flags across a relaunch, /// and a fresh process asks again before it pushes anything. #[derive(Debug)] pub struct DatabaseList { clock: Arc, last: Mutex>, /// Whose list this is: `None` for the household's own server, or the /// origin of another person's Mac. One list per origin, never shared. origin: Option, } #[derive(Debug, Clone)] struct Seen { listing: Listing, at_ms: i64, } impl DatabaseList { pub fn new(clock: Arc) -> Arc { Arc::new(DatabaseList { clock, last: Mutex::new(None), origin: None, }) } /// The list of another person's Mac at `origin`: its answers change only /// the entries joined there ([`ConnectionFile::apply_listing_at`]). pub fn at(clock: Arc, origin: &str) -> Arc { Arc::new(DatabaseList { clock, last: Mutex::new(None), origin: Some(origin.to_string()), }) } fn seen(&self) -> std::sync::MutexGuard<'_, Option> { self.last .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Did the last answer list `id`? `false` until the first answer arrives: /// nothing is pushed on the strength of a list nobody has read. pub fn is_listed(&self, id: &str) -> bool { self.seen() .as_ref() .is_some_and(|seen| seen.listing.lists(id)) } /// The last answer, and when it was taken (epoch ms). pub fn last(&self) -> Option<(Listing, i64)> { self.seen() .as_ref() .map(|seen| (seen.listing.clone(), seen.at_ms)) } /// Take a fresh answer, and write what it changes into the record. /// /// The in-memory list moves even when the record cannot be written: what /// is pushed is decided by what the server said just now, and a record /// that could not be updated is reported, not a reason to push against /// an older answer. pub fn observe(&self, listing: Listing, connection: &ConnectionFile) -> ListChange { let now = self.clock.now(); *self.seen() = Some(Seen { listing: listing.clone(), at_ms: now.timestamp_millis(), }); let applied = match &self.origin { None => connection.apply_listing(&listing, &crate::seams::iso(now)), Some(origin) => connection.apply_listing_at(origin, &listing, &crate::seams::iso(now)), }; match applied { Ok(change) => change, Err(error) => { eprintln!("[cotton-sync] the database list could not be written down: {error}"); let record = connection.read_record(); if let Some(origin) = &self.origin { return reconcile_at( origin, record .as_ref() .map_or(&[], |record| record.places.as_slice()), &listing, ); } reconcile( record .as_ref() .and_then(|record| record.mine.workspace_id.as_deref()), record .as_ref() .map_or(&[], |record| record.places.as_slice()), &listing, ) } } } } #[cfg(test)] #[path = "list_tests.rs"] mod tests;