//! THE seam: which server this Mac talks to — the part of it that exists in 3a. //! //! A partial port of the deleted Electron app's `main/client/connection.ts`. What is //! here is what the shell and the menu bar need before there is a sync loop: //! what `/client/connection.json` holds, and which refusals are //! TERMINAL (the four that stop the loop for good, because retrying against a //! decision only a person can reverse is a battery, not a fix). The transports — //! `remote` HTTP with the device signature, and `embedded` calling the sync //! routes' own functions with no port, no bearer and no JSON round trip — //! arrive with the sync loop in 3e. //! //! The seam's rule holds from here on: everything downstream takes this object, //! never a URL. //! //! ## AND IT HOLDS MORE THAN ONE DATABASE //! //! The record is the person's own database ("Mine") plus a list of PLACES — //! other databases this device syncs ([`ConnectionRecord`]). Mine's fields //! stay at the top level of the file, so everything that asks "which server, //! which workspace" still reads Mine. A place is never removed because a //! server stopped listing it: absence only flags it unavailable, and the //! replica, outbox and media it holds stay where they are. Removing one is a //! decision the owner makes, never an answer a server gives. use std::path::Path; use serde::{Deserialize, Serialize}; /// Where a workspace's data lives, as this Mac understands it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ConnectionMode { /// The data is on another server — the Mac they paired with, or a hosted /// one. Remote, /// This device serves its own database locally until a Mac joins it. /// /// What a phone that pressed *Start* is in until a Mac arrives /// (`crate::start::start_local`). The replica is at the ordinary client /// address and every read and write path works against it; what is absent /// is the other end of the sync loop, and that is a STATE rather than a /// failure — `base_url` is empty, [`ConnectionFile::base_url`] answers /// `None` so no request is ever made, and the loop reports `noServerYet` /// instead of climbing a backoff ladder against nobody. Local, } impl ConnectionMode { /// Is there a server on the other end of this connection at all? /// /// The one question every caller that used to spell `== Remote` was really /// asking. `Local` is the variant that made the spelling wrong: a device /// serving its own database has no remote sync peer. #[must_use] pub fn has_server(self) -> bool { !matches!(self, ConnectionMode::Local) } } /// What `/client/connection.json` holds. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StoredConnection { /// A placement-only connection holds an address and identity, never a replica. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "read_device_scope", serialize_with = "write_device_scope")] pub device_scope: Option, #[serde(default)] pub takes_placements: bool, pub mode: ConnectionMode, /// An origin — scheme, host, optional port. No path, no trailing slash. pub base_url: String, /// MINE: the person's own workspace, once `POST /v1/me` has named one. /// Other databases this device syncs are places in [`ConnectionRecord`], /// never this field. pub workspace_id: Option, /// Who the server filed that workspace under. pub owner_id: Option, /// When this Mac was approved and joined, ISO-8601 UTC. pub connected_at: Option, } fn write_device_scope(scope: &Option, encoder: S) -> Result { cotton_store::device_scope::DeviceScope::parse(scope.as_deref()).map_err(serde::ser::Error::custom)?; scope.serialize(encoder) } fn read_device_scope<'de, D: serde::Deserializer<'de>>(decoder: D) -> Result, D::Error> { let scope = Some(String::deserialize(decoder)?); cotton_store::device_scope::DeviceScope::parse(scope.as_deref()).map_err(serde::de::Error::custom)?; Ok(scope) } /// The whole of `connection.json`: Mine's entry, and the places. /// /// Mine is FLATTENED, so the file is one object with Mine's fields at the top /// level and `places` beside them — every reader that wants only Mine reads /// the same keys it always did. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ConnectionRecord { #[serde(flatten)] pub mine: StoredConnection, #[serde(default)] pub places: Vec, /// Databases explicitly left on this device. Household listings cannot /// silently rejoin them; a new invitation may admit one again. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub left_databases: Vec, /// Leaves the serving Mac has not yet taken: a database joined at another /// person's Mac was left on this device while that Mac was away (or its /// vault was locked). Each is told to that Mac again on the next pass over /// the joined databases until it answers, so the person's admission ends /// there too and the owner's People no longer lists them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pending_leaves: Vec, } /// A leave still owed to the Mac that served the database. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PendingLeave { pub database: String, pub origin: String, pub server_device_id: String, } /// One other database this device syncs. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlaceEntry { /// The database's id — its workspace id, and the name of its replica. pub id: String, pub name: Option, /// Did the last answer to `GET /v1/me/databases` list it? `false` stops its /// sync loop and keeps everything it holds; the device keeps asking. pub available: bool, /// When it was last seen to go missing, ISO-8601 UTC. `None` while listed. pub unavailable_since: Option, /// The origin of the Mac that serves it, for a database JOINED at another /// person's Mac ([`joined::JoinedDatabase`]). `None` for a database at the /// household's own address, which is every database a listing admitted. #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option, /// The device id of the Mac the invite named — the only Mac this entry's /// requests are signed to. `None` beside a `None` origin. #[serde(default, skip_serializing_if = "Option::is_none")] pub server_device_id: Option, /// When this device was removed from the database (`device_revoked` at /// its origin), ISO-8601 UTC. From then the copy is in this device's Bin /// and nowhere else — no list, read or write reaches it — until it is /// purged [`joined::REMOVED_COPY_DAYS`] later; a listing never clears /// this, and a new admission starts a fresh copy. #[serde(default, skip_serializing_if = "Option::is_none")] pub removed_at: Option, /// WHO REMOVED this device, by name: the refusal's `removedBy`, else the /// database's owner as the copy named them when the removal was heard. /// `None` when neither was known. #[serde(default, skip_serializing_if = "Option::is_none")] pub removed_by: Option, /// MADE ON THIS DEVICE and not yet taken by the household's server /// ([`crate::start::start_place`]). A listing that does not name it has /// not lost it — the server has never heard of it — so it is never /// flagged gone; the first listing that names it clears this. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub pending: bool, /// What the database was made for. Its starter definitions and home /// arrangement are installed into the file before this listing is saved. #[serde(default, skip_serializing_if = "Option::is_none")] pub toolkit: Option, } impl PlaceEntry { /// Is this entry synced — listed, and this device not removed from it? #[must_use] pub fn syncs(&self) -> bool { self.available && self.removed_at.is_none() } } pub mod held; pub mod joined; pub mod list; #[derive(Debug, thiserror::Error)] pub enum ConnectionFileError { #[error("{path}: {source}")] Read { path: String, #[source] source: std::io::Error, }, #[error("{path} is not a connection file: {source}")] Parse { path: String, #[source] source: serde_json::Error, }, /// A file a NEWER build wrote. Moving it back would drop what that build /// knows, so it is refused by name rather than read short. #[error("{path} is a connection file of shape {found}, newer than this build's {known}")] Ahead { path: String, found: u64, known: u64 }, } /// THE SHAPE THIS BUILD WRITES, stamped as `shape` on every write. /// /// A client file of an older shape is MOVED FORWARD IN PLACE when it is read — /// never refused — the way the store's files are moved at open: each step in /// [`SHAPE_MOVES`] takes a file from shape `n` to `n + 1`, and the moved file /// is written back stamped, so the move runs once. A file with no stamp is /// shape 0: every file written before the stamp existed. pub const CONNECTION_SHAPE: u64 = 2; /// One move per shape: `SHAPE_MOVES[n]` takes a shape-`n` file to `n + 1`. /// A new shape is a new step here and a rise of [`CONNECTION_SHAPE`]. const SHAPE_MOVES: [fn(&mut serde_json::Map); CONNECTION_SHAPE as usize] = [unstamped_to_1, serving_era_to_2]; /// 0 → 1: a file with no `mode` gets the one its address implies. /// /// Every writer in this code's history wrote `mode`; a file without one was /// written by hand or by a tool outside it (a Mac, 13 Oct 2026: the host's /// `setUpdateHold` refused `missing field mode`). An address is a server to /// talk to — `remote`; no address is a device holding its own database with /// no server yet — `local`. fn unstamped_to_1(file: &mut serde_json::Map) { if file.contains_key("mode") { return; } let address = file .get("baseUrl") .and_then(serde_json::Value::as_str) .map(str::trim) .unwrap_or_default() .to_string(); let mode = if address.is_empty() { "local" } else { "remote" }; file.insert("mode".to_string(), serde_json::Value::from(mode)); file.insert("baseUrl".to_string(), serde_json::Value::from(address)); } /// 1 → 2: what only the serving Macs wrote goes. /// /// `embedded` said the server was in this process; no build serves, so the /// address it names is a server like any other — `remote`, the address kept. /// `admittedBy` and `householdMacs` were the relay join's pairing answer, and /// a place's `servedHere` was a stand-down's mark: nothing reads any of them. fn serving_era_to_2(file: &mut serde_json::Map) { if file.get("mode").and_then(serde_json::Value::as_str) == Some("embedded") { file.insert("mode".to_string(), serde_json::Value::from("remote")); } file.remove("admittedBy"); file.remove("householdMacs"); if let Some(places) = file.get_mut("places").and_then(serde_json::Value::as_array_mut) { for place in places.iter_mut().filter_map(serde_json::Value::as_object_mut) { place.remove("servedHere"); } } } /// Move a parsed file forward to [`CONNECTION_SHAPE`]. `Ok(true)` when it /// moved and must be written back; `Ok(false)` for a file already current. fn move_forward( path: &Path, value: &mut serde_json::Value, ) -> Result { let Some(file) = value.as_object_mut() else { // Not an object: no move applies, and the typed read names the fault. return Ok(false); }; let found = file .get("shape") .and_then(serde_json::Value::as_u64) .unwrap_or(0); if found > CONNECTION_SHAPE { return Err(ConnectionFileError::Ahead { path: path.display().to_string(), found, known: CONNECTION_SHAPE, }); } for step in &SHAPE_MOVES[found as usize..] { step(file); } file.insert("shape".to_string(), serde_json::Value::from(CONNECTION_SHAPE)); Ok(found < CONNECTION_SHAPE) } /// Read `connection.json`, or `None` when this Mac has not connected yet. /// /// A MISSING file is an answer ("nothing to sync against"); an unreadable or /// malformed one is an error, never a silent fresh start — that would drop a /// person's pairing on a bad disk read and re-pair as a new device. /// /// Mine's entry only: see [`read_record`] for the places. pub fn read_connection(path: &Path) -> Result, ConnectionFileError> { Ok(read_record(path)?.map(|record| record.mine)) } /// Is this device a runner — paired at scope `runner`, so it holds no copy of /// any database and serves none? An unreadable or missing connection is not /// a runner: it is a device that has not joined, and holds nothing yet. A Mac /// becoming a runner (its journal present) holds none open either. pub fn holds_no_copy(layout: &crate::layout::Layout) -> bool { // A Mac on its way to becoming a runner holds its copies shut too. if layout.becoming_runner_journal().exists() { return true; } read_connection(&layout.connection_json()) .ok() .flatten() .and_then(|stored| cotton_store::device_scope::DeviceScope::parse(stored.device_scope.as_deref()).ok()) == Some(cotton_store::device_scope::DeviceScope::Runner) } /// Read the whole record — Mine and the places — with [`read_connection`]'s /// rules about a missing and a broken file. pub fn read_record(path: &Path) -> Result, ConnectionFileError> { let text = match std::fs::read_to_string(path) { Ok(text) => text, Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(source) => { return Err(ConnectionFileError::Read { path: path.display().to_string(), source, }) } }; let parse = |source| ConnectionFileError::Parse { path: path.display().to_string(), source, }; let mut value: serde_json::Value = serde_json::from_str(&text).map_err(parse)?; let moved = move_forward(path, &mut value)?; let record: ConnectionRecord = serde_json::from_value(value).map_err(parse)?; cotton_store::device_scope::DeviceScope::from_pair(record.mine.device_scope.as_deref(), Some(i64::from(record.mine.takes_placements))) .map_err(|reason| parse(::custom(reason)))?; if !moved { return Ok(Some(record)); } // AN OLDER SHAPE IS WRITTEN BACK MOVED, at once and in place, so the move // runs once and every later reader — this build's or a tool's — reads the // current shape. ONLY OVER THE TEXT IT WAS MOVED FROM: under the one write // lock, and only if the file still holds what was read — a write that // landed in between is newer, and a move-back over it would be a lost // update; that file is read again instead. A write that fails is this // read's failure, named: a record this device cannot keep is not one to // answer from. let lock = writing(path); let _writing = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner); match std::fs::read_to_string(path) { Ok(now) if now == text => { write_record_holding_the_lock(path, &record)?; Ok(Some(record)) } _ => { drop(_writing); read_record(path) } } } /// THE ONE WRITE LOCK over a connection file in this process: every write, and /// every move-back a read makes, takes the lock of the file it writes. One per /// path, so two files never wait on each other's fsync. fn writing(path: &Path) -> std::sync::Arc> { static LOCKS: std::sync::OnceLock< std::sync::Mutex>>>, > = std::sync::OnceLock::new(); let mut locks = LOCKS .get_or_init(Default::default) .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); std::sync::Arc::clone(locks.entry(path.to_path_buf()).or_default()) } /// Write Mine's entry to `connection.json`, atomically, KEEPING the places. /// /// A join or a Start rewrites Mine; neither is a reason to forget the other /// databases this device syncs. A file that cannot be read has no places to /// keep, and is replaced exactly as it always was. pub fn write_connection( path: &Path, connection: &StoredConnection, ) -> Result<(), ConnectionFileError> { let (places, left_databases, pending_leaves) = read_record(path) .ok() .flatten() .map(|record| (record.places, record.left_databases, record.pending_leaves)) .unwrap_or_default(); write_record( path, &ConnectionRecord { mine: connection.clone(), places, left_databases, pending_leaves, }, ) } /// Write the whole record, atomically. /// /// Through a temp file and a rename, like every other write in this crate that /// matters: a half-written connection file is a device that has joined a server /// whose name is truncated, and the next launch would refuse an address nobody /// typed. pub fn write_record(path: &Path, record: &ConnectionRecord) -> Result<(), ConnectionFileError> { cotton_store::device_scope::DeviceScope::from_pair(record.mine.device_scope.as_deref(), Some(i64::from(record.mine.takes_placements))) .map_err(|reason| ConnectionFileError::Parse {path: path.display().to_string(), source: ::custom(reason)})?; let lock = writing(path); let _writing = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner); write_record_holding_the_lock(path, record) } fn write_record_holding_the_lock( path: &Path, record: &ConnectionRecord, ) -> Result<(), ConnectionFileError> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|source| ConnectionFileError::Read { path: parent.display().to_string(), source, })?; } let parse = |source| ConnectionFileError::Parse { path: path.display().to_string(), source, }; // EVERY WRITE IS STAMPED with this build's shape ([`CONNECTION_SHAPE`]). let mut value = serde_json::to_value(record).map_err(parse)?; if let Some(file) = value.as_object_mut() { file.insert("shape".to_string(), serde_json::Value::from(CONNECTION_SHAPE)); } let body = serde_json::to_string_pretty(&value).map_err(parse)?; // A TEMP NAME OF ITS OWN per write: two readers moving the same older file // forward at once both write it, and a shared temp name had the second // rename find the first had already taken it (ENOENT on a good file). static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let temp = path.with_extension(format!( "json.{}.{}.writing", std::process::id(), WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); write_durably(&temp, path, &format!("{body}\n")).map_err(|source| ConnectionFileError::Read { path: path.display().to_string(), source, }) } /// Write, FSYNC, rename, and fsync the DIRECTORY. /// /// The temp-and-rename alone is atomic against a half-written file and nothing /// else: the bytes and the rename both sit in the operating system's cache, and /// a phone that is force-quit (or loses power) a moment later can come back to /// a connection record that is present and EMPTY, or absent altogether — which /// on this device reads as "never joined" and sends a paired phone to the Join /// screen. The directory fsync is the half that is easy to forget: without it /// the rename itself is the thing that may not have landed. fn write_durably(temp: &Path, path: &Path, body: &str) -> std::io::Result<()> { use std::io::Write; { // not a copy: the connection file. let mut file = std::fs::File::create(temp)?; file.write_all(body.as_bytes())?; file.sync_all()?; } // not a copy: the connection file. std::fs::rename(temp, path)?; if let Some(parent) = path.parent() { // Best effort, and only this half: the bytes are already durable, so a // platform that will not let us open a directory costs the rename's // ordering guarantee rather than the file. if let Ok(dir) = std::fs::File::open(parent) { let _ = dir.sync_all(); } } Ok(()) } /// `connection.json` as the transport's address seam. /// /// THE one owner of "which server this device talks to". A cache sits in front /// of the file because every signed request asks — but the cache is filled from /// the file and never instead of it, so an address that could not be written is /// an address this device does not have. #[derive(Debug)] pub struct ConnectionFile { path: std::path::PathBuf, /// The whole record — Mine and the places — as last read or written. cached: std::sync::Mutex>>, } impl ConnectionFile { pub fn at(path: impl Into) -> ConnectionFile { ConnectionFile { path: path.into(), cached: std::sync::Mutex::new(None), } } pub fn path(&self) -> &Path { &self.path } /// What the file says about MINE, or `None` for a device that has joined /// nothing. /// /// An UNREADABLE file reads as `None` here and as an error through /// [`read_connection`]: this is the address seam, whose caller is a request /// about to go out, and "I could not read the file" and "there is no server" /// mean the same thing to it — no request. The loud form is what a boot /// read uses, so a bad disk is still reported rather than re-paired over. pub fn read(&self) -> Option { self.read_record().map(|record| record.mine) } /// The whole record — Mine and the places — with [`Self::read`]'s rule /// about an unreadable file. pub fn read_record(&self) -> Option { let mut cached = self.cache(); Self::current(&mut cached, &self.path) } /// Refresh after Start or another writer has replaced the connection /// record. Reading the file under the cache lock keeps subsequent owner /// calls and database creation on the connection just established. pub fn reload(&self) -> Option { let mut cached = self.cache(); Self::on_disk(&mut cached, &self.path) } /// Mine's id: the person's own workspace, once one is named. pub fn mine_id(&self) -> Option { self.read().and_then(|stored| stored.workspace_id) } /// Remember Mine — what a join or a Start writes when it completes. /// /// Read, change, write under the cache's lock, so the PLACES already in /// the file are kept: rewriting Mine never forgets another database. pub fn write(&self, connection: StoredConnection) -> Result<(), ConnectionFileError> { let mut cached = self.cache(); let (places, left_databases, pending_leaves) = Self::on_disk(&mut cached, &self.path) .map(|record| (record.places, record.left_databases, record.pending_leaves)) .unwrap_or_default(); let record = ConnectionRecord { mine: connection, places, left_databases, pending_leaves, }; write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(()) } /// Write down what one answer to `GET /v1/me/databases` says about the /// places this record holds. /// /// Only the availability flags change. A place the answer does not list is /// marked unavailable and KEPT — its replica, outbox and media are not this /// call's to touch — and a listed id this record does not hold is handed up /// in [`list::ListChange::new`] and not added here. pub fn apply_listing( &self, listing: &list::Listing, now: &str, ) -> Result { // A signed listing can re-admit a creator copy. Serialize it with // purge across ConnectionFile instances, like an explicit rejoin. let _membership = Self::membership_hold(); let mut cached = self.cache(); let Some(record) = Self::on_disk(&mut cached, &self.path) else { return Ok(list::reconcile(None, &[], listing)); }; let mut change = list::reconcile(record.mine.workspace_id.as_deref(), &record.places, listing); change.new.retain(|database| !record.left_databases.contains(&database.id)); Self::write_listing(&mut cached, &self.path, record, change, now) } /// [`Self::apply_listing`] for the answer of ANOTHER person's Mac at /// `origin`: only the entries joined at that origin change, and nothing it /// lists is ever handed up as new — a database at another Mac arrives by /// an invite, never because that Mac listed it. pub fn apply_listing_at( &self, origin: &str, listing: &list::Listing, now: &str, ) -> Result { let mut cached = self.cache(); let Some(record) = Self::on_disk(&mut cached, &self.path) else { return Ok(list::ListChange::default()); }; let change = list::reconcile_at(origin, &record.places, listing); Self::write_listing(&mut cached, &self.path, record, change, now) } fn write_listing( cached: &mut Option>, path: &Path, mut record: ConnectionRecord, change: list::ListChange, now: &str, ) -> Result { if change.gone.is_empty() && change.back.is_empty() && change.taken.is_empty() { return Ok(change); } for place in &mut record.places { // The server lists a database this device made: it has taken it. if change.taken.contains(&place.id) { place.pending = false; } if change.gone.contains(&place.id) { place.available = false; place.unavailable_since = Some(now.to_string()); } else if change.back.contains(&place.id) { place.available = true; place.unavailable_since = None; if place.origin.is_none() { place.removed_at = None; } } } write_record(path, &record)?; *cached = Some(Some(record)); Ok(change) } /// Record a database MADE ON THIS DEVICE as a place: held from this /// moment, pending until the household's server takes it. Never adds /// Mine, never adds an id twice, and needs a personal database to stand /// beside. pub fn add_made_place( &self, id: &str, name: &str, toolkit: Option<&str>, ) -> Result<(), ConnectionFileError> { let mut cached = self.cache(); let Some(mut record) = Self::current(&mut cached, &self.path) .filter(|record| record.mine.workspace_id.is_some()) else { return Err(ConnectionFileError::Read { path: self.path.display().to_string(), source: std::io::Error::new( std::io::ErrorKind::NotFound, "this device has no personal database to make another beside", ), }); }; if record.places.iter().any(|entry| entry.id == id) { return Ok(()); } record.places.push(PlaceEntry { id: id.to_string(), name: Some(name.to_string()), available: true, unavailable_since: None, origin: None, server_device_id: None, removed_at: None, removed_by: None, pending: true, toolkit: toolkit.map(str::to_string), }); write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(()) } /// This device was removed from a shared database, or its creator deleted /// it: stop syncing it and put its copy in this device's Bin for thirty /// days — `by` is who removed it, when known. Personal is never removed. /// Answers whether the record changed. pub fn mark_removed( &self, database: &str, now: &str, by: Option<&str>, ) -> Result { let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(false); }; if record.mine.workspace_id.as_deref() == Some(database) { return Ok(false); } let Some(entry) = record .places .iter_mut() .find(|entry| entry.id == database) else { return Ok(false); }; if entry.removed_at.is_some() { return Ok(false); } entry.removed_at = Some(now.to_string()); if entry.origin.is_none() { entry.available = false; entry.unavailable_since = Some(now.to_string()); } entry.removed_by = by.map(str::trim).filter(|name| !name.is_empty()).map(str::to_string); write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(true) } /// Leave exactly one held shared database. The personal connection and /// every other database are preserved, even if the server lists it again. pub fn forget_database(&self, database: &str) -> Result, ConnectionFileError> { let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(None) }; if record.mine.workspace_id.as_deref() == Some(database) { return Ok(None); } let Some(at) = record.places.iter().position(|entry| entry.id == database) else { return Ok(None) }; let entry = record.places.remove(at); if !record.left_databases.iter().any(|id| id == database) { record.left_databases.push(database.to_owned()); } write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(Some(entry)) } /// Owe the serving Mac a leave it has not taken yet (the device left /// `database` while the Mac was away). Idempotent per database. pub fn queue_leave(&self, leave: PendingLeave) -> Result<(), ConnectionFileError> { let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(()) }; if record.pending_leaves.iter().any(|pending| pending.database == leave.database) { return Ok(()); } record.pending_leaves.push(leave); write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(()) } /// The serving Mac took the leave (or will never take it): stop owing it. pub fn settle_leave(&self, database: &str) -> Result<(), ConnectionFileError> { let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(()) }; let before = record.pending_leaves.len(); record.pending_leaves.retain(|pending| pending.database != database); if record.pending_leaves.len() == before { return Ok(()); } write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(()) } /// Forget a database this device was REMOVED from — the first half of /// purging its copy. Answers the entry that went, or `None` when the /// record holds no such removed entry: a database this device still /// syncs, the personal one and one at the household's own address are /// never forgotten here. The database is named LEFT, as a leave names it, /// so the person's joined places never offer it back as "on another /// device"; a new admission lifts the mark. pub fn forget_removed( &self, database: &str, ) -> Result, ConnectionFileError> { let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(None); }; let Some(at) = record.places.iter().position(|entry| { entry.id == database && entry.origin.is_some() && entry.removed_at.is_some() }) else { return Ok(None); }; let entry = record.places.remove(at); if !record.left_databases.iter().any(|id| id == database) { record.left_databases.push(database.to_owned()); } write_record(&self.path, &record)?; *cached = Some(Some(record)); Ok(Some(entry)) } /// Purge a removed joined copy while holding its connection entry stable. /// The bytes go before the entry: an interrupted purge retains its marker /// for retry, and a concurrent re-admission cannot race the unlink. pub fn purge_removed_with( &self, database: &str, now: chrono::DateTime, purge: impl FnOnce(&str) -> Result<(), String>, ) -> Result { self.purge_removed_if(database, |at| cotton_store::database_bin::purge_due(at, now), purge) } /// [`Self::purge_removed_with`] whatever the removal's age — a new /// admission at the same Mac starts a fresh copy. pub fn purge_removed_now_with( &self, database: &str, purge: impl FnOnce(&str) -> Result<(), String>, ) -> Result { self.purge_removed_if(database, |_| true, purge) } /// An archived copy was dropped, not left: lift the LEFT mark its purge /// wrote, so the listing that names it again after a restore brings it /// back. Answers whether the record changed. pub fn unmark_left(&self, database: &str) -> Result { let _membership = Self::membership_hold(); let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(false) }; let before = record.left_databases.len(); record.left_databases.retain(|id| id != database); if record.left_databases.len() == before { return Ok(false); } write_record(&self.path, &record).map_err(|error| error.to_string())?; *cached = Some(Some(record)); Ok(true) } fn purge_removed_if( &self, database: &str, due: impl Fn(&str) -> bool, purge: impl FnOnce(&str) -> Result<(), String>, ) -> Result { let _membership = Self::membership_hold(); let mut cached = self.cache(); let Some(mut record) = Self::on_disk(&mut cached, &self.path) else { return Ok(false); }; if record.mine.workspace_id.as_deref() == Some(database) { return Ok(false); } let Some(at) = record.places.iter().position(|entry| { entry.id == database && entry.removed_at.as_deref().is_some_and(&due) }) else { return Ok(false) }; purge( record.places[at] .removed_at .as_deref() .expect("the due check found a date"), )?; record.places.remove(at); // Named LEFT, as a leave names it, so the person's joined places // never offer it back as "on another device"; a new admission lifts // the mark. if !record.left_databases.iter().any(|id| id == database) { record.left_databases.push(database.to_owned()); } write_record(&self.path, &record).map_err(|error| error.to_string())?; *cached = Some(Some(record)); Ok(true) } /// Remove this device's connection — Mine's leave, and the erase path. /// /// The whole file goes, places included: a device that leaves Mine has /// left. The device key and the op-author id are NOT touched — they are /// this device's identity, not its address. Leaving one place is not /// this call. pub fn forget(&self) { // not a copy: the connection file. let _ = std::fs::remove_file(&self.path); *self.cache() = Some(None); } // Admission can be written through a fresh ConnectionFile at the same // path. A per-instance cache lock alone cannot exclude it during purge. fn membership_hold() -> std::sync::MutexGuard<'static, ()> { static HOLD: std::sync::Mutex<()> = std::sync::Mutex::new(()); HOLD.lock().unwrap_or_else(|error| error.into_inner()) } fn cache(&self) -> std::sync::MutexGuard<'_, Option>> { self.cached .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The record AS THE FILE HOLDS IT NOW, for a change about to be written. /// /// Never the cache: this object is not the file's only writer — a join /// rewrites Mine through an object of its own — and a change made over a /// remembered copy would write that copy back, dropping whatever the /// other writer added. fn on_disk( cached: &mut Option>, path: &Path, ) -> Option { *cached = None; Self::current(cached, path) } /// The record, from the cache or — the first time — the file. fn current( cached: &mut Option>, path: &Path, ) -> Option { if let Some(known) = cached.as_ref() { return known.clone(); } let fresh = read_record(path).ok().flatten(); *cached = Some(fresh.clone()); fresh } } impl ConnectionFile { /// What the FILE remembers — the join's own answer, and the first one. /// /// `None` for a LOCAL connection as well as for no connection at all, and /// the two mean the same thing here: the join wrote down no server. An /// empty string handed up would be an origin every signed request went out /// against. fn remembered_url(&self) -> Option { self.read() .filter(|stored| stored.mode.has_server()) .map(|stored| stored.base_url) .filter(|url| !url.is_empty()) } } impl crate::transport::ServerAddress for ConnectionFile { /// The address, or `None` when there is nowhere to send a request: what /// the file remembers, and nothing else. fn base_url(&self) -> Option { self.remembered_url() } fn mine_id(&self) -> Option { ConnectionFile::mine_id(self) } /// The database, by the SAME rule as the address: the one the join wrote /// down beside the server. A LOCAL connection's workspace is a database /// no server holds yet, so it names nothing: sending it to a server the /// phone is joining would be naming a file that server has never seen. fn database(&self) -> Option { self.read() .filter(|stored| stored.mode.has_server() && !stored.base_url.is_empty()) .and_then(|stored| stored.workspace_id) .filter(|id| !id.is_empty()) } } /// The four refusals that stop the sync loop for good. pub const TERMINAL_DEVICE_CODES: [&str; 4] = [ "device_not_approved", "device_revoked", "device_bad_signature", "no_device_key", ]; pub fn is_terminal_device_refusal(code: &str) -> bool { TERMINAL_DEVICE_CODES.contains(&code) } /// What this build calls the machine it runs on, mid-sentence. /// /// The crate is compiled per target, so the noun is decided where the /// sentence is written rather than handed down from a caller — a phone that /// read "this Mac's access was revoked" was a Mac's sentence on a phone's /// screen. pub const THIS_DEVICE: &str = if cfg!(target_os = "macos") { "this Mac" } else if cfg!(any(target_os = "ios", target_os = "android")) { "this phone" } else { "this device" }; /// The sentence the window shows for a terminal refusal — what happened, and /// what a person does about it. Names the device by [`THIS_DEVICE`]. pub fn terminal_device_sentence(code: &str) -> Option { let noun = THIS_DEVICE; match code { "device_not_approved" => Some(format!( "{noun} is not an approved device on that server — approve it from a device that already is, then connect again" )), "device_revoked" => Some(format!( "{noun}'s access was revoked on that server — pair it again to reconnect" )), "device_bad_signature" => Some(format!( "the server could not verify {noun}'s signature — its device key does not match the one approved; pair again" )), "no_device_key" => Some(format!( "{noun} has no device identity to sign with — the Keychain was unavailable when the app started; relaunch from the desktop session" )), _ => None, } } #[cfg(test)] mod tests { use super::*; /// Every shape of `connection.json` this code has ever written, oldest /// first, plus the one found on a Mac with no `mode` (written outside the /// code). Synthetic values only. const EVERY_SHAPE: &[(&str, &str)] = &[ ("no mode, an address (found on a Mac, 13 Oct 2026)", r#"{"baseUrl":"https://example.invalid","workspaceId":"ws-1","ownerId":"owner-1"}"#), ("no mode, no address", r#"{"workspaceId":"ws-1"}"#), ("the Electron app (5 Sep 2026)", r#"{ "mode": "remote", "baseUrl": "https://example.invalid", "workspaceId": null, "ownerId": null, "connectedAt": null }"#), ("Rust v1, embedded (8 Sep 2026)", r#"{"mode":"embedded","baseUrl":"http://127.0.0.1:8787","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":"2026-09-08T00:00:00.000Z"}"#), ("local (17 Sep 2026)", r#"{"mode":"local","baseUrl":"","workspaceId":"ws-1","ownerId":null,"connectedAt":null}"#), ("places (3 Oct 2026)", r#"{"mode":"remote","baseUrl":"https://example.invalid","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":null,"places":[{"id":"ws-2","name":"Shared","available":false,"unavailableSince":"2026-10-03T00:00:00Z"}]}"#), ("left and pending leaves (4 Oct 2026)", r#"{"mode":"remote","baseUrl":"https://example.invalid","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":null,"places":[],"leftDatabases":["ws-3"],"pendingLeaves":[{"database":"ws-3","origin":"https://other.invalid","serverDeviceId":"dev-9"}]}"#), ("admitted by and household Macs (11 Oct 2026)", r#"{"mode":"remote","baseUrl":"https://example.invalid","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":null,"admittedBy":"dev-1","householdMacs":["dev-1","dev-2"],"places":[]}"#), ("stamped, a place served here (13 Oct 2026)", r#"{"shape":1,"mode":"embedded","baseUrl":"http://127.0.0.1:8787","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":null,"admittedBy":"dev-1","places":[{"id":"ws-2","name":"Shared","available":true,"unavailableSince":null,"servedHere":true}]}"#), ]; /// What only the serving Macs wrote: the keys the move to shape 2 takes /// away, and the one value it changes. const SERVING_ERA: &[&str] = &["admittedBy", "householdMacs"]; /// RULE: a client file of any shape this code has ever written is moved forward in place and stamped — never refused — and the move is idempotent, because a refused connection file stops the host writing (a Mac, 13 Oct 2026: setUpdateHold refused `missing field mode`) and a pairing must survive every upgrade. #[test] fn every_shape_ever_written_is_moved_forward_in_place_once() { for (shape, text) in EVERY_SHAPE { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); std::fs::write(&path, text).expect("the file"); let first = read_record(&path) .unwrap_or_else(|error| panic!("{shape}: refused — {error}")) .unwrap_or_else(|| panic!("{shape}: read as absent")); let moved = std::fs::read_to_string(&path).expect("the moved file"); let stamped: serde_json::Value = serde_json::from_str(&moved).expect("json"); assert_eq!(stamped["shape"], serde_json::json!(CONNECTION_SHAPE), "{shape}: not stamped"); // Nothing a field held is lost by the move, but what only a // serving Mac wrote. let before: serde_json::Value = serde_json::from_str(text).expect("json"); for (key, value) in before.as_object().expect("an object") { match key.as_str() { "shape" => {} key if SERVING_ERA.contains(&key) => assert!(stamped.get(key).is_none(), "{shape}: `{key}` kept"), "mode" if value == "embedded" => assert_eq!(stamped[key], "remote", "{shape}: `embedded` not moved"), "places" => { let mut kept = value.clone(); for place in kept.as_array_mut().expect("places").iter_mut() { place.as_object_mut().expect("a place").remove("servedHere"); } assert_eq!(stamped[key], kept, "{shape}: `places` changed in the move"); } _ => assert_eq!(&stamped[key], value, "{shape}: `{key}` changed in the move"), } } // Idempotent: a second read answers the same and writes nothing. let second = read_record(&path).expect("a second read").expect("a value"); assert_eq!(first, second, "{shape}: the second read differs"); assert_eq!(std::fs::read_to_string(&path).expect("the file"), moved, "{shape}: rewritten twice"); } } /// RULE: a file with no `mode` takes the one its address implies — an address is `remote`, none is `local` — because a device with no address has no server to reach. #[test] fn a_file_with_no_mode_takes_the_mode_its_address_implies() { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); std::fs::write(&path, EVERY_SHAPE[0].1).expect("the file"); assert_eq!(read_connection(&path).expect("a read").expect("a value").mode, ConnectionMode::Remote); std::fs::write(&path, EVERY_SHAPE[1].1).expect("the file"); let local = read_connection(&path).expect("a read").expect("a value"); assert_eq!((local.mode, local.base_url.as_str()), (ConnectionMode::Local, "")); } /// RULE: a file a serving Mac wrote still opens — `embedded` is the server at its address, `remote`, and the relay join's admitter, the household's Macs and a stand-down's mark are gone from the file — because no build serves and nothing reads them, and a refused connection file is a pairing lost. #[test] fn a_file_a_serving_mac_wrote_opens_with_what_only_serving_wrote_gone() { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); std::fs::write(&path, EVERY_SHAPE.last().expect("a shape").1).expect("the file"); let record = read_record(&path).expect("a read").expect("a value"); assert_eq!((record.mine.mode, record.mine.base_url.as_str()), (ConnectionMode::Remote, "http://127.0.0.1:8787")); assert_eq!(record.places.len(), 1); assert!(record.places[0].syncs()); let moved = std::fs::read_to_string(&path).expect("the moved file"); for gone in ["embedded", "admittedBy", "householdMacs", "servedHere"] { assert!(!moved.contains(gone), "`{gone}` is still in {moved}"); } } /// RULE: a file of a NEWER shape is refused by name and left untouched, because moving it back would silently drop what the newer build knows. #[test] fn a_file_from_a_newer_build_is_refused_and_left_as_it_is() { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); let ahead = format!(r#"{{"shape":{},"mode":"remote","baseUrl":"https://example.invalid"}}"#, CONNECTION_SHAPE + 1); std::fs::write(&path, &ahead).expect("the file"); assert!(matches!(read_record(&path), Err(ConnectionFileError::Ahead { .. }))); assert_eq!(std::fs::read_to_string(&path).expect("the file"), ahead); } #[test] fn the_file_reads_back_as_the_typescript_wrote_it_camel_case_and_all() { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); std::fs::write( &path, r#"{"mode":"remote","baseUrl":"https://example.invalid","workspaceId":"ws-1","ownerId":"owner-1","connectedAt":"2026-09-08T00:00:00.000Z"}"#, ) .expect("the file"); let stored = read_connection(&path).expect("a read").expect("a value"); assert_eq!(stored.mode, ConnectionMode::Remote); assert_eq!(stored.base_url, "https://example.invalid"); assert_eq!(stored.workspace_id.as_deref(), Some("ws-1")); } #[test] fn a_missing_file_is_an_answer_and_a_broken_one_is_an_error() { let dir = tempfile::tempdir().expect("a temp dir"); assert!(read_connection(&dir.path().join("nothing.json")) .expect("a read") .is_none()); let broken = dir.path().join("connection.json"); std::fs::write(&broken, "{ not json").expect("the file"); assert!(read_connection(&broken).is_err()); } #[test] fn a_write_lands_whole_and_leaves_no_half_written_sibling() { // The temp file is renamed, never left beside the real one — a // `connection.json.writing` that survived would be read by nobody and // would say nothing, and the next launch of a phone whose write was // interrupted has to find either the old record or the new one. let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("client").join("connection.json"); let stored = StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Remote, base_url: "https://example.invalid".to_string(), workspace_id: Some("ws-1".to_string()), owner_id: None, connected_at: Some("2026-09-11T00:00:00.000Z".to_string()), }; write_connection(&path, &stored).expect("the write"); assert_eq!(read_connection(&path).expect("a read"), Some(stored)); let beside: Vec<_> = std::fs::read_dir(path.parent().expect("a parent")) .expect("the directory") .map(|entry| entry.expect("an entry").file_name()) .collect(); assert_eq!(beside, vec![std::ffi::OsString::from("connection.json")]); } #[test] fn rewriting_mine_keeps_the_places_and_mine_reads_back_at_the_top_level() { let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); let mine = StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Remote, base_url: "https://example.invalid".to_string(), workspace_id: Some("ws-1".to_string()), owner_id: None, connected_at: None, }; let place = PlaceEntry { id: "ws-2".to_string(), name: Some("A synthetic place".to_string()), available: true, unavailable_since: None, origin: None, server_device_id: None, removed_at: None, removed_by: None, pending: false, toolkit: None, }; write_record( &path, &ConnectionRecord { mine: mine.clone(), places: vec![place.clone()], left_databases: Vec::new(), pending_leaves: Vec::new(), }, ) .expect("the record"); let file = ConnectionFile::at(&path); file.write(StoredConnection { base_url: "https://other.invalid".to_string(), ..mine }) .expect("the rewrite"); let record = read_record(&path).expect("a read").expect("a record"); assert_eq!(record.places, vec![place]); assert_eq!(record.mine.base_url, "https://other.invalid"); assert_eq!(file.mine_id().as_deref(), Some("ws-1")); // Mine's fields are where every Mine-only reader looks for them. let flat: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the file")) .expect("json"); assert_eq!(flat["workspaceId"], "ws-1"); assert_eq!(flat["places"][0]["id"], "ws-2"); } fn address_of(file: &ConnectionFile) -> Option { use crate::transport::ServerAddress; file.base_url() } /// RULE: One place owns which server holds the data: every source, the copy, the sync loop and the upload queue take that, never a web address of their own. #[test] fn a_device_that_joined_a_server_talks_to_the_one_it_joined() { // The file is the join's own answer, and the only one. let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); write_connection( &path, &StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Remote, base_url: "https://other.relay.cottondb.com".to_string(), workspace_id: Some("ws-1".to_string()), owner_id: None, connected_at: None, }, ) .expect("the write"); let file = ConnectionFile::at(&path); assert_eq!( address_of(&file).as_deref(), Some("https://other.relay.cottondb.com") ); } #[test] fn the_database_follows_the_address_and_a_local_one_names_none() { use crate::transport::ServerAddress; let dir = tempfile::tempdir().expect("a temp dir"); let path = dir.path().join("connection.json"); let connected = |mode: ConnectionMode| StoredConnection { device_scope: None, takes_placements: false, mode, base_url: "https://other.relay.cottondb.com".to_string(), workspace_id: Some("ws-joined".to_string()), owner_id: None, connected_at: None, }; // A device that JOINED names the database it joined. write_connection(&path, &connected(ConnectionMode::Remote)).expect("the write"); let file = ConnectionFile::at(&path); assert_eq!(file.database().as_deref(), Some("ws-joined")); // A LOCAL database is one no server holds yet: naming it to a server // would name a file that server has never seen, so nothing is named. write_connection(&path, &connected(ConnectionMode::Local)).expect("the write"); let file = ConnectionFile::at(&path); assert_eq!(file.database(), None); } #[test] fn every_terminal_code_has_a_sentence_and_nothing_else_does() { for code in TERMINAL_DEVICE_CODES { assert!(is_terminal_device_refusal(code)); let sentence = terminal_device_sentence(code).unwrap_or_else(|| panic!("{code}")); assert!( sentence.contains(THIS_DEVICE), "the sentence names the machine it is shown on: {sentence}" ); } assert!(!is_terminal_device_refusal("rate_limited")); assert!(terminal_device_sentence("rate_limited").is_none()); } }