//! One way for a handler's edit to become a change every device pulls.//!//! In the shape design S6 gives it: the `pgrest` query-builder layer is//! DROPPED (design S2), so a handler collects [`LocalChange`]s — the store's//! own shape — and `commit` hands them to [`cotton_store::mint::mint`], the//! ONE place changes are made (slice 2a). The clock seeded from the file, the//! stale skip that is an error rather than a shrug, the fold as the one//! chokepoint, the author the ops are stamped with, the outbox a replica//! queues into: all of that is `mint`'s now and is written once, there. What//! stays here is the collection, the `workspace_id` every row carries, and//! the ACTOR the write is asked by.//!//! **The actor.** A `Writer` is built for an [`Actor`] — the token, credential,//! device, job or session the write is asked from — and how this process holds//! the file ([`Held`]). [`Writer::acting`] is the only door: no site names an//! author, because the file has one (slice 2b; the guard//! `no_server_author_constant_remains`).use std::sync::Arc;use chrono::{DateTime, Utc};use cotton_store::actor::{Actor, JobName};use cotton_store::driver::Driver;use cotton_store::mint::clock::writer_clock;use cotton_store::mint::{changes_of, mint_undo, Act, Held, History};use cotton_store::outbox::LocalChange;use cotton_store::protocol::types::CottonOp;use cotton_store::protocol::ulid::Monotonic;use cotton_store::Result;use serde_json::{Map, Value};usecrate::random::Random;/// The actor a job of the serving Mac writes as: `job:<name>`. The name is a/// word written in code, so a name that is not one is a mistake in the source/// and stops the process that carries it, at the first write.pubfn job(name: &'static str) -> Actor {Actor::Job(JobName::named(name).unwrap_or_else(|error| panic!("`{name}` is not a job name: {error}")), )}/// Collects changes, then mints and folds them in one transaction.////// The ops are the same shape a device push carries, which is the point: an/// assistant's edit is a first-class change every device pulls, not a side-door/// write only the server can see.pubstructWriter<'a> { driver: &'a Driver, workspace_id: String, owner_user_id: String, actor: Actor, held: Held,/// What the write is called in a refusal — the tool or route, when the/// caller says; `write` when it does not. verb: String, now: DateTime<Utc>, random: Arc<dynRandom>, changes: Vec<LocalChange>,/// Every op this writer has folded, in order. ops: Vec<CottonOp>,/// The undo fact the next commit's act names ([`Writer::undoing`]). undo: Option<String>,/// How many generic verbs are running whose own change row is the/// action's history ([`Writer::noting_history`]); while any is, the acts/// committed under them keep none of their own. noted: u32,/// The physical table whose next record created here is held for the/// owner alone ([`Writer::holding_next_create`]), until a commit mints it. hold: Option<String>,}impl<'a> Writer<'a> {/// A writer for an actor, on a file held this way.pubfn acting( driver: &'a Driver, workspace_id: &str, owner_user_id: &str, actor: Actor, held: Held, now: DateTime<Utc>, random: Arc<dynRandom>, ) -> Writer<'a> {Writer { driver, workspace_id: workspace_id.to_string(), owner_user_id: owner_user_id.to_string(), actor, held, verb: "write".to_string(), now, random, changes: Vec::new(), ops: Vec::new(), undo: None, noted: 0, hold: None, } }/// The same writer, on a file held `held` — a replica's install writes/// held, as every replica write is. #[must_use]pubfn held_as(mutself, held: Held) -> Writer<'a> {self.held = held;self }/// Name the write, for its refusals. #[must_use]pubfn about(mutself, verb: &str) -> Writer<'a> {self.verb = verb.to_string();self }pubfn workspace_id(&self) -> &str { &self.workspace_id }pubfn owner_user_id(&self) -> &str { &self.owner_user_id }/// Who the write is asked by.pubfn actor(&self) -> &Actor { &self.actor }/// How this process holds the file the write lands in.pubfn held(&self) -> Held {self.held }pubfn now(&self) -> DateTime<Utc> {self.now }pubfn upsert(&mutself, table: &str, row_id: &str, patch: Map<String, Value>) {self.changes.push(LocalChange::upsert(table, row_id, patch)); }/// A message the disappearing timer put in the Bin, out of the Bin again by any path but the timer's own put-back/// (an undo, an assistant, a restore from the Bin, a restore that came by pull and is written here next): it is/// his now, and the timer never takes it again (ABSENCE 5 item 4, ABSENCE 6 H1). Decided by the row as it will/// stand: out of the Bin with `timer_binned` still on it. Only the timer's own put-back writes `timer_back` (and/// no `timer_binned`): it passes, the mark taken off so no row and no undo ever carries it. Anything else that/// unbins, even an undo whose meta is from before the bin, is his (ABSENCE 7, item 4).fn timer_kept(&self, table: &str, row_id: &str, mut patch: Map<String, Value>) -> Map<String, Value> {if table != "cotton_msg_messages" {return patch; }letOk(Some(row)) = self.driver.get("SELECT meta, trashed_at FROM cotton_msg_messages WHERE id = ? AND json_extract(meta, '$.cotton.timer_binned') IS NOT NULL", &[rusqlite::types::Value::Text(row_id.to_string())]) else {return patch; };let binned_after = match patch.get("trashed_at") {Some(value) => !value.is_null(),None => row.text("trashed_at").is_some_and(|t| !t.is_empty()), };if binned_after {return patch; }let parse = |text: &str| serde_json::from_str::<Value>(text).ok();letmut meta: Value = match patch.get("meta") {Some(Value::String(text)) => parse(text).unwrap_or_else(|| serde_json::json!({})),Some(value @ Value::Object(_)) => value.clone(),Some(_) => serde_json::json!({}),None => row.text("meta").and_then(parse).unwrap_or_else(|| serde_json::json!({})), };let timers_own = patch.contains_key("meta") && meta.pointer("/cotton/timer_back") == Some(&Value::Bool(true)) && meta.pointer("/cotton/timer_binned").is_none_or(Value::is_null);if !meta.is_object() { meta = serde_json::json!({}); }if !meta.get("cotton").is_some_and(Value::is_object) { meta["cotton"] = serde_json::json!({}); }ifletSome(cotton) = meta.get_mut("cotton").and_then(Value::as_object_mut) { cotton.remove("timer_back");if !timers_own { cotton.remove("timer_binned"); cotton.insert("timer_kept".to_string(), Value::Bool(true)); } } patch.insert("meta".to_string(), meta); patch }/// `workspace_id` on every row that has the column — stamped at commit,/// after the handler's own patch has been read as it was given.fn stamped(&self, table: &str, patch: Map<String, Value>) -> Map<String, Value> {letmut patch = patch;ifletSome(columns) = cotton_core::records::place::builtin_columns().get(table) { cotton_core::records::place::invalidate_unpicked(columns, &mut patch);// The coordinates and version of an unpicked place go with it, where this file keeps them.let unpicked: Vec<String> = columns.iter() .filter(|(_, siblings)| patch.get(&siblings.id) == Some(&Value::Null)) .flat_map(|(_, siblings)| cotton_core::records::place::extra_siblings(siblings).cloned().collect::<Vec<_>>()) .collect();if !unpicked.is_empty() {let spec = cotton_store::schema::package_shape::spec_on(self.driver, table).ok().flatten();for key in unpicked {if spec.is_some_and(|spec| spec.columns.iter().any(|(name, _)| *name == key)) { patch.entry(key).or_insert(Value::Null); } } }// A person's explicit city choice is no longer an automatic fill,// even if its text happens to equal the earlier suggestion.if table == "cotton_people" && patch.contains_key("city") { patch.entry("city_filled_at".to_string()).or_insert(Value::Null); } }// A made table is known by this file, not the build// (`package_shape::spec_on`).if !patch.contains_key("workspace_id") && cotton_store::schema::package_shape::spec_on(self.driver, table) .ok() .flatten() .is_some_and(|spec| spec.columns.iter().any(|(column, _)| *column == "workspace_id")) { patch.insert("workspace_id".to_string(),Value::from(self.workspace_id.clone()), ); } patch }/// RETRACT a row: it leaves every device, and a later create at the same/// id is an ordinary create. `why` says which of the three retracts this/// is ([`Retract`]); there is no delete that names none.pubfn retract(&mutself, table: &str, row_id: &str, why: Retract) { debug_assert!(why.is_listed(), "{why:?} is on neither retract list");self.changes.push(LocalChange::delete(table, row_id).retract()); }/// ERASE a record: the owner emptied it from the bin, or the verb destroys/// its bytes. An erased record is never recreated by a later write. Only/// the verbs the design lists erase; everything else retracts. `reason`/// is `bin`, or the verb that destroys the bytes; the store takes the/// record's owned descendants with it, so the act names only the record.pubfn erase(&mutself, table: &str, row_id: &str, reason: &str) { debug_assert!(!reason.is_empty(), "an erase names its reason");self.changes.push(LocalChange::delete(table, row_id).erase(reason)); }/// TAKE BACK an add: Undo of the add, by the person who made the record,/// on the device they made it on, while nothing has changed it — an/// erase `mint` judges (`cotton_store::take_back`) and refuses otherwise./// `through` is the stamp of the last receipt of the add's own act.pubfn take_back(&mutself, table: &str, row_id: &str, through: &str) {self.changes.push(LocalChange::delete(table, row_id).take_back(through)); }/// SOURCE-ERASE a row: `job` mirrors a deletion made outside Cotton (the/// mail provider erased a message, the calendar cancelled an event), so/// the job's next pass must not bring it back.pubfn source_erase(&mutself, job: &str, table: &str, row_id: &str) { debug_assert!(!job.is_empty(), "a source-erase names its job");self.changes.push(LocalChange::delete(table, row_id).source_erase(job)); }/// Revoke a subject in this act — the fact and the row's mirror, through/// the one revocation writer ([`cotton_store::revocation::revoke`]);/// nothing lands until [`Writer::commit`]. `by` is the device key acting./// Answers how many mirrors were written (0: already revoked).pubfn revoke( &mutself, subject_table: &str, subject_id: &str, reason: &str, successor: Option<&str>, signer: Option<&cotton_store::revocation::Signer>, by: &str, ) -> Result<usize> {let at = crate::clock::iso(self.now);self.revoke_at(subject_table, subject_id, reason, successor, signer, by, &at) }/// [`Writer::revoke`] at a moment the caller names: a signed removal's/// `revoked_at` is the stamp its signer signed, so the fact can be checked/// against its signature later. The caller bounds how far `at` may be/// from this writer's own clock. #[allow(clippy::too_many_arguments)]pubfn revoke_at( &mutself, subject_table: &str, subject_id: &str, reason: &str, successor: Option<&str>, signer: Option<&cotton_store::revocation::Signer>, by: &str, at: &str, ) -> Result<usize> {let actor = self.actor.to_wire();let random = Arc::clone(&self.random);letmut new_id = move || crate::random::uuid_v4(random.as_ref()); cotton_store::revocation::revoke( &mut cotton_store::revocation::RevokeAct { db: self.driver, changes: &mutself.changes, workspace_id: &self.workspace_id, actor: &actor, by, at, new_id: &mut new_id, }, subject_table, subject_id, reason, successor, signer, ) }/// End a stale hardware key and retain its replacement in the typed revocation fact.pubfn replace_device(&mutself, device_id: &str, replaced_by: &str, by: &str) -> Result<usize> {let at = crate::clock::iso(self.now);let actor = self.actor.to_wire();let random = Arc::clone(&self.random);letmut new_id = move || crate::random::uuid_v4(random.as_ref()); cotton_store::revocation::replace_device(&mut cotton_store::revocation::RevokeAct { db: self.driver, changes: &mutself.changes, workspace_id: &self.workspace_id, actor: &actor, by, at: &at, new_id: &mut new_id, }, device_id, replaced_by) }/// Re-key: the old key is succeeded by `successor` (`revocation::succeed_device`).pubfn succeed_device(&mutself, device_id: &str, successor: &str, by: &str) -> Result<usize> {let at = crate::clock::iso(self.now);let actor = self.actor.to_wire();let random = Arc::clone(&self.random);letmut new_id = move || crate::random::uuid_v4(random.as_ref()); cotton_store::revocation::succeed_device(&mut cotton_store::revocation::RevokeAct { db: self.driver, changes: &mutself.changes, workspace_id: &self.workspace_id, actor: &actor, by, at: &at, new_id: &mut new_id, }, device_id, successor) }/// HOLD THE NEXT RECORD MADE IN `table` (its physical table) for the/// owner alone: the commit that creates it mints the only-you mark/// (`cotton_store::audience::mark`) in the same act, BEFORE the record —/// so no exchange, replica or reader ever has the record without its mark.pubfn holding_next_create(&mutself, table: &str) {self.hold = Some(table.to_string()); }/// Is a hold asked for still waiting on its record's create?pubfn hold_waiting(&self) -> bool {self.hold.is_some() }/// Forget a hold that will not be minted (a create that asked first).pubfn drop_hold(&mutself) {self.hold = None; }/// The asked-for hold's mark, put before the first change that creates a/// row of its table — a row this file holds no receipt of.fn put_hold_first(&mutself, changes: &mutVec<LocalChange>) -> Result<()> {letSome(table) = self.hold.clone() else {returnOk(()); };letmut at = None;for (index, change) in changes.iter().enumerate() {if change.kind != cotton_store::protocol::types::OpKind::Upsert || change.table != table {continue; }let known = self .driver .get("SELECT 1 AS x FROM _writes WHERE tbl = ?1 AND row_id = ?2 \ UNION ALL SELECT 1 FROM _tombstones WHERE tbl = ?1 AND row_id = ?2 LIMIT 1", &[ rusqlite::types::Value::Text(table.clone()), rusqlite::types::Value::Text(change.row_id.clone()), ], )? .is_some();if !known { at = Some(index);break; } }letSome(index) = at else {returnOk(()); };let record = changes[index].row_id.clone();let when = crate::mcp::handlers::common::iso_of_ms(self.now.timestamp_millis());let mark = cotton_store::audience::mark(self.driver, &self.workspace_id, &table, &record, &when)?; changes.insert(index, LocalChange::upsert(&mark.table, &mark.row_id, mark.patch.unwrap_or_default()));self.hold = None;Ok(()) }pubfn pending(&self) -> usize {self.changes.len() }pubfn ops(&self) -> &[CottonOp] { &self.ops }pubfn discard_queued(&mutself) {self.changes.clear();self.hold = None; }/// Open (`true`) or close (`false`) a generic verb whose own change row is/// the action's history (slice 6b-2): the engine's acts committed while one/// is open keep no history of their own, so an action leaves ONE row.pubfn noting_history(&mutself, open: bool) {if open {self.noted += 1; } else {self.noted = self.noted.saturating_sub(1); } }/// Make the next commit an UNDO (slice 3b): its act's receipts name the/// `cotton_undos` fact `fact`, which the caller writes first in that act.pubfn undoing(&mutself, fact: &str) {self.undo = Some(fact.to_string()); }/// Mint the collected changes as ops and fold them, in one transaction —/// [`cotton_store::mint::mint`], as this writer's actor.////// Returns the ops it wrote, so a caller that has to wake the live channel/// or answer with a row id does not read them back out of the file.pubfn commit(&mutself) -> Result<Vec<CottonOp>> {crate::derive::install();ifself.changes.is_empty() {returnOk(Vec::new()); }letmut queued = std::mem::take(&mutself.changes);self.put_hold_first(&mut queued)?;let changes: Vec<LocalChange> = queued .into_iter() .map(|change| LocalChange { patch: change.patch.map(|patch| self.stamped(&change.table, self.timer_kept(&change.table, &change.row_id, patch))), ..change }) .collect();let now_ms = self.now.timestamp_millis();let random = Arc::clone(&self.random);letmut ids = Monotonic::new(move |bytes: &mut [u8]| random.fill(bytes));// JUDGED (slice 1): the serving Mac's file and a replica's alike mint// by their judge's clock, after the release pass; the wall clock on a// handle with no judge.let clock = writer_clock(self.driver, now_ms, &mut ids)?;self.mint_changes(changes, &clock, &mut ids).map(|minted| minted.ops) }/// [`Writer::commit`] as one batch of rows ([`cotton_store::mint::mint_batch`]):/// the same ops, with the file's shape read once for them all.pubfn commit_batch(&mutself) -> Result<Vec<CottonOp>> {let driver = self.driver; cotton_store::fold::as_one_batch(driver, || self.commit()) }/// Mint the collected changes by a clock the CALLER read, in one/// transaction, with no release pass first — the take-over's act (slice/// 12), which is made by the one relay reading it took and must be Checked:/// never held, never re-dated. Answers the whole [`Minted`], so the caller/// can refuse an act the clock held or moved to another author.pubfn commit_at( &mutself, clock: &cotton_store::mint::Clock, ) -> Result<cotton_store::mint::Minted> {crate::derive::install();let changes: Vec<LocalChange> = std::mem::take(&mutself.changes) .into_iter() .map(|change| LocalChange { patch: change.patch.map(|patch| self.stamped(&change.table, self.timer_kept(&change.table, &change.row_id, patch))), ..change }) .collect();let random = Arc::clone(&self.random);letmut ids = Monotonic::new(move |bytes: &mut [u8]| random.fill(bytes));self.mint_changes(changes, clock, &mut ids) }/// Import a Cotton package as this writer's actor, on the file it holds/// ([`cotton_store::cottonpkg::import`]): each record minted by this/// writer's clock, the bytes landed through `media`. The ops join this/// writer's, so the caller wakes the live channel as for any write.pubfn import_package( &mutself, package: &cotton_store::cottonpkg::Package, media: &mutdyn cotton_store::cottonpkg::MediaSink, ) -> Result<cotton_store::cottonpkg::Imported> {crate::derive::install();let random = Arc::clone(&self.random);letmut ids = Monotonic::new(move |bytes: &mut [u8]| random.fill(bytes));let clock = writer_clock(self.driver, self.now.timestamp_millis(), &mut ids)?;let imported = cotton_store::cottonpkg::import(self.driver, package, &self.actor, &clock, &mut ids, self.held, media)?;self.ops.extend(imported.ops.iter().cloned());Ok(imported) }fn mint_changes( &mutself, changes: Vec<LocalChange>, clock: &cotton_store::mint::Clock, ids: &mutdyn cotton_store::mint::IdSource, ) -> Result<cotton_store::mint::Minted> {let undo = self.undo.take();let changes_span = cotton_store::spans::span("writer::changes_of");let changes = changes_of(self.driver, &changes); drop(changes_span);let act = Act { actor: self.actor.clone(), verb: self.verb.clone(), history: ifself.noted > 0 { History::None } else { History::Kept }, changes, };let minted = mint_undo(self.driver, &act, clock, ids, self.held, undo.as_deref())?;self.ops.extend(minted.ops.iter().cloned());Ok(minted) }}/// The last stamp this file issued. Read by the one hand-built op path left/// (`oauth/grant.rs`), which slice 2b moves to `mint`.pubfn last_hlc_of(db: &Driver) -> Result<Option<String>> {Ok(db .get("SELECT last_hlc FROM _meta", &[])? .and_then(|row| row.text("last_hlc").map(str::to_string)))}#[cfg(test)]#[path = "writer_tests.rs"]mod tests;/// Which retract a site is — the first of the five kinds of delete (the sync/// design's 6.2; the others are Erase, Source-erase, Revocation, and Fact,/// whose delete is refused).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumRetract {/// A relation or a derived row: a link, a membership, a projection, a row/// a job rewrites from its source. Re-creating it is the ordinary case.Relation,/// A person-facing hard-delete verb whose bin is not built yet, named on/// [`RETRACT_VERBS`]. It becomes a move to the bin when the table has one.Verb(&'static str),/// A machine path, with its reason on [`MACHINE_RETRACTS`].Machine(&'static str),}implRetract {fn is_listed(self) -> bool {matchself {Retract::Relation => true,Retract::Verb(verb) => RETRACT_VERBS.contains(&verb),Retract::Machine(reason) => MACHINE_RETRACTS.iter().any(|(name, _)| *name == reason), } }}/// The person-facing verbs that hard-delete a record because its table has no/// bin yet. Each is a Retract, never an Erase: the record's history stays and/// an undo brings it back.pubconst RETRACT_VERBS: &[&str] = &["connections.disconnect","delete_thread","delete_toolkit","remove_evidence","settings.forgetVoiceTerm","stop_todo_recurrence",];/// The machine paths that retract a row, each with what it is doing.pubconst MACHINE_RETRACTS: &[(&str, &str)] = &[ ("theme_undo", "undo withdraws a theme override whose prior row was absent"), ("board_undo", "undo withdraws a board override whose prior row was absent"), ("reroute", "a capture routed again: the row its first routing made, never edited, is withdrawn"), ("rekey", "a row re-inserted under its derived id; the old id is withdrawn"), ("moved", "a made table's record the generic store had retracted: its tombstone, carried to the record's own table"), ("drop_old_music", "a phone's own copy drops the music before Cotton Music once: the old tables' rows and the gone tables' definitions (kit_keep KEEP_RULE 8)"), ("retire_gone", "a phone's own copy holds a retired table's or tool's definition as retired, its rows kept (kit_keep KEEP_RULE 13, cotton_core::retired)"),];