//! A database this device holds that ANOTHER PERSON'S Mac serves. //! //! A device's own databases are at its household's address: the personal one //! by the join, the others by that server's list. A database a person was //! invited to is somewhere else — the inviter's Mac — and it is held beside //! the device's own without sharing anything with them: its own origin, its //! own pinned Mac, its own list, its own refusal note, its own exchange. //! //! So a refusal there is about that database and nothing else. Being removed //! from it ([`ConnectionFile::mark_removed`](super::ConnectionFile::mark_removed)) //! stops its sync and puts its copy in this device's Bin — reachable from //! nothing else, purged [`REMOVED_COPY_DAYS`] later (architect's ruling, //! 16 Oct 2026); the personal database carries on, because nothing the other //! Mac says was ever filed against it. use std::path::{Path, PathBuf}; use sha2::{Digest, Sha256}; use super::{ConnectionRecord, PlaceEntry}; /// What an invite hands this device: the database, and the one Mac it is at. #[derive(Debug, Clone, PartialEq, Eq)] pub struct JoinedDatabase { pub id: String, pub name: String, /// The serving Mac's origin — scheme, host, optional port. pub origin: String, /// The serving Mac's device id. Requests for this database are signed to /// a Mac that answers as this one and to no other. pub server_device_id: String, } /// The databases this device syncs at ONE origin — one exchange a cycle. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OriginGroup { /// `None` is the household's own address (the connection record's). pub origin: Option, /// The pinned Mac, for another person's origin. pub server_device_id: Option, pub databases: Vec, } impl OriginGroup { pub fn is_joined(&self) -> bool { self.origin.is_some() } } /// Which Mac answers for ONE held database: the household's, or the one an /// invite pinned. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ServedAt { /// The household's own address — the device's own database and every /// database a household listing admitted. Household, /// Another person's Mac, and the device id it must answer as. Joined { origin: String, server_device_id: String, }, } /// Why no Mac answers for a database on this device. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NotServed { /// No synced entry names it: never held, unlisted, or removed from it. NotHeld, /// An entry with an origin and no pinned Mac, or a pin and no origin — /// nothing a request could be signed to. NoVerifiedMac, } impl NotServed { /// The code a refusal of this carries — the same for an owner call and /// for a byte, so the two say one thing. pub fn code(self) -> &'static str { "database_not_held" } pub fn sentence(self) -> &'static str { match self { NotServed::NotHeld => "This device does not hold that database.", NotServed::NoVerifiedMac => "This database has no verified serving Mac.", } } } /// Where every request about `database` goes — owner calls and bytes alike. /// /// ONE RULE for both, because the two disagreeing is the bug this exists to /// end: the owner calls went to the pinned Mac while every picture of the same /// database went to the household, which refused it as a stranger's. pub fn served_at(record: &ConnectionRecord, database: &str) -> Result { if record.mine.workspace_id.as_deref() == Some(database) { return Ok(ServedAt::Household); } let place = record .places .iter() .find(|place| place.id == database && place.syncs()) .ok_or(NotServed::NotHeld)?; match (&place.origin, &place.server_device_id) { (None, None) => Ok(ServedAt::Household), (Some(origin), Some(key)) => Ok(ServedAt::Joined { origin: origin.clone(), server_device_id: key.clone(), }), _ => Err(NotServed::NoVerifiedMac), } } /// Every origin this device syncs at, the household's own first, each with /// the databases held there. An entry that is unlisted or removed is in no /// group: nothing is sent for it. pub fn origin_groups(record: &ConnectionRecord) -> Vec { let mut groups: Vec = Vec::new(); if let Some(mine) = record.mine.workspace_id.clone() { groups.push(OriginGroup { origin: None, server_device_id: None, databases: vec![mine], }); } for place in record.places.iter().filter(|place| place.syncs()) { let at = groups.iter_mut().find(|group| { group.origin == place.origin && group.server_device_id == place.server_device_id }); match at { Some(group) => { if !group.databases.contains(&place.id) { group.databases.push(place.id.clone()); } } // A household entry on a device with no personal database has no // address to be sent to. None if place.origin.is_none() => {} None => groups.push(OriginGroup { origin: place.origin.clone(), server_device_id: place.server_device_id.clone(), databases: vec![place.id.clone()], }), } } groups } /// The address of another person's Mac, for the transport that talks to it. /// /// It knows no personal database and names no default one: nothing at this /// origin is Mine, so no request there is ever filed under Mine's id, and a /// request that forgets to name its database is refused by the server rather /// than answered from whichever file this side guessed. #[derive(Debug, Clone, PartialEq, Eq)] pub struct JoinedAddress { origin: String, } impl JoinedAddress { pub fn at(origin: &str) -> JoinedAddress { JoinedAddress { origin: origin.to_string(), } } } impl crate::transport::ServerAddress for JoinedAddress { fn base_url(&self) -> Option { Some(self.origin.clone()) } fn database(&self) -> Option { None } } /// Where the refusal note for one other origin is kept: its own file beside /// the connection record, never the household's `refusal.json`. pub fn refusal_note_path(connection_json: &Path, origin: &str) -> PathBuf { let digest = Sha256::digest(origin.as_bytes()); connection_json.with_file_name(format!("refusal-{}.json", hex::encode(&digest[..8]))) } /// How long the copy of a database this device was removed from waits in /// this device's Bin before it is purged with its media — a deleted /// database's rule. Only a new admission brings the database back, and that /// starts a fresh copy. pub const REMOVED_COPY_DAYS: i64 = cotton_store::database_bin::KEEP_DAYS; /// When a copy removed at `removed_at` is purged: [`REMOVED_COPY_DAYS`] on, /// in the same ISO-8601 UTC form. `None` for an instant that does not parse. pub fn purge_at(removed_at: &str) -> Option { let at = chrono::DateTime::parse_from_rfc3339(removed_at.trim()).ok()?; let purge = at.with_timezone(&chrono::Utc) + chrono::Duration::days(REMOVED_COPY_DAYS); Some(purge.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) } /// The entries of databases this device was removed from — its Bin's /// removed copies, in the order they were admitted. pub fn removed_copies(record: &ConnectionRecord) -> Vec<&PlaceEntry> { record .places .iter() .filter(|place| place.origin.is_some() && place.removed_at.is_some()) .collect() } /// What the app says over a database this device was removed from. pub fn removed_sentence(entry: &PlaceEntry) -> String { match entry.name.as_deref().map(str::trim).filter(|name| !name.is_empty()) { Some(name) => format!("You were removed from {name}"), None => "You were removed from this database".to_string(), } } #[cfg(test)] #[path = "joined_tests.rs"] mod tests;