//! `cotton_serving_machine` — which machine serves this database, epoch by //! epoch. //! //! INSERT-ONLY. A hand-over never edits the row before it: it writes the next //! epoch, and the HIGHEST epoch is the machine that serves now. Every earlier //! row stays as the record of who served when, under which author, with which //! relay key and which backup access key — which is what makes a key an older //! fact recorded a key nobody may use again. //! //! **This is the one reader of the table.** The backup gate asks it "may this //! machine back up", and every later slice that needs "who serves" asks it //! too: two readers of one fact are two answers the day one of them orders the //! rows differently. //! //! Nothing here writes. The hand-over that mints a row is its own slice; the //! heard epoch beside the facts is written by the exchange, as it takes an //! answer (`exchange::fold_answer`). use rusqlite::types::Value as SqlValue; use crate::driver::Driver; use crate::error::Result; /// One epoch's row: the machine that serves from `since`, and what it serves /// under. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ServingFact { pub id: String, pub epoch: i64, /// The serving machine, named by the id its device credential carries — /// the same id `cotton_devices.device_id` holds. pub device_credential_id: String, pub author_id: String, pub relay_key: Option, /// The bucket access key this epoch took for itself; `None` on a planned /// switch, which backs up with the household's key as it stands. A key is /// retired the moment a newer epoch records one ([`retired_backup_access_keys`]). pub backup_access_key_id: Option, pub since: String, pub confirmed_by: Option, } /// The latest fact (highest epoch), or `None` when the file holds no fact. /// /// A tie on the epoch is two machines that each wrote "I serve epoch N" — /// a fork the hand-over exists to prevent, but a reader still has to give ONE /// answer to it, and the same one on every machine. The tie breaks on `id`, /// descending: a stable column every copy of the file holds identically, /// rather than insertion order, which a copy does not keep. pub fn serving_fact(db: &Driver, workspace_id: &str) -> Result> { let row = db.get( "SELECT id, epoch, device_credential_id, author_id, relay_key, backup_access_key_id, \ since, confirmed_by \ FROM cotton_serving_machine \ WHERE workspace_id = ? \ ORDER BY epoch DESC, id DESC \ LIMIT 1", &[text(workspace_id)], )?; Ok(row.as_ref().map(fact_of)) } /// The fact of one `epoch` (the tie broken as [`serving_fact`] breaks it), /// or `None` when the file holds none at that epoch. pub fn fact_at(db: &Driver, workspace_id: &str, epoch: i64) -> Result> { let row = db.get( "SELECT id, epoch, device_credential_id, author_id, relay_key, backup_access_key_id, \ since, confirmed_by \ FROM cotton_serving_machine \ WHERE workspace_id = ? AND epoch = ? \ ORDER BY id DESC \ LIMIT 1", &[text(workspace_id), rusqlite::types::Value::Integer(epoch)], )?; Ok(row.as_ref().map(fact_of)) } /// The newest serving epoch this file has heard of: the higher of its latest /// fact's epoch and `_meta.heard_serving_epoch`, the newest epoch an answer /// has named to it. `None` when it has heard of neither. /// /// Both, because they arrive apart: the first answer from a Mac that took /// over names its epoch before that epoch's fact has reached this file, and a /// fact can arrive in an answer that named no epoch. Every question "is this /// answer an old Mac's" and "has this replica handed over to the Mac serving /// now" reads this one number. pub fn heard_epoch(db: &Driver, workspace_id: &str) -> Result> { let fact = serving_fact(db, workspace_id)?.map(|fact| fact.epoch); let heard = db .get("SELECT heard_serving_epoch FROM _meta", &[])? .and_then(|row| row.int("heard_serving_epoch")); Ok(fact.max(heard)) } /// THE RESTORE POINT of the latest epoch (slice 12): `start_positions.positions` /// off the latest fact, `{author: stamp}` — what every answer of the epoch /// carries as `restored`. `None` when the file holds no fact or the latest one /// froze none (an epoch that began without a take-over). /// /// The column's shape is the act's (`{"positions": {author: stamp}, /// "skipped": [...]}`); a column of any other shape is refused, not read as /// "no restore point" — a device would then hand over from `seen`. pub fn restored( db: &Driver, workspace_id: &str, ) -> Result>> { let Some(fact) = serving_fact(db, workspace_id)? else { return Ok(None); }; let Some(frozen) = db .get( "SELECT start_positions FROM cotton_serving_machine WHERE id = ?", &[text(&fact.id)], )? .and_then(|row| row.text("start_positions").map(str::to_string)) else { return Ok(None); }; let unreadable = || { crate::error::StoreError::encode(format!( "serving fact {} has start_positions without a {{author: stamp}} `positions` map", fact.id )) }; let parsed: serde_json::Value = serde_json::from_str(&frozen).map_err(|_| unreadable())?; let positions = parsed .get("positions") .and_then(serde_json::Value::as_object) .ok_or_else(unreadable)?; positions .iter() .map(|(author, stamp)| { stamp .as_str() .map(|stamp| (author.clone(), stamp.to_string())) .ok_or_else(unreadable) }) .collect::>() .map(Some) } /// The Mac whose serving fact records `device` as a SKIPPED claimant /// (slice 12, V11-2: `start_positions.skipped[].device`), or `None`. The /// lowest epoch's fact answers when several do. A column of any shape but the /// act's is refused, as [`restored`] refuses it. pub fn skipped_by(db: &Driver, device: &str) -> Result> { Ok(claimants(db, Some(device))? .into_iter() .find(|claimant| claimant.device == device) .map(|claimant| claimant.by)) } /// Every skipped claimant any serving fact records, each with the Mac whose /// fact records it — once, by the lowest epoch's fact, as [`skipped_by`] /// answers it. pub fn skipped_claimants(db: &Driver) -> Result> { let mut seen = std::collections::BTreeSet::new(); Ok(claimants(db, None)? .into_iter() .filter(|claimant| seen.insert(claimant.device.clone())) .collect()) } /// A key a serving fact records as skipped (`device`), and that fact's Mac /// (`by`), with that fact's epoch and `since`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SkippedClaimant { pub device: String, pub by: String, pub epoch: i64, pub since: String, } /// Every `skipped` entry, in epoch order — of the facts whose column mentions /// `needle` at all, when one is given. fn claimants(db: &Driver, needle: Option<&str>) -> Result> { let needle = needle.map_or(SqlValue::Null, text); let rows = db.all( "SELECT id, epoch, since, device_credential_id, start_positions FROM cotton_serving_machine \ WHERE start_positions IS NOT NULL AND (? IS NULL OR instr(start_positions, ?) > 0) \ ORDER BY epoch ASC, id ASC", &[needle.clone(), needle], )?; let mut out = Vec::new(); for row in &rows { let id = row.text("id").unwrap_or_default(); let unreadable = || { crate::error::StoreError::encode(format!( "serving fact {id} has start_positions whose `skipped` is not a list of {{epoch, device}}" )) }; let parsed: serde_json::Value = serde_json::from_str(row.text("start_positions").unwrap_or_default()).map_err(|_| unreadable())?; let Some(skipped) = parsed.get("skipped") else { continue; }; let skipped = skipped.as_array().ok_or_else(unreadable)?; for claimant in skipped { let named = claimant.get("device").and_then(serde_json::Value::as_str).ok_or_else(unreadable)?; out.push(SkippedClaimant { device: named.to_string(), by: row.text("device_credential_id").unwrap_or_default().to_string(), epoch: row.int("epoch").unwrap_or_default(), since: row.text("since").unwrap_or_default().to_string(), }); } } Ok(out) } /// THE OLD-AUTHOR CUT-OFF (slice 12): why a receipt by `author` stamped /// `stamp` is not applied here, or `None` when it is judged like any other. /// /// An old author is an author whose fact names a device a serving fact names, /// at an epoch a later fact ended: that Mac stopped serving at the later /// epoch's `since` — the take-over act's committed stamp — and nothing it /// wrote after that is the household's. The cut-off is the `since` of the /// first epoch above the device's highest; a receipt whose stamp's /// millisecond is above it is past it, one at or below it is not. A device /// the latest fact names has no cut-off. /// /// A SKIPPED CLAIMANT's author (V11-2 (b)) is judged like any old author's: /// its device is named by no serving fact, only in a later fact's `skipped`, /// and its cut-off is that fact's `since` — the claimant never served past it. pub fn past_the_cut_off(db: &Driver, author: &str, stamp: &str) -> Result> { let (since, epoch, formerly_served) = match db.get( "SELECT later.since AS since, later.epoch AS epoch FROM cotton_authors a \ JOIN cotton_serving_machine old ON old.device_credential_id = a.device_id \ JOIN cotton_serving_machine later \ ON later.workspace_id = old.workspace_id AND later.epoch > old.epoch \ WHERE a.id = ? \ AND old.epoch = (SELECT MAX(epoch) FROM cotton_serving_machine \ WHERE workspace_id = old.workspace_id \ AND device_credential_id = a.device_id) \ ORDER BY later.epoch ASC, later.id ASC LIMIT 1", &[text(author)], )? { Some(row) => ( row.text("since").unwrap_or_default().to_string(), row.int("epoch").unwrap_or_default(), true, ), None => { let device = db .get("SELECT device_id FROM cotton_authors WHERE id = ?", &[text(author)])? .and_then(|row| row.text("device_id").map(str::to_string)); let Some(device) = device else { return Ok(None); }; let Some(claimant) = claimants(db, Some(&device))? .into_iter() .find(|claimant| claimant.device == device) else { return Ok(None); }; (claimant.since, claimant.epoch, false) } }; let Some(since_ms) = crate::protocol::js::parse_date_ms(&since) else { return Err(crate::error::StoreError::encode(format!( "serving fact of epoch {epoch} has a since that is no time: {since}" ))); }; let stamped_ms = crate::protocol::hlc::hlc_parts(stamp)?.ms; if stamped_ms <= since_ms { return Ok(None); } // A former server remains an admitted device. Its new client stream // starts after the grant, unlike its ended serving stream. Preserve its // edits while still refusing writes under the old serving author. if formerly_served && !is_serving_author(db, author)? { if let Some(first) = db.get("SELECT first_stamp FROM cotton_authors WHERE id = ?", &[text(author)])? .and_then(|row| row.text("first_stamp").map(str::to_string)) { if crate::protocol::hlc::hlc_parts(&first)?.ms > since_ms { return Ok(None); } } } Ok(Some(format!( "written by a Mac that no longer serves: its author's Mac stopped serving at {since}, \ when epoch {epoch} began, and this write is stamped after that" ))) } /// THE SERVING AUTHORS of one epoch: the authors its Mac wrote under while it /// served that epoch, and so the authors that act for the devices asking it. /// /// The fact's own `author_id` — the author the Mac took over under, or, at /// epoch 1, the author the file was born under (minted before `since`) — and /// every author of the fact's device minted while it served: reason /// `take-over`, `redate` or `keys`, at or after `since` and before the `since` /// of the first epoch above this one. That Mac's author from its CLIENT days /// (reason `first`, or minted outside the window) is not one: its writes were /// a client's. /// /// The one definition: the serving Mac's push screen asks it of the latest /// fact (`cotton_server::sync::serving_screen::judge_authors`), and the fold /// asks it of every fact ([`is_serving_author`]), so the two never disagree. pub fn serving_authors( db: &Driver, fact: &ServingFact, ) -> Result> { let mut authors = std::collections::BTreeSet::new(); if !fact.author_id.is_empty() { authors.insert(fact.author_id.clone()); } let ended = db .get( "SELECT since FROM cotton_serving_machine \ WHERE workspace_id = (SELECT workspace_id FROM cotton_serving_machine WHERE id = ?) \ AND epoch > ? \ ORDER BY epoch ASC, id ASC LIMIT 1", &[text(&fact.id), SqlValue::Integer(fact.epoch)], )? .and_then(|row| row.text("since").map(str::to_string)); for row in db.all( &format!( "SELECT id FROM cotton_authors \ WHERE device_id = ? AND reason IN {SERVING_REASONS} AND minted_at >= ? \ AND (? IS NULL OR minted_at < ?)" ), &[ text(&fact.device_credential_id), text(&fact.since), ended.as_deref().map_or(SqlValue::Null, text), ended.as_deref().map_or(SqlValue::Null, text), ], )? { if let Some(id) = row.text("id") { authors.insert(id.to_string()); } } Ok(authors) } /// Whether `author` is a serving author of ANY epoch this file holds a fact /// for ([`serving_authors`]) — a receipt it wrote may name the owner or a /// member of another device than its own, because a serving Mac writes for the /// devices that ask it. A file with no fact has no serving author. An older /// epoch's author is bounded by [`past_the_cut_off`], which parks what it /// wrote after it stopped serving. pub fn is_serving_author(db: &Driver, author: &str) -> Result { for fact in facts(db)? { if serving_authors(db, &fact)?.contains(author) { return Ok(true); } } Ok(false) } /// The author reasons a serving Mac mints under while it serves /// ([`serving_authors`]), as an SQL list. const SERVING_REASONS: &str = "('take-over','redate','keys')"; /// Whether `author`, which is no serving author here ([`is_serving_author`]), /// is WAITING for the serving fact that would make it one: its reason is a /// serving reason, and no serving fact this file holds names its device at /// all — that Mac's fact has not arrived (pull pages hand authors out in /// rounds, so a token can land before it). Once a fact naming its device is /// held and the author is still outside every window, it is `false`: the /// receipt is refused and parks `conflict`. An author with no fact here, or /// minted as a client (`first`), is `false`. pub fn awaits_a_serving_fact(db: &Driver, author: &str) -> Result { Ok(db .get( &format!( "SELECT 1 AS waits FROM cotton_authors a \ WHERE a.id = ? AND a.reason IN {SERVING_REASONS} \ AND NOT EXISTS (SELECT 1 FROM cotton_serving_machine f \ WHERE f.device_credential_id = a.device_id)" ), &[text(author)], )? .is_some()) } /// The authors a serving fact this file just took makes serving authors /// ([`serving_authors`] of the row `id`) — whoever parked receipts of theirs /// waiting for it offers them again now. Empty for an id that is no fact. pub fn announced_by_fact(db: &Driver, id: &str) -> Result> { let Some(row) = db.get( "SELECT id, epoch, device_credential_id, author_id, relay_key, backup_access_key_id, \ since, confirmed_by \ FROM cotton_serving_machine WHERE id = ?", &[text(id)], )? else { return Ok(Vec::new()); }; Ok(serving_authors(db, &fact_of(&row))?.into_iter().collect()) } /// The serving authors of epoch `epoch` of `workspace_id` — every fact this /// file holds for that epoch, each by [`serving_authors`] — or `None` when it /// holds no fact of that epoch yet. A kept relay key is taken only from one /// of these (`fact_hooks`, `cotton_device_relay_keys`). pub fn authors_of_epoch( db: &Driver, workspace_id: &str, epoch: i64, ) -> Result>> { let held: Vec = db .all( "SELECT id, epoch, device_credential_id, author_id, relay_key, backup_access_key_id, \ since, confirmed_by \ FROM cotton_serving_machine WHERE workspace_id = ? AND epoch = ? ORDER BY id ASC", &[text(workspace_id), SqlValue::Integer(epoch)], )? .iter() .map(fact_of) .collect(); if held.is_empty() { return Ok(None); } let mut authors = std::collections::BTreeSet::new(); for fact in &held { authors.extend(serving_authors(db, fact)?); } Ok(Some(authors)) } /// Every fact this file holds, in epoch order. fn facts(db: &Driver) -> Result> { Ok(db .all( "SELECT id, epoch, device_credential_id, author_id, relay_key, backup_access_key_id, \ since, confirmed_by \ FROM cotton_serving_machine ORDER BY epoch ASC, id ASC", &[], )? .iter() .map(fact_of) .collect()) } fn fact_of(row: &crate::driver::Row) -> ServingFact { ServingFact { id: row.text("id").unwrap_or_default().to_string(), epoch: row.int("epoch").unwrap_or_default(), device_credential_id: row .text("device_credential_id") .unwrap_or_default() .to_string(), author_id: row.text("author_id").unwrap_or_default().to_string(), relay_key: row.text("relay_key").map(str::to_string), backup_access_key_id: row.text("backup_access_key_id").map(str::to_string), since: row.text("since").unwrap_or_default().to_string(), confirmed_by: row.text("confirmed_by").map(str::to_string), } } /// The latest fact, when it names a machine OTHER than `this_device`. /// /// The one question a client Mac's gates ask — may this Mac serve the file, /// run peer sync or the replicate pull, hold the household's TLS key. `None` /// is "no fact" or "the fact names this machine": both admit. A machine with /// no device id cannot be the one a fact names. pub fn served_elsewhere( db: &Driver, workspace_id: &str, this_device: Option<&str>, ) -> Result> { Ok(serving_fact(db, workspace_id)? .filter(|fact| this_device != Some(fact.device_credential_id.as_str()))) } /// Every backup access key id recorded BELOW THE NEWEST FACT THAT RECORDS A /// KEY — non-null, distinct, sorted. /// /// A fact that records a key is a machine that took a key of its own: the /// founder, or a take-over, whose owner typed a new pair. Everything recorded /// below it is retired — the machines before it may still hold those keys. /// A fact that records NO key is a move of serving between two machines of /// one household by the owner's grant (`serving_grant::commit`): nobody was /// revoked, the household's one /// pair is sealed in its vault for whichever Mac serves, so that fact retires /// nothing and the key below it stands. What keeps the Mac that stood down /// out of the bucket is the fact itself — the backup gate refuses a machine /// the newest fact does not name before it ever asks about the key. /// /// "Below" is read off the epoch, not off "every row but that one": a key an /// older fact recorded is retired EVEN WHEN the newest key-recording fact /// records the same key again. A machine that served before, was taken over /// and was handed back must mint a new key — the old one is in the hands of /// whoever held it in between, and that machine refusing to start is the only /// thing standing between two writers and one prefix. /// /// A tie at that epoch retires nobody's key: both rows are AT it, and which /// of them [`serving_fact`] answers with is a tie-break, not a hand-over. pub fn retired_backup_access_keys(db: &Driver, workspace_id: &str) -> Result> { let rows = db.all( "SELECT DISTINCT backup_access_key_id AS key \ FROM cotton_serving_machine \ WHERE workspace_id = ? \ AND backup_access_key_id IS NOT NULL \ AND epoch < (SELECT MAX(epoch) FROM cotton_serving_machine \ WHERE workspace_id = ? AND backup_access_key_id IS NOT NULL) \ ORDER BY backup_access_key_id", &[text(workspace_id), text(workspace_id)], )?; Ok(rows .iter() .filter_map(|row| row.text("key").map(str::to_string)) .collect()) } fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } #[cfg(test)] #[path = "serving_tests.rs"] mod serving_tests;