//! Found a database on this device, using the shared birth rows and fold. //! //! The first device serves it and records epoch one in the same serving //! table a Mac uses. Engine-free tools work locally; the file is the phone's //! writable replica. No HTTP listener or Mac engine is started here. use std::path::PathBuf; use std::sync::Arc; use cotton_core::device::pairing::DevicePlatform; use cotton_store::birth::{seed_workspace_rows, WorkspaceSeed}; use cotton_store::driver::Driver; use cotton_store::meta::Meta; use cotton_tools::devices::{DeviceWrite, NewDeviceRow, SELF_APPROVER}; use crate::connection::{ConnectionFile, ConnectionMode, StoredConnection}; use crate::join::held_workspaces; use crate::layout::Layout; use crate::replica::{resolve_device_id, ReplicaError, CURSOR_DDL}; use crate::seams::{uuid_v4, Clock, Random}; /// The longest name a database may be given here. /// /// The server's bound on a name (`PATCH /v1/me`, 1..80), counted the way the /// server counts one — UTF-16 code units — so a name typed on this screen /// cannot become a 400 the first time it is pushed. pub const DATABASE_NAME_MAX: usize = 80; /// Why a device could not start a database. #[derive(Debug, thiserror::Error)] pub enum StartLocalError { #[error("No personal database in this flavour.")] NoPersonalInFlavour, /// This device already holds one. Never overwritten: a second start over a /// live file is somebody's week. #[error("{0}")] AlreadyStarted(String), #[error("a database's name is 1 to {DATABASE_NAME_MAX} characters")] BadName, #[error(transparent)] Replica(#[from] ReplicaError), #[error(transparent)] Store(#[from] cotton_store::StoreError), /// The file was made and the address could not be remembered. The file is /// deleted rather than left where nothing will look for it. #[error("this device could not remember the database it just started ({0})")] NotRemembered(String), /// A database is made BESIDE the personal one, and this device has none. #[error("this device has no personal database yet — start or join one first")] NoPersonal, #[error("“Personal” is your own database's name — give this one its own")] ReservedName, } impl StartLocalError { /// The word a caller answers with. pub fn code(&self) -> &'static str { match self { StartLocalError::NoPersonalInFlavour => cotton_core::genesis::NO_PERSONAL_DATABASE_IN_FLAVOUR, StartLocalError::AlreadyStarted(_) => "already_started", StartLocalError::BadName | StartLocalError::ReservedName => "bad_request", StartLocalError::NoPersonal => "no_personal_database", StartLocalError::Replica(_) | StartLocalError::Store(_) => "start_failed", StartLocalError::NotRemembered(_) => "no_server", } } } /// What one start is asked for. pub struct StartLocal<'a> { pub layout: &'a Layout, pub clock: &'a dyn Clock, pub random: &'a dyn Random, /// What the person called their database. `None` is "Personal". pub name: Option<&'a str>, /// This device's own key — the base64url Ed25519 public half a server would /// admit it under. /// /// `None` is a real state and not a failure: a device whose keychain was /// unavailable can still hold a database, and its row is written the first /// time a key exists. What it must never be is INVENTED here — a device row /// keyed by anything but the real key is a row no server will ever match. pub device_key_id: Option<&'a str>, /// What to call this device in the list. pub device_name: &'a str, pub platform: DevicePlatform, pub app_version: Option<&'a str>, /// The device key the new file's first writes are signed with (keys slice /// KS1), so its first author names the key and its seed rows are signed. /// An empty slot mints them unsigned. pub receipt_signer: cotton_store::signed::SignerSlot, } /// What a start left behind. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StartedLocal { pub workspace_id: String, pub owner_id: String, /// `device:` — the AUTHOR of every op this device writes, which is /// not the key a server admits. `replica::resolve_device_id` says why. pub author_device_id: String, /// The key the device list is keyed by, when this device had one. pub device_id: Option, pub replica: PathBuf, } /// Mint a database on this device and open on it. pub fn start_local(input: StartLocal<'_>) -> Result { let genesis = cotton_core::genesis::Genesis::at(input.layout.root()) .map_err(StartLocalError::NotRemembered)?; genesis.require_personal().map_err(|_| StartLocalError::NoPersonalInFlavour)?; let tools = cotton_core::genesis::GenesisTools::at(input.layout.root()) .map_err(StartLocalError::NotRemembered)?; let StartLocal { layout, clock, random, name, device_key_id, device_name, platform, app_version, receipt_signer, } = input; let name = match name.map(str::trim).filter(|value| !value.is_empty()) { Some(value) if value.encode_utf16().count() > DATABASE_NAME_MAX => { return Err(StartLocalError::BadName) } other => other, }; // ── 1. is there already a life here? ─────────────────────────────────── // // Two questions, because they fail apart: a connection record naming a // workspace is a device that has joined or started, and a replica with no // record is a start that was interrupted between the file and the write. // Neither is overwritten. // // Only MINE refuses a start. A place this device syncs is somebody else's // database, and its replica is one the record HAS an address for — so it // is neither a second life nor a stray one. let connection = ConnectionFile::at(layout.connection_json()); if let Some(stored) = connection.read() { if let Some(workspace_id) = stored.workspace_id { return Err(StartLocalError::AlreadyStarted(format!( "this device already holds {workspace_id} — starting a new database would make a \ second one" ))); } } let places: Vec = connection .read_record() .map(|record| record.places.into_iter().map(|place| place.id).collect()) .unwrap_or_default(); let stray = held_workspaces(layout, "") .into_iter() .find(|held| !places.contains(&held.workspace_id)); if let Some(held) = stray { return Err(StartLocalError::AlreadyStarted(format!( "this device already holds a database ({}) that nothing has an address for — leave it \ or erase it before starting another", held.workspace_id ))); } // ── 2. the two ids, minted and never derived ─────────────────────────── let workspace_id = uuid_v4(random); let owner_id = uuid_v4(random); let author_device_id = resolve_device_id(layout, clock, random)?; // ── 3. the file, at the ordinary client address ──────────────────────── let path = layout.replica(&workspace_id); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|error| { StartLocalError::NotRemembered(format!("{} ({error})", parent.display())) })?; } let at = clock.now(); let now = clock.now_iso(); let made = make_file( &path, receipt_signer, &Meta { workspace_id: workspace_id.clone(), owner_id: owner_id.clone(), device_id: author_device_id.clone(), last_server_seq: 0, last_hlc: None, }, &now, at.timestamp_millis(), name, &DeviceSeed { device_key_id, device_name, platform, app_version, now: &now, at, }, // The device bringing its FIRST database into existence serves it // until a Mac takes it over: there is no peer to push to. cotton_store::mint::Held::Served, "personal", &tools, &cotton_core::kit::AppKit::at(layout.root()).map_err(StartLocalError::NotRemembered)?.map(|kit| kit.tables).unwrap_or_default(), ); if let Err(error) = made { // NOTHING HALF-BORN IS LEFT BEHIND. A file at the replica's address // that nothing recorded would be read on the next launch as a life this // device is holding, and `held_workspaces` would refuse every later // start because of it. forget_unfinished(&path); return Err(error); } // ── 4. and ONLY now, the address ─────────────────────────────────────── // // Last, exactly as a join writes it last: the record is what makes the app // open on this file, and one naming a database that does not exist is a // phone that boots into nothing. connection .write(StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Local, // EMPTY, and the mode is what says so. A device that has started a // database alone has no server to talk to, and an address invented // here would be one every signed request went out against. base_url: String::new(), workspace_id: Some(workspace_id.clone()), owner_id: Some(owner_id.clone()), connected_at: Some(now.clone()), }) .map_err(|error| { forget_unfinished(&path); StartLocalError::NotRemembered(error.to_string()) })?; Ok(StartedLocal { workspace_id, owner_id, author_device_id, device_id: device_key_id.map(str::to_string), replica: path, }) } /// The personal database's name, reserved for it. pub const PERSONAL_NAME: &str = "Personal"; /// What making one database beside the personal one is asked for. pub struct StartPlace<'a> { pub layout: &'a Layout, /// The device's ONE connection record — the same object its transport /// writes listings through, so neither overwrites the other. pub connection: &'a ConnectionFile, pub clock: &'a dyn Clock, pub random: &'a dyn Random, pub name: &'a str, /// The device key every receipt this mint writes is signed by — the same /// slot a start is handed. pub receipt_signer: cotton_store::signed::SignerSlot, pub device_key_id: Option<&'a str>, pub device_name: &'a str, pub platform: DevicePlatform, pub app_version: Option<&'a str>, } /// A database made beside the personal one. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StartedPlace { pub id: String, pub name: String, pub replica: PathBuf, } /// MAKE A DATABASE ON THIS DEVICE, with no network. /// /// Every project is its own database from the day it is made, and the day it /// is made may be a day with no signal. So the file is minted here: its id, /// its own workspace row, its calendar and this device's row, all QUEUED — /// this device is a replica of a database its household's server will serve, /// and its first rows leave with the first exchange after the server takes /// the id (`connection::list::hand_over_made`). Until then the place is /// `pending`: held, readable and writable here, and in no exchange. /// /// The owner is the personal database's owner: a database beside Mine is the /// same person's. pub fn start_place(input: StartPlace<'_>) -> Result { let name = input.name.trim(); if name.is_empty() || name.encode_utf16().count() > DATABASE_NAME_MAX { return Err(StartLocalError::BadName); } if name.eq_ignore_ascii_case(PERSONAL_NAME) { return Err(StartLocalError::ReservedName); } let mine = input .connection .read() .filter(|mine| mine.workspace_id.is_some()) .ok_or(StartLocalError::NoPersonal)?; let owner_id = mine.owner_id.ok_or(StartLocalError::NoPersonal)?; let tools = cotton_core::genesis::GenesisTools::at(input.layout.root()) .map_err(StartLocalError::NotRemembered)?; let id = uuid_v4(input.random); let author_device_id = resolve_device_id(input.layout, input.clock, input.random)?; let path = input.layout.replica(&id); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|error| { StartLocalError::NotRemembered(format!("{} ({error})", parent.display())) })?; } let forget = |path: &std::path::Path| { forget_unfinished(path); }; let at = input.clock.now(); let now = input.clock.now_iso(); let made = make_file( &path, input.receipt_signer.clone(), &Meta { workspace_id: id.clone(), owner_id, device_id: author_device_id, last_server_seq: 0, last_hlc: None, }, &now, at.timestamp_millis(), Some(name), &DeviceSeed { device_key_id: input.device_key_id, device_name: input.device_name, platform: input.platform, app_version: input.app_version, now: &now, at, }, cotton_store::mint::Held::Replica, "shared", &tools, &[], ); if let Err(error) = made { forget(&path); return Err(error); } // The database is made with the shell and the app's genesis set (the // manifest's `tools`, architect 22 Oct 2026); any other tool is added by hand. // The record LAST, as a start writes it: an entry naming a file that does // not exist is a database that opens onto nothing. if let Err(error) = input.connection.add_made_place(&id, name, None) { forget(&path); return Err(StartLocalError::NotRemembered(error.to_string())); } Ok(StartedPlace { id, name: name.to_string(), replica: path, }) } /// The device row's half of a start. struct DeviceSeed<'a> { device_key_id: Option<&'a str>, device_name: &'a str, platform: DevicePlatform, app_version: Option<&'a str>, now: &'a str, at: chrono::DateTime, } /// Create the file, seed it, and write this device into its own device list. fn make_file( path: &std::path::Path, receipt_signer: cotton_store::signed::SignerSlot, meta: &Meta, now: &str, now_ms: i64, name: Option<&str>, device: &DeviceSeed<'_>, held: cotton_store::mint::Held, kind: &str, tools: &cotton_core::genesis::GenesisTools, kit_tables: &[String], ) -> Result<(), StartLocalError> { let db = Driver::open(path)?.sharing_signer(receipt_signer); cotton_store::create::create_workspace(&db, meta)?; // The device bringing the database into existence SERVES it until a Mac // takes it over; there is no peer to push to, so nothing is queued — a // peer that joins later pulls the whole stream. The same holding the // root device row below is written under. let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SystemRandom)); seed_workspace_rows( &db, now, now_ms, &WorkspaceSeed { workspace_id: &meta.workspace_id, owner_id: &meta.owner_id, name, kind, // A database a device makes on its own has no address yet; the // relay is chosen where a household is founded on a Mac // (`cotton_server::provision::provision_on_relay`). relay: None, }, &mut ids, held, )?; // The device-local cursor table, so a source that imports into this file // before it ever meets a server has somewhere to record where it got to. db.exec(CURSOR_DDL)?; if let Some(device_id) = device.device_key_id { // THE SAME WRITER A MAC'S APPROVAL USES. The row is minted as an op, // stamped with this file's own author, and handed to every later device // on the first exchange — which is what makes "who may open this // database" a fact of the database rather than of whichever machine // happened to be asked. // // `approved_by` is `self`, as the root row of a Mac's own database is: // nobody approved the first device, and `armed()` deliberately does not // count a self-approval, so a database with one device is still a // database whose next join needs a person to say yes. DeviceWrite { db: &db, workspace_id: &meta.workspace_id, owner_id: &meta.owner_id, now: device.at, random: Arc::new(cotton_tools::random::SystemRandom), } .insert(&NewDeviceRow { device_id: device_id.to_string(), workspace_id: meta.workspace_id.clone(), name: device.device_name.to_string(), platform: Some(device.platform), app_version: device.app_version.map(str::to_string), approved_at: device.now.to_string(), approved_by: SELF_APPROVER.to_string(), // A phone never dials the relay, so it publishes no relay identity. relay_identity_key: None, })?; } if held == cotton_store::mint::Held::Served { cotton_store::serving_handover::found(&db, &meta.workspace_id, &cotton_store::mint::Clock::wall(now_ms), &mut ids) .map_err(|error| cotton_store::StoreError::refused(error.to_string()))?; } // The shell — Home's board, the themes, the cap — and the app's genesis // set: every tool its manifest names, installed as ordinary data. cotton_tools::presentation::write_shell_for_a_copy(&db, device.at, Arc::new(cotton_tools::random::SystemRandom), held) .map_err(|failure| cotton_store::StoreError::refused(failure.0))?; cotton_tools::kit::install_genesis_tools(&db, device.at, Arc::new(cotton_tools::random::SystemRandom), held, tools) .map_err(|failure| cotton_store::StoreError::refused(failure.0))?; cotton_tools::kit_keep::stamp_fresh(&db, tools) .map_err(|failure| cotton_store::StoreError::refused(failure.0))?; // And the kit's own tables no tool carries (Sites' `site`, Post's `email_account`). // A refusal here never stops the birth: the next open lays what is missing (review of GENESIS KITS, 26 Nov 2026). if let Err(failure) = cotton_tools::kit::lay_kit_tables(&db, device.at, Arc::new(cotton_tools::random::SystemRandom), Some(held), kit_tables) { eprintln!("[kit] the kit's own tables were not laid at birth; the next open tries again: {}", failure.0); } Ok(()) } #[cfg(test)] #[path = "start_tests.rs"] mod tests; /// A database a start made and could not finish leaves through the one function (anything in it that is unsent keeps /// it aside), and its folder goes only if nothing is left in it. pub(crate) fn forget_unfinished(path: &std::path::Path) { let _ = crate::copy_keep::retire_at(path, crate::copy_keep::Ending::keep("a database this start made and could not finish")); if let Some(parent) = path.parent() { // not a copy: an empty folder only: remove_dir refuses one that holds anything. let _ = std::fs::remove_dir(parent); } }