//! The two rows a brand-new file needs before anything can be written into it. //! //! `create::create_workspace` seeds `_meta` — who this file belongs to — and //! stops there. A file at that point is not yet USABLE: every domain table keys //! back to `cotton_workspaces`, so the first todo written into it fails a //! foreign key, and with no calendar the first event has nowhere to file into. //! //! **This lives in the store because it is a fact of the FILE, not of the //! server.** It used to live in `cotton-server`'s `provision.rs`, which was //! right while a server was the only thing that could bring a workspace into //! existence. A phone that starts a database on its own //! (`cotton_client::start_local`) brings one into existence too, and it links //! no server — so the alternative to moving it here was a second function //! writing the same two rows, which is the one thing this repo says no to //! ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]). //! //! **Each row is asked for separately**, and that is the whole of //! [`seed_workspace_rows`]. One guard standing for two rows assumes the only //! way to hold a workspace row is to have run this, and that is false in both //! directions: an ADOPTED file arrives with a workspace row and whatever else //! its old life had, and a fixture may write its own before anything seeds it. //! Either way the calendar never lands, and the symptom is a long way from the //! cause — the calendar screen says "Couldn't load this day" for ever. //! //! **Written as STAMPED ops**, through [`crate::mint::mint`], with the //! op ids DERIVED from the workspace and the row: a seed that ran twice over a //! file that kept one of the two rows cannot mint a second op id for the row it //! re-writes. use serde_json::json; use crate::driver::Driver; use crate::error::Result; use crate::actor::{Actor, JobName}; use crate::mint::{changes_of, mint, Act, Held, History}; use crate::outbox::{IdSource, LocalChange}; use crate::protocol::types::OpKind; use rusqlite::types::Value as SqlValue; /// What a workspace's first two rows say. pub struct WorkspaceSeed<'a> { pub workspace_id: &'a str, pub owner_id: &'a str, /// `None` means "Personal" — the placeholder a `POST /v1/me` reports as /// null. pub name: Option<&'a str>, /// `personal` for the owner's own database, `shared` for one made beside /// it. Set once, here, and never changed after. pub kind: &'a str, /// The household's own relay — `(relay_domain, relay_tunnel_host)` — or /// `None` for Cotton's, which is what every household that never chose /// gets and what the row then holds as two NULLs. /// /// A pair, so half an address cannot be asked for; and HERE, because here /// is the only moment the two columns can be written at all /// (`fold::IDENTITY_WRITE_ONCE`: a change naming them is refused at mint /// and on every device). The caller has checked they are hostnames /// (`cotton_core::relay_address::RelayAddress::new`); this crate does not /// know what a hostname is. pub relay: Option<(&'a str, &'a str)>, } /// The workspace row and the default calendar, each asked for on its own. /// /// `now` is the ISO instant the rows carry, `now_ms` the one their stamps are /// minted from — two spellings of one moment, taken from the caller because /// this crate reaches for no clock. pub fn seed_workspace_rows( db: &Driver, now: &str, now_ms: i64, seed: &WorkspaceSeed<'_>, ids: &mut dyn IdSource, held: Held, ) -> Result<()> { seed_rows(db, now, now_ms, seed, ids, held, true) } /// The workspace row ALONE — what a server writes when it takes a database a /// device made offline. Everything else in that database's life (its /// calendar, its first records) is the device's and arrives with its /// exchange; the workspace row is written here because every other row a /// server must write to make the file reachable — its devices, its vault — /// hangs off it. Its id is the database's id, so the device's own copy of the /// row and this one are one row. pub fn seed_workspace_row( db: &Driver, now: &str, now_ms: i64, seed: &WorkspaceSeed<'_>, ids: &mut dyn IdSource, held: Held, ) -> Result<()> { seed_rows(db, now, now_ms, seed, ids, held, false) } fn seed_rows( db: &Driver, now: &str, now_ms: i64, seed: &WorkspaceSeed<'_>, ids: &mut dyn IdSource, held: Held, calendar: bool, ) -> Result<()> { let workspace = || SqlValue::Text(seed.workspace_id.to_string()); let mut seeded: Vec = Vec::new(); if db .get( "SELECT id FROM cotton_workspaces WHERE id = ?", &[workspace()], )? .is_none() { let mut patch = json!({ "id": seed.workspace_id, "name": seed.name.unwrap_or("Personal"), "owner_user_id": seed.owner_id, "created_at": now, // A file this seeds is the owner's own: Mine, whose derived // ids are made in its own id. Set once, here, and never // changed after (`link_rule::no_identity_change`). "kind": seed.kind, "namespace": seed.workspace_id, }) .as_object() .expect("an object") .clone(); // The household's own relay, in the row's birth and nowhere after it. // Left out entirely for Cotton's, so that row is the same row it // always was. if let Some((domain, tunnel)) = seed.relay { patch.insert("relay_domain".to_string(), json!(domain)); patch.insert("relay_tunnel_host".to_string(), json!(tunnel)); } seeded.push(LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_workspaces".to_string(), row_id: seed.workspace_id.to_string(), patch: Some(patch), }); } // One default calendar, or the first `create_event` has nowhere to file // into. Asked for by KIND rather than by id, because the id is derived from // the workspace and the clock — so a second call a second later would mint // a different one and give the file two "Personal" calendars. if calendar && db .get( "SELECT id FROM cotton_collections WHERE workspace_id = ? AND kind = 'calendar' AND archived_at IS NULL", &[workspace()], )? .is_none() { let id = default_calendar_id(seed.workspace_id, now); seeded.push(LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_collections".to_string(), row_id: id.clone(), patch: Some( json!({ "id": id, "workspace_id": seed.workspace_id, "kind": "calendar", "name": "Personal", "is_default": true, "sort_key": "0", "created_at": now, }) .as_object() .expect("an object") .clone(), ), }); } if seeded.is_empty() { return Ok(()); } // The device bringing the workspace into existence is the one writing, so // this is also the file's first mint: its author and author fact land // first (see `mint`). The op ids were once derived from the row so a second // seed could not queue a second copy; the row checks above already make a // second seed write nothing, so a fresh ulid per op is the right id. // Judged on the serving Mac's file, the wall clock on any other handle. let clock = crate::mint::clock::writer_clock(db, now_ms, &mut *ids)?; mint( db, &Act { actor: Actor::DeviceJob(JobName::named("birth")?), verb: "seed_workspace_rows".to_string(), history: History::None, changes: changes_of(db, &seeded), }, &clock, ids, held, )?; Ok(()) } /// The default calendar's id: a uuid-shaped string DERIVED from the workspace /// and the moment, so seeding the same file twice cannot mint two calendars /// that differ only in entropy. fn default_calendar_id(workspace_id: &str, now: &str) -> String { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(format!("cotton-default-calendar/{workspace_id}/{now}").as_bytes()); let hex = hex::encode(hasher.finalize()); format!( "{}-{}-4{}-8{}-{}", &hex[0..8], &hex[8..12], &hex[13..16], &hex[17..20], &hex[20..32] ) } #[cfg(test)] #[path = "birth_tests.rs"] mod tests;