//! Database deletion policy shared by the serving Mac and every retained copy. //! Returns facts; the database definition supplies the person's words. use crate::{membership, Driver, Result}; use chrono::{DateTime, TimeDelta, Utc}; use rusqlite::types::Value; pub const KEEP_DAYS: i64 = 30; #[derive(Debug, Clone, PartialEq, Eq)] pub enum DeleteRefusal { Unknown, Personal, NotCreator, Members { count: usize }, } /// Evaluate under the same writer hold as the deletion: an admission must /// not slip between this check and the lifecycle write. The earliest owner /// admission is the creator, never the owner of the household serving it. pub fn may_delete( db: &Driver, database: &str, person: &str, ) -> Result> { let kind = db .get( "SELECT kind FROM cotton_workspaces WHERE id=?", &[Value::Text(database.into())], )? .and_then(|row| row.text("kind").map(str::to_string)); match kind.as_deref() { Some("personal") => return Ok(Err(DeleteRefusal::Personal)), Some("shared") => {} _ => return Ok(Err(DeleteRefusal::Unknown)), } if membership::birth_owner(db)?.as_deref() != Some(person) { return Ok(Err(DeleteRefusal::NotCreator)); } let mut count = 0; for row in db.all( "SELECT DISTINCT person_key FROM cotton_admissions WHERE workspace_id=? AND person_key<>?", &[Value::Text(database.into()), Value::Text(person.into())], )? { if let Some(key) = row.text("person_key") { if membership::of(db, key)?.is_some() { count += 1; } } } Ok(if count == 0 { Ok(()) } else { Err(DeleteRefusal::Members { count }) }) } /// A bad date, a clock behind the deletion, or an overflowing deadline never /// authorises erasure. Used for creator deletions and removed members alike. pub fn purge_due(deleted_at: &str, now: DateTime) -> bool { deadline(deleted_at).is_some_and(|deadline| now >= deadline) } /// The moment a binned copy is erased: thirty days after it was binned. The /// Bin's row says it ("kept until"); nothing else reads the copy to say so. pub fn kept_until(deleted_at: &str) -> Option { deadline(deleted_at).map(|deadline| deadline.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) } fn deadline(deleted_at: &str) -> Option> { DateTime::parse_from_rfc3339(deleted_at) .ok() .and_then(|at| at.checked_add_signed(TimeDelta::days(KEEP_DAYS))) .map(|deadline| deadline.with_timezone(&Utc)) } #[cfg(test)] mod tests { use super::*; /// RULE: Every database copy is kept for thirty full days; invalid, future or overflowing dates cannot shorten retention and erase recoverable data. #[test] fn retention_is_thirty_full_days() { let now = DateTime::parse_from_rfc3339("2026-10-31T00:00:00Z") .unwrap() .to_utc(); assert!(purge_due("2026-10-01T00:00:00Z", now)); assert!(!purge_due("2026-10-01T00:00:00.001Z", now)); assert!(!purge_due("2026-11-01T00:00:00Z", now)); assert!(!purge_due("broken", now)); assert!(!purge_due("+262142-12-31T23:59:59Z", now)); } } /// One purge implementation for the serving Bin and removed device copies. /// The caller owns this database folder and has excluded concurrent opens. pub fn purge_folder( path: &std::path::Path, deleted_at: &str, now: DateTime, ) -> std::io::Result { if !purge_due(deleted_at, now) { return Ok(false); } remove_folder(path)?; Ok(true) } /// Remove one database folder whatever its age — for a copy a new admission /// replaces at once. Never follows a symbolic link; a missing folder is gone. pub fn remove_folder(path: &std::path::Path) -> std::io::Result<()> { match std::fs::symlink_metadata(path) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(error) => Err(error), Ok(meta) if meta.file_type().is_symlink() => Err(std::io::Error::other( "A database purge folder cannot be a symbolic link", )), // not a copy: a binned database's folder on the serving Mac, or a phone database's media; a phone copy's own // folder reaches the bin only through `cotton_client::copy_keep` (QUEUE BAD OP 4). Ok(_) => std::fs::remove_dir_all(path), } }