//! The importer's own copy of what its engines read (sealing plan L8).//!//! The messages and calls engines used to run on the Worker over the object's//! rows in the clear. A sealed table gives the Worker nothing to match on, so//! they run here instead, the way the phone runs them: over a copy of the//! rows they read, opened with this Mac's data key (DK), and the rows they//! plan go up through one act, `import_rows`, sealed when their table is.//! The object matches nothing; it only keeps.//!//! The copy is one SQLite file beside `importer.db`, `copy.db`, holding the//! object's rows of [`TABLES`] in the object's own shape (`rows(table_id,//! id, data, …)`, `data` the opened columns as JSON), so the engine's//! questions are answered by the same statements the Worker's reader asked//! (`apps/business/src/import/reader.ts`). It is filled by `GET /v1/sync` of//! those tables from its own cursor, whole, with no window: every message the//! object holds is here, so a re-read dedupes by the message's own id.//!//! Three rules, as on the phone://! - **No fallback to clear.** A sealed table's row leaves only sealed, with//! its blind tokens; with no DK, or the object's seal keys unread, the//! landing refuses by name ([`cotton_client::seal::SEAL_KEY_MISSING`]) and//! the batch is read again next pass.//! - **A row that does not open stops the refresh by name**//! (`seal_does_not_open`): an engine that could not see it would make it//! again, so nothing is planned over a copy with a hole in it.//! - **A landing is whole or not at all here.** Its rows go into the copy//! inside one transaction, the reply pass reads them there, and the copy//! keeps them only once the object took every call; a refused call rolls//! the copy back and the next refresh brings whatever the object did keep.use std::collections::BTreeMap;use std::path::Path;use std::sync::{Arc, Mutex};use cotton_client::seal::{DataKeyStore, Sealer, SEAL_KEY_TABLE};use cotton_core::definitions::seal::SealSpec;use cotton_core::seal::row as stored_row;use cotton_rules::import::asked::{self, Ask};use rusqlite::{params, Connection, OptionalExtension};use serde_json::{json, Map, Value};usecrate::object::{ObjectClient, ObjectError, IMPORT_ROWS};/// The object's tables the importer's engines read and write, plus the seal/// keys: threads, messages and their people for the messages engine, people/// and their handles for every match, calls for the calls engine, and the/// pictures, their sightings and faces for the Photos pass ([`crate::photos`]).pubconst TABLES: &[&str] = &["person","person_handle",// Where each contact came from (Photos finds a person it kept before) and the numbers several contacts share// (who(handle) names all of them): PEOPLE BUILD 1b and 2."person_source","shared_handle","message_contact","message_contact_handle","thread","thread_member","message","message_reaction","call","photo","video","sighting","face", SEAL_KEY_TABLE,];/// The tables the messages engine writes.pubconst MESSAGE_TABLES: &[&str] = &["thread", "message", "thread_member", "message_reaction", "message_contact", "message_contact_handle"];/// The phone's table names the engine plans under → the object's.const ENGINE_TABLES: &[(&str, &str)] = &[ ("cotton_msg_threads", "thread"), ("cotton_msg_messages", "message"), ("cotton_msg_thread_participants", "thread_member"), ("cotton_msg_reactions", "message_reaction"), ("cotton_msg_contacts", "message_contact"), ("cotton_msg_contact_handles", "message_contact_handle"),];/// Keys of a planned patch that are the row's frame, never its columns.const FRAME: &[&str] = &["id", "created_at", "updated_at", "workspace_id"];const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS rows( table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 0, deleted INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT '', dek_enc TEXT, seal_v INTEGER, PRIMARY KEY(table_id, id));CREATE INDEX IF NOT EXISTS rows_message_external ON rows(json_extract(data, '$.external_id')) WHERE table_id = 'message';CREATE INDEX IF NOT EXISTS rows_message_thread ON rows(json_extract(data, '$.thread_id'), json_extract(data, '$.sent_at')) WHERE table_id = 'message';CREATE INDEX IF NOT EXISTS rows_contact_handle ON rows(json_extract(data, '$.value')) WHERE table_id = 'message_contact_handle';CREATE INDEX IF NOT EXISTS rows_email_gmail ON rows(json_extract(data, '$.gmail_id')) WHERE table_id = 'email';CREATE INDEX IF NOT EXISTS rows_thread_key ON rows(json_extract(data, '$.external_key')) WHERE table_id = 'thread';CREATE INDEX IF NOT EXISTS rows_sighting_source ON rows(json_extract(data, '$.source_id')) WHERE table_id = 'sighting';CREATE INDEX IF NOT EXISTS rows_face_cluster ON rows(json_extract(data, '$.cluster_id')) WHERE table_id = 'face';CREATE TABLE IF NOT EXISTS copy_meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE INDEX IF NOT EXISTS rows_outbox_sent ON rows(json_extract(data, '$.sent_external_id')) WHERE table_id = 'outbox';-- The messages erased from the person's database (a chat's own timer, or any delete), by channel and the channel's-- own id, never their words: an import never brings one back. A message that comes back to life leaves the list.CREATE TABLE IF NOT EXISTS erased(channel TEXT NOT NULL, external_id TEXT NOT NULL, at TEXT NOT NULL DEFAULT '', PRIMARY KEY(channel, external_id));-- WhatsApp polls the Mac asked the phone for again (old polls kept without their options): when and how often.CREATE TABLE IF NOT EXISTS asked_polls(external_id TEXT PRIMARY KEY, at INTEGER NOT NULL, tries INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS asked_older(thread_id TEXT PRIMARY KEY, before TEXT NOT NULL, at INTEGER NOT NULL, tries INTEGER NOT NULL, done INTEGER NOT NULL DEFAULT 0);";#[derive(Debug, thiserror::Error, PartialEq)]pubenumCopyError { #[error(transparent)]Object(#[from] ObjectError),/// A seal refusal by its code (`seal_key_missing`, `seal_does_not_open`, …). #[error("{code}: {message}")]Seal { code: String, message: String },/// The engine refused the batch: its words and its code. #[error("the import engine refused ({code}): {message}")]Engine { code: String, message: String }, #[error("the importer's copy: {0}")]File(String),}implCopyError {pubfn code(&self) -> Option<&str> {matchself {CopyError::Object(error) => error.code(),CopyError::Seal { code, .. } | CopyError::Engine { code, .. } => Some(code),CopyError::File(_) => None, } }}fn file(error: rusqlite::Error) -> CopyError {CopyError::File(error.to_string())}fn seal(error: cotton_core::seal::SealError) -> CopyError {CopyError::Seal { code: error.code().to_string(), message: error.to_string() }}pubtypeResult<T> = std::result::Result<T, CopyError>;/// A table as the definitions serve it: its columns, their defaults, its seal.#[derive(Debug, Clone, Default)]structShape { columns: Vec<String>, defaults: Map<String, Value>, seal: Option<SealSpec>,}/// One row the engine planned, under the object's table name.#[derive(Debug, Clone, PartialEq)]pubstructChange {pub table: String,pub id: String,/// `None` for a retract.pub patch: Option<Map<String, Value>>,}implChange {/// The engine's planned changes (`{table, id, patch}` or `{table, id,/// retract: true}`, phone table names) as the object's.pubfn from_plan(planned: &Value) -> Result<Vec<Change>> {let list = planned.as_array().ok_or_else(|| CopyError::File("the engine's plan carries no changes".into()))?; list.iter() .map(|change| {let table = change["table"].as_str().unwrap_or_default();let table = ENGINE_TABLES .iter() .find(|(phone, _)| *phone == table) .map_or(table, |(_, object)| *object) .to_string();let id = change["id"].as_str().unwrap_or_default().to_string();if change.get("retract") == Some(&Value::Bool(true)) {returnOk(Change { table, id, patch: None }); }let patch = change["patch"].as_object().cloned().unwrap_or_default();Ok(Change { table, id, patch: Some(patch) }) }) .collect() }}/// What a landing did at the object.#[derive(Debug, Clone, Default, PartialEq)]pubstructLanded {/// Rows sent, by table.pub sent: BTreeMap<String, i64>,/// `import_rows` calls made.pub calls: i64,/// Rows new to the copy, by table: a row it held (live) already is not counted, so a source read again from/// its start creates none (the panel's count is what is new, never what was sent again).pub created: BTreeMap<String, i64>,}implLanded {/// Rows new to the copy across `tables`.pubfn created_in(&self, tables: &[&str]) -> i64 { tables.iter().map(|t| self.created.get(*t).copied().unwrap_or(0)).sum() }}pubstructCopy { conn: Mutex<Connection>, sealer: Arc<Sealer>, keys: Arc<dynDataKeyStore>, database_id: String, shapes: Mutex<BTreeMap<String, Shape>>, owner_phone: Mutex<Option<String>>, namespace: Mutex<Option<String>>,}impl std::fmt::DebugforCopy {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Copy").field("database_id", &self.database_id).finish_non_exhaustive() }}implCopy {/// The copy at `path` of `database_id`'s rows, sealing and opening with/// the DK `keys` holds. A copy made for another database is started/// again: its rows are not this one's.pubfn open(path: &Path, database_id: &str, keys: Arc<dynDataKeyStore>) -> Result<Copy> {let conn = Connection::open(path).map_err(file)?;// One transaction, so one sync to disk: each statement on its own commits and syncs, and on a busy disk// the copy's dozen tables took half a minute to make (rust-main 17065, a Mac source's first landed run).let opening = conn.unchecked_transaction().map_err(file)?; opening.execute_batch(SCHEMA).map_err(file)?;// ERASES: what an older build kept of a row the person removed (its words, on this Mac). A removed row// keeps only that it was removed. opening.execute("UPDATE rows SET data = '{}' WHERE deleted = 1 AND data <> '{}'", []).map_err(file)?;let held: Option<String> = opening .query_row("SELECT value FROM copy_meta WHERE key = 'database_id'", [], |r| r.get(0)) .optional() .map_err(file)?;if held.as_deref() != Some(database_id) { opening.execute_batch("DELETE FROM rows; DELETE FROM copy_meta; DELETE FROM erased;").map_err(file)?; opening.execute("INSERT INTO copy_meta(key, value) VALUES ('database_id', ?1)", [database_id]).map_err(file)?; } opening.commit().map_err(file)?;let sealer = Sealer::new(database_id, Arc::clone(&keys));// The seal keys this copy kept: a table's version is known before the// next refresh, but nothing seals until a refresh reads them all. {letmut statement = conn.prepare("SELECT id, data FROM rows WHERE table_id = ?1 AND deleted = 0").map_err(file)?;let kept = statement .query_map([SEAL_KEY_TABLE], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) .map_err(file)?;for row in kept {let (id, data) = row.map_err(file)?;ifletOk(Value::Object(data)) = serde_json::from_str(&data) { sealer.learn(&id, &data); } } }Ok(Copy { conn: Mutex::new(conn), sealer, keys, database_id: database_id.to_string(), shapes: Mutex::new(BTreeMap::new()), owner_phone: Mutex::new(None), namespace: Mutex::new(None), }) }pubfn sealer(&self) -> &Arc<Sealer> { &self.sealer }pubfn database_id(&self) -> &str { &self.database_id }/// What derived ids (contacts, threads, calls) are made under: the/// object's namespace as its definitions serve it, its own database id/// unless it was made under an older file's.pubfn namespace(&self) -> String {self.namespace.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone().unwrap_or_else(|| self.database_id.clone()) }fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {self.conn.lock().unwrap_or_else(std::sync::PoisonError::into_inner) }/// The DK, or [`cotton_client::seal::SEAL_KEY_MISSING`] by name.fn dk(&self) -> Result<cotton_core::seal::DataKey> {matchself.keys.data_key(&self.database_id) {Ok(Some(dk)) => Ok(dk),Ok(None) => Err(seal(cotton_core::seal::SealError::KeyMissing(format!("the data key of {} (this Mac holds none yet)", self.database_id)))),Err(why) => Err(seal(cotton_core::seal::SealError::KeyMissing(format!("the data key of {} (the key store said: {why})", self.database_id)))), } }/// The file key a sealed file of `table` whose row keeps no key of its own/// (a story's picture) is sealed under: derived from the DK's blind key/// of `table` and the file's random object key/// ([`cotton_core::seal::file::derived_key`]).pubfn derived_file_key(&self, table: &str, object_key: &str) -> Result<cotton_core::seal::file::FileKey> {let bk = cotton_core::seal::blind_key(&self.dk()?, &self.database_id, table).map_err(seal)?;Ok(cotton_core::seal::file::derived_key(&bk, object_key)) }/// What an engine makes derived ids under when it writes `tables`: the/// object's [`Copy::namespace`] while none of them is sealed, else a/// namespace only this database's DK makes. A derived id is a hash of the/// namespace and a phone number; under the database id (which the Worker/// knows) a number is found again by trying every one, so a sealed row's/// id is made under a namespace the Worker cannot.pubfn namespace_for(&self, tables: &[&str]) -> Result<String> {let plain = self.namespace();if !tables.iter().any(|t| self.is_sealed(t)) {returnOk(plain); } cotton_client::seal::keyed_namespace(&self.dk()?, &self.database_id, &plain).map_err(seal) }/// The id a row of `table` the engine planned under `planned` is kept/// under: itself, unless the table is sealed and the id says something/// (a reaction's `react:<message>:<actor phone>`), when it is the keyed/// id only the DK makes from it, the same on every pass.fn object_id(&self, table: &str, sealed: bool, planned: &str) -> Result<String> {if !sealed || uuid_shaped(planned) {returnOk(planned.to_string()); } cotton_client::seal::keyed_row_id(&self.dk()?, &self.database_id, table, planned).map_err(seal) }/// Whether `table` is sealed, as the object's definitions last said.pubfn is_sealed(&self, table: &str) -> bool {self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(table).is_some_and(|s| s.seal.is_some()) }/// Bring the copy up to the object: its definitions (columns and seals)/// and owner, then every row of [`TABLES`] changed since the copy's/// cursor, opened. The cursor moves only once the last page is in.pubfn refresh(&self, object: &ObjectClient) -> Result<()> {self.take_definitions(&object.definitions()?)?;self.read_up(object) }/// The folder the copy's file is in: where what waits beside it is kept (a WhatsApp picture waiting for the/// data key). None for a copy held in memory.pubfn folder(&self) -> Option<std::path::PathBuf> {self.conn().path().filter(|path| !path.is_empty()).and_then(|path| std::path::Path::new(path).parent().map(std::path::Path::to_path_buf)) }/// One value the copy keeps beside its rows (`copy_meta`), by name.pubfn kept(&self, key: &str) -> Result<Option<String>> {self.conn().query_row("SELECT value FROM copy_meta WHERE key = ?1", [key], |r| r.get::<_, String>(0)).optional().map_err(file) }/// Keep `value` under `key` beside the rows; None forgets it.pubfn keep(&self, key: &str, value: Option<&str>) -> Result<()> {let conn = self.conn();match value {Some(value) => conn.execute("INSERT INTO copy_meta(key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]),None => conn.execute("DELETE FROM copy_meta WHERE key = ?1", [key]), } .map_err(file)?;Ok(()) }/// The kept tables read up to the object from the copy's cursor, with the definitions it holds: what every/// landing does first (STALE WRITES, 25 Nov 2026), so a patch is never sealed over a row as it stood before a/// long wait (a batch's uploads, a transcription). One sync, and nothing when nothing changed.pubfn read_up(&self, object: &ObjectClient) -> Result<()> {let tables = self.kept_tables();let set = tables.join(",");letmut conn = self.conn();let meta = |key: &str| -> Result<Option<String>> { conn.query_row("SELECT value FROM copy_meta WHERE key = ?1", [key], |r| r.get::<_, String>(0)).optional().map_err(file) };// A table newly kept (sealed since the last refresh) comes whole: the copy reads again from nothing.let since: i64 = if meta("tables")?.as_deref() == Some(set.as_str()) { meta("cursor")?.and_then(|v| v.parse().ok()).unwrap_or(0) } else { 0 };let tx = conn.transaction().map_err(file)?; tx.execute("INSERT INTO copy_meta(key, value) VALUES ('tables', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [&set]).map_err(file)?;let names: Vec<&str> = tables.iter().map(String::as_str).collect();letmut cursor: Option<String> = None;letmut version = since;loop {let page = object.sync_page(since, &names, cursor.as_deref())?;for row in page["rows"].as_array().into_iter().flatten() {self.fold(&tx, row)?; }ifletSome(v) = page["version"].as_i64() { version = v; }match page.get("next").and_then(Value::as_str) {Some(next) => cursor = Some(next.to_string()),None => break, } } tx.execute("INSERT INTO copy_meta(key, value) VALUES ('cursor', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [version.to_string()], ) .map_err(file)?; tx.commit().map_err(file)?;self.sealer.learned_all();Ok(()) }/// The tables the copy keeps: what the engines read ([`TABLES`]), and/// every sealed table, whose rows a partial write is sealed whole over.fn kept_tables(&self) -> Vec<String> {let shapes = self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner);letmut tables: Vec<String> = TABLES.iter().map(|t| (*t).to_string()).collect();for (table, shape) in shapes.iter() {if shape.seal.is_some() && !tables.contains(table) { tables.push(table.clone()); } } tables }/// The tables the object's definitions seal, as the copy last read them.pubfn sealed_tables(&self) -> Vec<String> {self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|(_, s)| s.seal.is_some()).map(|(t, _)| t.clone()).collect() }/// Whether the object's definitions give `table` the column `key`.pubfn has_column(&self, table: &str, key: &str) -> bool {self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(table).is_some_and(|s| s.columns.iter().any(|c| c == key)) }/// A row the object served (a list answer's `data`), opened when sealed.pubfn open_served(&self, table: &str, id: &str, data: &Map<String, Value>) -> Result<Map<String, Value>> {self.sealer.open(table, id, data).map_err(seal) }fn take_definitions(&self, served: &Value) -> Result<()> {letmut shapes = BTreeMap::new();for table in served["tables"].as_array().into_iter().flatten() {letSome(id) = table["id"].as_str() else { continue };let seal = cotton_client::seal::spec_of_definition(table).map_err(|message| CopyError::Seal { code: "seal_bad_input".into(), message })?;letmut shape = Shape { seal, ..Shape::default() };for column in table["columns"].as_array().into_iter().flatten() {letSome(key) = column["key"].as_str() else { continue };if column.get("computed").is_some_and(|c| !c.is_null()) {continue; } shape.columns.push(key.to_string());ifletSome(default) = column.get("default").filter(|d| !d.is_null()) { shape.defaults.insert(key.to_string(), default.clone()); } } shapes.insert(id.to_string(), shape); } *self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = shapes; *self.owner_phone.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = served.pointer("/business/owner_phone").and_then(Value::as_str).map(str::to_string); *self.namespace.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = served.pointer("/business/namespace").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string);Ok(()) }/// One served row into the copy, opened when sealed.fn fold(&self, tx: &Connection, row: &Value) -> Result<()> {let (Some(table), Some(id)) = (row["table"].as_str(), row["id"].as_str()) else { returnOk(()) };if !TABLES.contains(&table) && !self.is_sealed(table) {returnOk(()); }let deleted = row.get("deleted") == Some(&Value::Bool(true));letmut data = row["data"].as_object().cloned().unwrap_or_default();letmut wrap: (Option<String>, Option<i64>) = (None, None);if table == SEAL_KEY_TABLE {if !deleted {self.sealer.learn(id, &data); } } elseif !deleted && stored_row::is_sealed(&data) { wrap = ( data.get(stored_row::DEK_ENC).and_then(Value::as_str).map(str::to_string), stored_row::version_of(&data).ok().map(i64::from), ); data = self.sealer.open(table, id, &data).map_err(seal)?; }if table == "message" { remember_erased(tx, id, deleted, &data, row["updated_at"].as_str().unwrap_or_default())?; }// A removed row keeps nothing of what it held: the person erased it.if deleted { data = Map::new(); } tx.execute("INSERT INTO rows(table_id, id, data, version, deleted, created_at, updated_at, dek_enc, seal_v) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(table_id, id) DO UPDATE SET data = excluded.data, version = excluded.version, deleted = excluded.deleted, created_at = excluded.created_at, updated_at = excluded.updated_at, dek_enc = excluded.dek_enc, seal_v = excluded.seal_v", params![ table, id,Value::Object(data).to_string(), row["version"].as_i64().unwrap_or(0), deleted, row["created_at"].as_str().unwrap_or_default(), row["updated_at"].as_str().unwrap_or_default(), wrap.0, wrap.1, ], ) .map_err(file)?;Ok(()) }/// Which of `external_ids` on `channel` were erased from the person's database: an import brings none back.pubfn erased_of(&self, channel: &str, external_ids: &[&str]) -> Result<std::collections::HashSet<String>> {let conn = self.conn();letmut statement = conn.prepare("SELECT EXISTS(SELECT 1 FROM erased WHERE channel = ?1 AND external_id = ?2)").map_err(file)?;letmut erased = std::collections::HashSet::new();for id in external_ids {if statement.query_row([channel, id], |r| r.get::<_, bool>(0)).map_err(file)? { erased.insert((*id).to_string()); } }Ok(erased) }/// The chat Comms named for a text it queued, found by the WhatsApp id fixed at the owner's tap: a first text/// to a number lands in the chat the phone already shows for it. The outbox is kept because it is sealed (as/// every phone writes it); naming it in [`TABLES`] would change the kept set and read the whole copy again.pubfn outbox_thread(&self, external_id: &str) -> Result<Option<String>> {self.conn() .query_row("SELECT json_extract(data, '$.thread_id') FROM rows WHERE table_id = 'outbox' AND deleted = 0 AND json_extract(data, '$.sent_external_id') = ?1 AND COALESCE(json_extract(data, '$.thread_id'), '') <> '' LIMIT 1", [external_id], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }/// Whether the copy holds the message `external_id` on `channel` with its/// file already: its bytes are never read again.pubfn holds_message_media(&self, channel: &str, external_id: &str) -> Result<bool> {self.conn() .query_row("SELECT EXISTS(SELECT 1 FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.external_id') = ?1 AND json_extract(data, '$.channel') = ?2 AND COALESCE(json_array_length(data, '$.media'), 0) > 0)", [external_id, channel], |r| r.get(0), ) .map_err(file) }/// How many of a source's own things the copy holds: WhatsApp's messages, the Photos library's pictures, the/// call history's calls (what the panel says the source brought; `None` for a source the copy does not hold,/// Mail). Rows an earlier build or the old store brought count too: they are in Cotton from that source./// `None` too while the copy was never brought up to the object: it would count nothing that is there./// What this Mac lands goes into the copy as it lands, so a copy brought up once counts it without asking.pubfn held_from(&self, source: &str) -> Result<Option<i64>> {let brought_up: bool = self .conn() .query_row("SELECT EXISTS(SELECT 1 FROM copy_meta WHERE key = 'tables')", [], |r| r.get(0)) .map_err(file)?;if !brought_up {returnOk(None); }let (sql, of) = match source {// A marker for an erased message is not a message held."whatsapp" => ("SELECT COUNT(*) FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.channel') = ?1 AND json_extract(data, '$.meta.cotton.erased') IS NULL","whatsapp", ),"photos" => ("SELECT COUNT(DISTINCT json_extract(data, '$.record_id')) FROM rows WHERE table_id = 'sighting' AND deleted = 0 AND json_extract(data, '$.source') = ?1","apple_library", ),"calls" => ("SELECT COUNT(*) FROM rows WHERE table_id = 'call' AND deleted = 0 AND json_extract(data, '$.source') = ?1", cotton_client::ingest::sources::call_history::CALL_SOURCE, ), _ => returnOk(None), };self.conn().query_row(sql, [of], |r| r.get(0)).map(Some).map_err(file) }/// The number of live rows of `table` the copy holds.pubfn count(&self, table: &str) -> Result<i64> {self.conn() .query_row("SELECT COUNT(*) FROM rows WHERE table_id = ?1 AND deleted = 0", [table], |r| r.get(0)) .map_err(file) }/// A live row of the copy, opened.pubfn row(&self, table: &str, id: &str) -> Result<Option<Map<String, Value>>> { held(&self.conn(), table, id) }/// The email the database holds for a Gmail message (its API id), with its row: how the mail walk knows a/// message it need not fetch again (`mail::history`).pubfn email_by_gmail_id(&self, gmail_id: &str) -> Result<Option<(String, Map<String, Value>)>> {let found: Option<(String, String)> = self .conn() .query_row("SELECT id, data FROM rows WHERE table_id = 'email' AND deleted = 0 AND json_extract(data, '$.gmail_id') = ?1 LIMIT 1", [gmail_id], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional() .map_err(file)?;Ok(found.and_then(|(id, data)| serde_json::from_str::<Value>(&data).ok()?.as_object().cloned().map(|row| (id, row)))) }/// The email whose `external_id` is `external` (the target of a mail act the phone filed), opened.pubfn email_by_external_id(&self, external: &str) -> Result<Option<(String, Map<String, Value>)>> {let found: Option<(String, String)> = self .conn() .query_row("SELECT id, data FROM rows WHERE table_id = 'email' AND deleted = 0 AND json_extract(data, '$.external_id') = ?1 LIMIT 1", [external], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional() .map_err(file)?;Ok(found.and_then(|(id, data)| serde_json::from_str::<Value>(&data).ok()?.as_object().cloned().map(|row| (id, row)))) }/// How many live emails the conversation `thread` holds.pubfn emails_in_thread(&self, thread: &str) -> Result<u64> {self.conn() .query_row("SELECT count(*) FROM rows WHERE table_id = 'email' AND deleted = 0 AND json_extract(data, '$.thread_id') = ?1", [thread], |r| r.get::<_, i64>(0)) .map(|n| n as u64) .map_err(file) }/// How many emails the database holds: what the mail walk measures its size against.pubfn email_count(&self) -> Result<u64> {self.conn() .query_row("SELECT count(*) FROM rows WHERE table_id = 'email' AND deleted = 0", [], |r| r.get::<_, i64>(0)) .map(|n| n.max(0) as u64) .map_err(file) }/// Run `body` over a landing: it plans with the engines and applies/// what they plan to the copy, inside one transaction; then every row it/// applied goes to the object in `import_rows` calls of at most/// [`IMPORT_ROWS`], and only once the object took them all does the copy/// keep them.pubfn landing<T>(&self, object: &ObjectClient, body: implFnOnce(&mutLanding<'_>) -> Result<T>) -> Result<(T, Landed)> {// Planned and sealed over the rows as the object holds them now: a sealed row is sealed whole, so a copy read// before the batch's uploads would put back what another device changed meanwhile (an archived chat, a// draft, a mute, a person's name), and a create of an id the object made since would reset its row.self.read_up(object)?;letmut conn = self.conn();let tx = conn.transaction().map_err(file)?;let shapes = self.shapes.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();let owner_phone = self.owner_phone.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();letmut landing = Landing { tx: &tx, copy: self, shapes, owner_phone, wire: Vec::new(), landed: Landed::default() };let out = body(&mut landing)?;letLanding { wire, mut landed, .. } = landing;for chunk in import_calls(&wire) { object.import_rows(chunk)?; landed.calls += 1; } tx.commit().map_err(file)?;Ok((out, landed)) }/// Messages deleted for everyone that still keep a file (deleted means deleted, owner FEEDBACK-3): each row's/// id and the storage keys of its files (the file and its playable copy).pubfn deleted_with_files(&self) -> Result<Vec<(String, Vec<String>)>> {let conn = self.conn();letmut statement = conn .prepare("SELECT id, data FROM rows WHERE table_id = 'message' AND deleted = 0 AND COALESCE(json_extract(data, '$.deleted_at'), '') <> '' AND COALESCE(json_array_length(data, '$.media'), 0) > 0", ) .map_err(file)?;let rows = statement.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(file)?;letmut out = Vec::new();for row in rows {let (id, data) = row.map_err(file)?;let data: Value = serde_json::from_str(&data).unwrap_or(Value::Null);let keys = data["media"] .as_array() .into_iter() .flatten() .flat_map(|m| [m.get("key"), m.get("playback_key")]) .filter_map(|k| k.and_then(Value::as_str).filter(|k| !k.is_empty()).map(str::to_string)) .collect(); out.push((id, keys)); }Ok(out) }/// Whether any live message other than `except` names the storage key `key` (a file two messages share stays).pubfn file_named_elsewhere(&self, key: &str, except: &[String]) -> Result<bool> {let conn = self.conn();letmut statement = conn .prepare("SELECT r.id FROM rows r, json_each(json_extract(r.data, '$.media')) m WHERE r.table_id = 'message' AND r.deleted = 0 AND (json_extract(m.value, '$.key') = ?1 OR json_extract(m.value, '$.playback_key') = ?1)", ) .map_err(file)?;let ids = statement.query_map([key], |r| r.get::<_, String>(0)).map_err(file)?;for id in ids {if !except.contains(&id.map_err(file)?) {returnOk(true); } }Ok(false) }/// The live message row holding `external_id` on `channel`, if the copy holds one./// WhatsApp polls the copy holds as the link wrote them before build 6 (a question, no options), each with the/// next message of its chat the link wrote, newest first: at most `limit` of those never asked for or asked/// fewer than `max_tries` times and last at or before `asked_before`. Beside them, how many such polls have no/// message after them yet ([`crate::old_polls`]).pubfn bare_polls(&self, asked_before: i64, max_tries: i64, limit: usize) -> Result<(Vec<(Value, Value)>, usize)> {let conn = self.conn();let sql = "WITH bare AS ( SELECT p.data AS data, json_extract(p.data, '$.external_id') AS external_id, json_extract(p.data, '$.sent_at') AS sent_at, (SELECT n.data FROM rows n WHERE n.table_id = 'message' AND n.deleted = 0 AND json_extract(n.data, '$.thread_id') = json_extract(p.data, '$.thread_id') AND json_extract(n.data, '$.sent_at') > json_extract(p.data, '$.sent_at') AND json_type(n.data, '$.meta.source') = 'object' AND json_extract(n.data, '$.meta.source.externalId') IS NOT NULL ORDER BY json_extract(n.data, '$.sent_at') LIMIT 1) AS next FROM rows p WHERE p.table_id = 'message' AND p.deleted = 0 AND json_extract(p.data, '$.channel') = 'whatsapp' AND json_type(p.data, '$.meta.source') = 'object' AND json_extract(p.data, '$.meta.source.messageType') = 'poll' AND json_type(p.data, '$.meta.poll') IS NOT 'object') SELECT bare.data, bare.next FROM bare LEFT JOIN asked_polls a ON a.external_id = bare.external_id WHERE bare.next IS NOT NULL AND (a.external_id IS NULL OR (a.tries < ?1 AND a.at <= ?2)) ORDER BY bare.sent_at DESC LIMIT ?3";letmut stmt = conn.prepare(sql).map_err(file)?;let rows = stmt .query_map(rusqlite::params![max_tries, asked_before, limit as i64], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) .map_err(file)? .filter_map(|row| row.ok()) .filter_map(|(poll, next)| Some((serde_json::from_str(&poll).ok()?, serde_json::from_str(&next).ok()?))) .collect();let waiting: i64 = conn .query_row("SELECT count(*) FROM rows p WHERE p.table_id = 'message' AND p.deleted = 0 AND json_extract(p.data, '$.channel') = 'whatsapp' AND json_type(p.data, '$.meta.source') = 'object' AND json_extract(p.data, '$.meta.source.messageType') = 'poll' AND json_type(p.data, '$.meta.poll') IS NOT 'object' AND NOT EXISTS (SELECT 1 FROM rows n WHERE n.table_id = 'message' AND n.deleted = 0 AND json_extract(n.data, '$.thread_id') = json_extract(p.data, '$.thread_id') AND json_extract(n.data, '$.sent_at') > json_extract(p.data, '$.sent_at') AND json_type(n.data, '$.meta.source') = 'object' AND json_extract(n.data, '$.meta.source.externalId') IS NOT NULL)", [], |r| r.get(0), ) .map_err(file)?;Ok((rows, waiting as usize)) }/// The WhatsApp chats whose profile picture Cotton would take now (owner's decision, 11 Oct 2026;/// `cotton_client::ingest::profile_pictures::wanted_chats` over the copy): every person a WhatsApp contact (a/// number) is linked to whose photo is empty or still WhatsApp's, and every WhatsApp group whose picture is.pubfn wanted_pictures(&self) -> Result<std::collections::BTreeSet<String>> {let conn = self.conn();letmut wanted = std::collections::BTreeSet::new();// The contact's person is derived (who(handle), PEOPLE BUILD 1b), as the phones derive it.letmut people = conn .prepare(&format!("SELECT json_extract(c.data, '$.phone_e164'), json_extract(p.data, '$.avatar_key') FROM rows c JOIN rows p ON p.table_id = 'person' AND p.deleted = 0 AND p.id = {} WHERE c.table_id = 'message_contact' AND c.deleted = 0", contact_person("c") )) .map_err(file)?;let rows = people.query_map([], |r| Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?))).map_err(file)?;for (phone, avatar) in rows.filter_map(std::result::Result::ok) {letSome(phone) = phone.filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) else { continue };if cotton_client::ingest::profile_pictures::takes_whatsapp_picture(avatar.as_deref()) { wanted.insert(format!("{phone}{}", cotton_client::ingest::profile_pictures::PERSON_SERVER)); } }// A contact no person is (most of his WhatsApp senders): the contact's own picture (CONTRACT "WhatsApp// profile pictures": the phones draw the person's, else the contact's).letmut contacts = conn .prepare( &format!("SELECT json_extract(c.data, '$.phone_e164'), json_extract(c.data, '$.avatar_key') FROM rows c WHERE c.table_id = 'message_contact' AND c.deleted = 0 AND {} IS NULL", contact_person("c") ), ) .map_err(file)?;let rows = contacts.query_map([], |r| Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?))).map_err(file)?;for (phone, avatar) in rows.filter_map(std::result::Result::ok) {letSome(phone) = phone.filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) else { continue };if cotton_client::ingest::profile_pictures::takes_whatsapp_picture(avatar.as_deref()) { wanted.insert(format!("{phone}{}", cotton_client::ingest::profile_pictures::PERSON_SERVER)); } }letmut groups = conn .prepare("SELECT json_extract(data, '$.external_key'), json_extract(data, '$.photo_key') FROM rows WHERE table_id = 'thread' AND deleted = 0 AND json_extract(data, '$.kind') = 'group' AND json_extract(data, '$.external_key') LIKE 'wa:group:%@g.us'", ) .map_err(file)?;let rows = groups.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?))).map_err(file)?;for (key, photo) in rows.filter_map(std::result::Result::ok) {if cotton_client::ingest::profile_pictures::takes_whatsapp_picture(photo.as_deref()) {ifletSome(jid) = key.strip_prefix("wa:group:") { wanted.insert(jid.to_string()); } } }Ok(wanted) }/// Who takes the WhatsApp profile picture of `jid` now: the person its number's contact is linked to, or the/// group, each with the picture it holds; `None` for a chat no one in Cotton is, or one whose picture someone/// chose (it stays).pubfn picture_holder(&self, jid: &str, is_group: bool) -> Result<Option<PictureHolder>> {use cotton_client::ingest::profile_pictures::{takes_whatsapp_picture, PERSON_SERVER};let conn = self.conn();let found: Option<(&'static str, String, Option<String>)> = if is_group { conn.query_row("SELECT id, json_extract(data, '$.photo_key') FROM rows WHERE table_id = 'thread' AND deleted = 0 AND json_extract(data, '$.kind') = 'group' AND json_extract(data, '$.external_key') = ?1 LIMIT 1", [format!("wa:group:{jid}")], |r| Ok(("thread", r.get(0)?, r.get(1)?)), ) .optional() .map_err(file)? } else {letSome(phone) = jid.strip_suffix(PERSON_SERVER).filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) else { returnOk(None) };let person: Option<(&'static str, String, Option<String>)> = conn.query_row( &format!("SELECT p.id, json_extract(p.data, '$.avatar_key') FROM rows c JOIN rows p ON p.table_id = 'person' AND p.deleted = 0 AND p.id = {} WHERE c.table_id = 'message_contact' AND c.deleted = 0 AND json_extract(c.data, '$.phone_e164') = ?1 ORDER BY c.id LIMIT 1", contact_person("c") ), [phone], |r| Ok(("person", r.get(0)?, r.get(1)?)), ) .optional() .map_err(file)?;// No person: the contact itself takes it.match person {Some(found) => Some(found),None => conn .query_row("SELECT c.id, json_extract(c.data, '$.avatar_key') FROM rows c WHERE c.table_id = 'message_contact' AND c.deleted = 0 AND json_extract(c.data, '$.phone_e164') = ?1 ORDER BY c.id LIMIT 1", [phone], |r| Ok(("message_contact", r.get(0)?, r.get(1)?)), ) .optional() .map_err(file)?, } };Ok(found .filter(|(_, _, current)| takes_whatsapp_picture(current.as_deref())) .map(|(table, id, current)| PictureHolder { is_group, table: table.to_string(), id, current })) }/// When the newest text (iMessage or SMS) the copy holds was sent: where the Mac's texts reader starts on its/// first read ([`crate::texts`]).pubfn newest_text_at(&self) -> Result<Option<String>> {self.conn() .query_row("SELECT max(json_extract(data, '$.sent_at')) FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.channel') IN ('sms', 'imessage')", [], |r| r.get::<_, Option<String>>(0), ) .map_err(file) }/// A poll asked for again at `at` (unix seconds): one more try./// Each WhatsApp chat's oldest message the link wrote (`crate::older`), the chats active most lately first, with/// what was last asked of it: (thread, its oldest message, the id last asked before, when, how often, done).pubfn oldest_whatsapp(&self, limit: usize) -> Result<Vec<(String, Value, Option<(String, i64, i64, bool)>)>> {let conn = self.conn();let sql = "WITH linked AS ( SELECT id, data, json_extract(data, '$.thread_id') AS thread, json_extract(data, '$.sent_at') AS at FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.channel') = 'whatsapp' AND json_type(data, '$.meta.source') = 'object' AND json_extract(data, '$.meta.source.externalId') IS NOT NULL AND json_extract(data, '$.meta.source.chat') IS NOT NULL), ranked AS ( SELECT thread, data, ROW_NUMBER() OVER (PARTITION BY thread ORDER BY at, id) AS n, MAX(at) OVER (PARTITION BY thread) AS newest FROM linked) SELECT r.thread, r.data, a.before, a.at, a.tries, a.done FROM ranked r LEFT JOIN asked_older a ON a.thread_id = r.thread WHERE r.n = 1 AND r.thread IS NOT NULL AND coalesce(a.done, 0) = 0 ORDER BY r.newest DESC LIMIT ?1";letmut stmt = conn.prepare(sql).map_err(file)?;let rows = stmt .query_map([limit as i64], |r| {let asked = match r.get::<_, Option<String>>(2)? {Some(before) => Some((before, r.get::<_, i64>(3)?, r.get::<_, i64>(4)?, r.get::<_, i64>(5)? != 0)),None => None, };Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, asked)) }) .map_err(file)? .filter_map(|row| row.ok()) .filter_map(|(thread, data, asked)| Some((thread, serde_json::from_str(&data).ok()?, asked))) .collect();Ok(rows) }/// What was asked of a chat's older history: before which message, when, the how-many-th time, and whether its/// beginning is reached.pubfn asked_older(&self, thread: &str, before: &str, at: i64, tries: i64, done: bool) -> Result<()> {self.conn() .execute("INSERT INTO asked_older(thread_id, before, at, tries, done) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(thread_id) DO UPDATE SET before = ?2, at = ?3, tries = ?4, done = ?5", rusqlite::params![thread, before, at, tries, done as i64], ) .map(|_| ()) .map_err(file) }pubfn asked_poll(&self, external_id: &str, at: i64) -> Result<()> {self.conn() .execute("INSERT INTO asked_polls(external_id, at, tries) VALUES (?1, ?2, 1) ON CONFLICT(external_id) DO UPDATE SET at = ?2, tries = tries + 1", rusqlite::params![external_id, at], ) .map(|_| ()) .map_err(file) }pubfn held_message_id(&self, channel: &str, external_id: &str) -> Result<Option<String>> {self.conn() .query_row("SELECT id FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.external_id') = ?1 AND json_extract(data, '$.channel') = ?2 ORDER BY id LIMIT 1", [external_id, channel], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }}/// Who takes a WhatsApp profile picture ([`Copy::picture_holder`]): a person (their `avatar_key`) or a group's/// thread (its `photo_key`), and the picture it holds now.#[derive(Debug, Clone, PartialEq)]pubstructPictureHolder {pub is_group: bool,/// `person` (its `avatar_key`), `message_contact` (its `avatar_key`) or `thread` (a group's `photo_key`).pub table: String,pub id: String,pub current: Option<String>,}/// The most search tokens one `import_rows` call carries. Every token is a row of the object's blind index, and one/// call that wrote tens of thousands of them into a 3.7 GB object is the suspect in its CPU resets (LIVE CPU 4,/// 24 Nov 2026: the Texts catch-up's chat batches of up to 124 sealed messages, word and prefix tokens each). A call/// stays far under the 30 s a request may spend.pubconst IMPORT_TOKENS: usize = 2_000;/// `wire` cut into `import_rows` calls of at most [`IMPORT_ROWS`] rows and [`IMPORT_TOKENS`] blind tokens; a row/// with more tokens than that goes alone.pubfn import_calls(wire: &[Value]) -> Vec<&[Value]> {letmut calls = Vec::new();let (mut start, mut tokens) = (0usize, 0usize);for (i, row) in wire.iter().enumerate() {let weight = row.get("blind").and_then(Value::as_array).map_or(0, Vec::len);if i > start && (i - start >= IMPORT_ROWS || tokens + weight > IMPORT_TOKENS) { calls.push(&wire[start..i]); start = i; tokens = 0; } tokens += weight; }if start < wire.len() { calls.push(&wire[start..]); } calls}/// Whether `id` is a uuid's shape (8-4-4-4-12 hex): a random or a hashed/// id, which names nothing.use cotton_client::seal::uuid_shaped;/// A live row of the copy, opened, read through `conn`./// A message row folding in: a tombstone over a message the copy held puts its channel and id on the erased list/// (its words are not kept); a live row takes them off again (restored from the bin, or written again by the person).fn remember_erased(tx: &Connection, id: &str, deleted: bool, data: &Map<String, Value>, at: &str) -> Result<()> {let keys = |data: &Map<String, Value>| -> Option<(String, String)> {let text = |key: &str| data.get(key).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);Some((text("channel")?, text("external_id")?)) };if deleted {letSome(before) = held(tx, "message", id)? else { returnOk(()) };ifletSome((channel, external_id)) = keys(&before) { tx.execute("INSERT INTO erased(channel, external_id, at) VALUES (?1, ?2, ?3) ON CONFLICT(channel, external_id) DO NOTHING", params![channel, external_id, at], ) .map_err(file)?; } } elseifletSome((channel, external_id)) = keys(data).filter(|_| !is_erased_marker(data)) { tx.execute("DELETE FROM erased WHERE channel = ?1 AND external_id = ?2", params![channel, external_id]).map_err(file)?; }Ok(())}/// The phones' marker for an erased WhatsApp message (CONTRACT "Disappearing messages on a WhatsApp chat"): it holds/// the WhatsApp id so no import brings the message back, and is never a message brought back to life.fn is_erased_marker(data: &Map<String, Value>) -> bool { data.get("meta").and_then(|m| m.get("cotton")).and_then(|c| c.get("erased")).is_some_and(|e| !e.is_null())}fn held(conn: &Connection, table: &str, id: &str) -> Result<Option<Map<String, Value>>> {let data: Option<String> = conn .query_row("SELECT data FROM rows WHERE table_id = ?1 AND id = ?2 AND deleted = 0", [table, id], |r| r.get(0)) .optional() .map_err(file)?;Ok(data.and_then(|d| serde_json::from_str::<Value>(&d).ok()).and_then(|v| v.as_object().cloned()))}/// One landing in progress: the copy's transaction, and the rows owed to the object.pubstructLanding<'a> { tx: &'a rusqlite::Transaction<'a>, copy: &'a Copy, shapes: BTreeMap<String, Shape>, owner_phone: Option<String>, wire: Vec<Value>, landed: Landed,}implLanding<'_> {/// The owner's own number, which a code-less number is read against.pubfn owner_phone(&self) -> Option<&str> {self.owner_phone.as_deref() }/// The id of the live call this copy already holds for `(source,/// external_id)`, opened: a call imported before `call` was sealed keeps/// the id it was made under (the plain namespace), so a re-read once the/// table is sealed (and ids are made under the keyed one) lands on that/// row instead of a second one beside it.pubfn held_call(&self, source: &str, external_id: &str) -> Result<Option<String>> {self.tx .query_row("SELECT id FROM rows WHERE table_id = 'call' AND deleted = 0 AND json_extract(data, '$.source') = ?1 AND json_extract(data, '$.external_id') = ?2 ORDER BY id LIMIT 1", [source, external_id], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }/// The record a sighting from the Apple library already carries for the/// asset `asset_uuid` (the Worker's `PhotoReader.sightingRecord`).pubfn apple_sighting_record(&self, asset_uuid: &str) -> Result<Option<String>> {let found: Option<Option<String>> = self .tx .query_row("SELECT json_extract(data, '$.record_id') FROM rows WHERE table_id = 'sighting' AND deleted = 0 AND json_extract(data, '$.source') = 'apple_library' AND json_extract(data, '$.source_id') = ?1 ORDER BY created_at, id LIMIT 1", [asset_uuid], |r| Ok(text_of(r.get_ref(0)?)), ) .optional() .map_err(file)?;Ok(found.flatten()) }/// Whether the copy holds `table`'s row `id`: `Some(false)` live,/// `Some(true)` a tombstone (the owner removed it), `None` never held.pubfn held_state(&self, table: &str, id: &str) -> Result<Option<bool>> {self.tx .query_row("SELECT deleted FROM rows WHERE table_id = ?1 AND id = ?2", [table, id], |r| r.get::<_, i64>(0)) .optional() .map(|held| held.map(|deleted| deleted != 0)) .map_err(file) }/// The person an Apple face cluster's faces already point at: the/// majority, ties on the id; a binned, archived or removed person is never/// one (the Worker's `PhotoReader.majorityPerson`).pubfn cluster_majority_person(&self, cluster_uuid: &str) -> Result<Option<String>> {self.tx .query_row( &format!("SELECT p.id FROM rows f JOIN rows p ON {} AND p.id = json_extract(f.data, '$.person_id') WHERE f.table_id = 'face' AND f.deleted = 0 AND json_extract(f.data, '$.source') = 'apple' AND json_extract(f.data, '$.cluster_id') = ?1 GROUP BY p.id ORDER BY COUNT(*) DESC, p.id ASC LIMIT 1", live_person("p") ), [cluster_uuid], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }/// The live person carrying the Contacts card `contact_identifier` (the/// Worker's `PhotoReader.byContact`).pubfn person_by_device_contact(&self, contact_identifier: &str) -> Result<Option<String>> {self.tx .query_row( &format!("SELECT p.id FROM rows p WHERE {} AND json_extract(p.data, '$.device_contact_id') = ?1 ORDER BY p.created_at, p.id LIMIT 1", live_person("p")), [contact_identifier], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }/// Every live person with the name the rules compare, oldest first (the/// Worker's `PhotoReader.activePeople`).pubfn active_people(&self) -> Result<Vec<(String, Option<String>)>> {letmut statement = self .tx .prepare_cached(&format!("SELECT p.id, json_extract(p.data, '$.full_name') FROM rows p WHERE {} ORDER BY p.created_at, p.id", live_person("p"))) .map_err(file)?;let rows = statement.query_map([], |r| Ok((r.get::<_, String>(0)?, text_of(r.get_ref(1)?)))).map_err(file)?; rows.collect::<std::result::Result<Vec<_>, _>>().map_err(file) }/// The contact an original record already belongs to (`person_source`, PEOPLE BUILD 1): a record seen before/// lands on its contact even after the owner renamed or merged it. A person in the bin is nobody.pubfn person_by_source(&self, kind: &str, device: &str, source_id: &str) -> Result<Option<String>> {self.tx .query_row( &format!("SELECT p.id FROM rows s JOIN rows p ON {} AND p.id = json_extract(s.data, '$.person') WHERE s.table_id = 'person_source' AND s.deleted = 0 AND json_extract(s.data, '$.kind') = ?1 AND coalesce(json_extract(s.data, '$.device'), '') = ?2 AND json_extract(s.data, '$.source_id') = ?3 ORDER BY s.id LIMIT 1", who_person("p") ), [kind, device, source_id], |r| r.get::<_, String>(0), ) .optional() .map_err(file) }/// Whether the object's definitions hold `table`: a table a kit gained is written only once the object has it.pubfn defines(&self, table: &str) -> bool {self.shapes.contains_key(table) }/// What derived ids of `tables` are made under ([`Copy::namespace_for`]).pubfn namespace_for(&self, tables: &[&str]) -> Result<String> {self.copy.namespace_for(tables) }/// The questions the engines ask, answered over this landing's copy.pubfn asker(&self) -> CopyAsk<'_> {CopyAsk { conn: self.tx, owner_phone: self.owner_phone.as_deref() } }/// Run the messages engine's `name` (`import`, `replies`, `changes`) over/// the copy as it stands in this landing.pubfn plan(&self, name: &str, input: &Value) -> Result<Value> { asked::run(name, &input.to_string(), &self.asker()).map_err(|refused| CopyError::Engine { code: refused.code.to_string(), message: refused.words }) }/// Apply `changes` to the copy and owe them to the object: a retract as/// one; a row of a sealed table whole and sealed, its blind tokens beside/// it; any other row as the patch the engine planned.pubfn apply(&mutself, changes: &[Change]) -> Result<()> {for change in changes {self.apply_one(change, true)?; }Ok(()) }/// Apply a writer's own rows under the ids it chose (mail's, a story's):/// as [`Landing::apply`], with no id keyed.pubfn apply_as_named(&mutself, changes: &[Change]) -> Result<()> {for change in changes {self.apply_one(change, false)?; }Ok(()) }fn apply_one(&mutself, change: &Change, key_ids: bool) -> Result<()> {let shape = self.shapes.get(&change.table).cloned().ok_or_else(|| CopyError::Object(ObjectError::Refused { status: 404, code: "no_such_table".into(), message: format!("the object serves no {} table", change.table), }))?;let id = self.copy.object_id(&change.table, key_ids && shape.seal.is_some(), &change.id)?;let change = &Change { table: change.table.clone(), id, patch: change.patch.clone() };letSome(patch) = &change.patch else {self.tx .execute("UPDATE rows SET deleted = 1, data = '{}' WHERE table_id = ?1 AND id = ?2", [&change.table, &change.id]) .map_err(file)?;self.wire.push(json!({ "table": change.table, "id": change.id, "retract": true })); *self.landed.sent.entry(change.table.clone()).or_insert(0) += 1;returnOk(()); };let stamp = |key: &str| patch.get(key).and_then(Value::as_str).map(str::to_string);let (created_at, updated_at) = (stamp("created_at"), stamp("updated_at"));// The engine plans the phone's columns; the object keeps its own (as its engine's `storable` does).let columns: Map<String, Value> = patch .iter() .filter(|(key, _)| !FRAME.contains(&key.as_str()) && shape.columns.iter().any(|c| c == *key)) .map(|(k, v)| (k.clone(), v.clone())) .collect();let before = held(self.tx, &change.table, &change.id)?;if before.is_none() { *self.landed.created.entry(change.table.clone()).or_insert(0) += 1; }let wrap: Option<(String, u32)> = self .tx .query_row("SELECT dek_enc, seal_v FROM rows WHERE table_id = ?1 AND id = ?2 AND deleted = 0 AND dek_enc IS NOT NULL", [&change.table, &change.id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)), ) .optional() .map_err(file)? .map(|(d, v)| (d, u32::try_from(v).unwrap_or(0)));letmut whole = before.clone().unwrap_or_else(|| shape.defaults.clone());for (key, value) in &columns { whole.insert(key.clone(), value.clone()); }letmut row = json!({ "table": change.table, "id": change.id });letmut kept_wrap: (Option<String>, Option<i64>) = (None, None);match &shape.seal {Some(spec) if whole.get(cotton_client::seal::KEEP_OPEN) != Some(&Value::Bool(true)) => {let sealed = self .copy .sealer .seal(&change.table, &change.id, spec, &whole, wrap.as_ref().map(|(d, v)| (d.as_str(), *v))) .map_err(seal)?; kept_wrap = (Some(sealed.dek_enc.clone()), Some(i64::from(sealed.seal_v))); row["data"] = Value::Object(sealed.data); row["blind"] = json!(sealed.blind); } _ => row["data"] = Value::Object(columns), }ifletSome(at) = &created_at { row["created_at"] = json!(at); }ifletSome(at) = &updated_at { row["updated_at"] = json!(at); }self.tx .execute("INSERT INTO rows(table_id, id, data, deleted, created_at, updated_at, dek_enc, seal_v) VALUES (?1, ?2, ?3, 0, ?4, ?5, ?6, ?7) ON CONFLICT(table_id, id) DO UPDATE SET data = excluded.data, deleted = 0, updated_at = CASE WHEN excluded.updated_at <> '' THEN excluded.updated_at ELSE rows.updated_at END, created_at = CASE WHEN rows.deleted = 1 AND excluded.created_at <> '' THEN excluded.created_at ELSE rows.created_at END, dek_enc = COALESCE(excluded.dek_enc, rows.dek_enc), seal_v = COALESCE(excluded.seal_v, rows.seal_v)", params![ change.table, change.id,Value::Object(whole).to_string(), created_at.unwrap_or_default(), updated_at.unwrap_or_default(), kept_wrap.0, kept_wrap.1, ], ) .map_err(file)?;self.wire.push(row); *self.landed.sent.entry(change.table.clone()).or_insert(0) += 1;Ok(()) }}// ── the engine's questions, answered over the copy ──────────────────────────//// One method per question, each the Worker reader's own statement// (apps/business/src/import/reader.ts) over the copy's `rows`, which hold the// object's rows in the object's shape, opened./// A column read as text, or `None` when it holds none.fn text_of(value: rusqlite::types::ValueRef<'_>) -> Option<String> {match value { rusqlite::types::ValueRef::Text(t) => Some(String::from_utf8_lossy(t).into_owned()), _ => None, }}/// A person an import may name, as row `p`: held, not binned, not archived.fn live_person(p: &str) -> String { format!("{p}.table_id = 'person' AND {p}.deleted = 0 AND json_extract({p}.data, '$.trashed_at') IS NULL AND json_extract({p}.data, '$.archived_at') IS NULL")}/// A person who(handle) may name (`cotton_store::protocol::who`, PEOPLE BUILD 1b): living, neither in the bin nor/// archived (a recycled number an old contact still carries is not theirs to answer for).fn who_person(p: &str) -> String { live_person(p)}/// The living holders of the phone `phone` (an SQL expression), as a sub-select of person ids: the one holding it/// on `person_handle`, and every contact keeping it as shared (`shared_handle`, a household landline).fn phone_holders(phone: &str) -> String { format!("SELECT json_extract(hh.data, '$.person_id') AS holder FROM rows hh JOIN rows hp ON {hp} AND hp.id = json_extract(hh.data, '$.person_id') WHERE hh.table_id = 'person_handle' AND hh.deleted = 0 AND json_extract(hh.data, '$.trashed_at') IS NULL AND json_extract(hh.data, '$.kind') = 'phone' AND json_extract(hh.data, '$.normalised') = {phone} UNION SELECT json_extract(hs.data, '$.person') FROM rows hs JOIN rows sp ON {sp} AND sp.id = json_extract(hs.data, '$.person') WHERE hs.table_id = 'shared_handle' AND hs.deleted = 0 AND json_extract(hs.data, '$.kind') = 'phone' AND json_extract(hs.data, '$.normalised') = {phone}", hp = live_person("hp"), sp = live_person("sp"), )}/// A chat contact's person, DERIVED as `cotton_store::protocol::who::contact_person_sql` derives it on the phone:/// the one living person its number names; nobody for a number several contacts share; else the person it was/// linked to by hand, while living.fn contact_person(c: &str) -> String {let phone = format!("json_extract({c}.data, '$.phone_e164')"); format!("(SELECT CASE WHEN n > 1 THEN NULL WHEN n = 1 THEN one ELSE (SELECT p.id FROM rows p WHERE {live} AND p.id = json_extract({c}.data, '$.person_id')) END FROM (SELECT COUNT(*) AS n, MIN(holder) AS one FROM ({holders})))", live = live_person("p"), holders = phone_holders(&phone), )}fn live(table: &str) -> String { format!("table_id = '{table}' AND deleted = 0")}fn j(column: &str) -> String { format!("json_extract(data, '$.{column}')")}/// The engine's driver over a copy: [`asked::Ask`] answered by SQL.pubstructCopyAsk<'a> { conn: &'a Connection, owner_phone: Option<&'a str>,}typeBound = Vec<rusqlite::types::Value>;fn text(value: &str) -> rusqlite::types::Value { rusqlite::types::Value::Text(value.to_string())}implCopyAsk<'_> {fn all(&self, sql: &str, bound: Bound, columns: &[&str]) -> std::result::Result<Vec<Map<String, Value>>, String> {letmut statement = self.conn.prepare_cached(sql).map_err(|e| e.to_string())?;let rows = statement .query_map(rusqlite::params_from_iter(bound), |r| {letmut out = Map::new();for (i, name) in columns.iter().enumerate() {let value = match r.get_ref(i)? { rusqlite::types::ValueRef::Null => Value::Null, rusqlite::types::ValueRef::Integer(n) => json!(n), rusqlite::types::ValueRef::Real(f) => json!(f), rusqlite::types::ValueRef::Text(t) => Value::String(String::from_utf8_lossy(t).into_owned()), rusqlite::types::ValueRef::Blob(_) => Value::Null, }; out.insert((*name).to_string(), value); }Ok(out) }) .map_err(|e| e.to_string())?; rows.collect::<std::result::Result<Vec<_>, _>>().map_err(|e| e.to_string()) }fn first(&self, sql: &str, bound: Bound, columns: &[&str]) -> std::result::Result<Value, String> {Ok(self.all(sql, bound, columns)?.into_iter().next().map_or(Value::Null, Value::Object)) }fn owner_region(&self) -> Option<String> {let phone = cotton_rules::phone::normalize_phone(self.owner_phone?)?; cotton_rules::phone::region_of(&phone).map(|region| AsRef::<str>::as_ref(®ion).to_string()) }}fn arg<'a>(args: &'a Value, field: &str) -> std::result::Result<&'a str, String> { args[field].as_str().ok_or_else(|| format!("the question carries no {field}"))}fn ids(args: &Value) -> std::result::Result<String, String> {if !args["ids"].is_array() {returnErr("the question carries no ids".into()); }Ok(args["ids"].to_string())}/// A JSON column read through `json_extract` comes back as text: parsed.fn parsed(value: &Value) -> Value {match value {Value::String(text) => serde_json::from_str(text).unwrap_or_else(|_| value.clone()), other => other.clone(), }}implAskforCopyAsk<'_> {fn ask(&self, question: &str, args: Value) -> std::result::Result<Value, String> {let msg = live("message");match question {"people_handles" => Ok(Value::Array(self.all( &format!("SELECT p.id, json_extract(p.data, '$.full_name'), json_extract(h.data, '$.normalised') FROM rows h JOIN rows p ON {} AND p.id = json_extract(h.data, '$.person_id') WHERE h.table_id = 'person_handle' AND h.deleted = 0 AND json_extract(h.data, '$.trashed_at') IS NULL AND json_extract(h.data, '$.kind') = ?1 UNION ALL SELECT p.id, json_extract(p.data, '$.full_name'), json_extract(s.data, '$.normalised') FROM rows s JOIN rows p ON {} AND p.id = json_extract(s.data, '$.person') WHERE s.table_id = 'shared_handle' AND s.deleted = 0 AND json_extract(s.data, '$.kind') = ?1", who_person("p"), who_person("p") ), vec![text(arg(&args, "kind")?)], &["id", "full_name", "value"], )? .into_iter() .map(Value::Object) .collect(), )),"contact_by_handle" => self.first( &format!("SELECT c.id, json_extract(c.data, '$.display_name'), {} FROM rows h JOIN rows c ON c.table_id = 'message_contact' AND c.deleted = 0 AND c.id = json_extract(h.data, '$.contact_id') WHERE h.table_id = 'message_contact_handle' AND h.deleted = 0 AND json_extract(h.data, '$.value') = ? AND json_extract(h.data, '$.kind') = ? ORDER BY h.created_at, h.id LIMIT 1", contact_person("c") ), vec![text(arg(&args, "value")?), text(arg(&args, "kind")?)], &["id", "display_name", "person_id"], ),"contact_by_phone" => self.first( &format!("SELECT c.id, json_extract(c.data, '$.display_name'), {} FROM rows c WHERE c.table_id = 'message_contact' AND c.deleted = 0 AND json_extract(c.data, '$.phone_e164') = ? ORDER BY c.created_at, c.id LIMIT 1", contact_person("c") ), vec![text(arg(&args, "phone")?)], &["id", "display_name", "person_id"], ),"dm_thread_for_contact" => Ok(self .first( &format!("SELECT id FROM rows WHERE {} AND {} = ? AND {} = 'dm' ORDER BY created_at, id LIMIT 1", live("thread"), j("contact_id"), j("kind")), vec![text(arg(&args, "contact_id")?)], &["id"], )? .get("id") .cloned() .unwrap_or(Value::Null)),"thread_by_id" => self.first( &format!("SELECT id, {} FROM rows WHERE {} AND id = ? AND {} = ?", j("contact_id"), live("thread"), j("kind")), vec![text(arg(&args, "id")?), text(arg(&args, "kind")?)], &["id", "contact_id"], ),"known_external_ids" => Ok(Value::Array(self.all( &format!("SELECT {} FROM rows WHERE {msg} AND {} IN (SELECT value FROM json_each(?)) AND {} = ? AND {} = ?", j("external_id"), j("external_id"), j("thread_id"), j("channel") ), vec![text(&ids(&args)?), text(arg(&args, "thread_id")?), text(arg(&args, "channel")?)], &["external_id"], )? .into_iter() .map(|r| r["external_id"].clone()) .collect(), )),"thread_stats" => {let r = self.first( &format!("SELECT COUNT(*), MIN({}), MAX({}) FROM rows WHERE {msg} AND {} = ? AND {} = ?", j("sent_at"), j("sent_at"), j("thread_id"), j("channel")), vec![text(arg(&args, "thread_id")?), text(arg(&args, "channel")?)], &["n", "oldest", "newest"], )?;Ok(json!({ "count": r["n"].as_i64().unwrap_or(0), "oldestSentAt": r["oldest"], "newestSentAt": r["newest"] })) }"group_thread_by_key" => self.first( &format!("SELECT id, {} FROM rows WHERE {} AND {} = ? AND {} = 'group' ORDER BY created_at, id LIMIT 1", j("title"), live("thread"), j("external_key"), j("kind")), vec![text(arg(&args, "external_key")?)], &["id", "title"], ),"jid_group_threads" => Ok(Value::Array(self.all( &format!("SELECT id, {} FROM rows WHERE {} AND {} = 'group' AND {} LIKE 'wa:group:%@g.us'", j("title"), live("thread"), j("kind"), j("external_key")), vec![], &["id", "title"], )? .into_iter() .map(Value::Object) .collect(), )),"thread_by_overlap" => {let r = self.first("SELECT json_extract(m.data, '$.thread_id') AS thread_id, json_extract(t.data, '$.contact_id'), COUNT(*) AS n FROM rows m JOIN rows t ON t.table_id = 'thread' AND t.deleted = 0 AND t.id = json_extract(m.data, '$.thread_id') WHERE m.table_id = 'message' AND m.deleted = 0 AND json_extract(m.data, '$.external_id') IN (SELECT value FROM json_each(?)) AND json_extract(t.data, '$.kind') = ? AND json_extract(m.data, '$.channel') = ? GROUP BY thread_id ORDER BY n DESC LIMIT 1", vec![text(&ids(&args)?), text(arg(&args, "kind")?), text(arg(&args, "channel")?)], &["thread_id", "contact_id", "matched"], )?;Ok(r) }"participants_of" => Ok(Value::Array(self.all( &format!("SELECT id, {}, {} FROM rows WHERE {} AND {} = ? ORDER BY created_at, id", j("contact_id"), j("display_name"), live("thread_member"), j("thread_id")), vec![text(arg(&args, "thread_id")?)], &["id", "contact_id", "display_name"], )? .into_iter() .map(Value::Object) .collect(), )),"thread_last_message_at" => self.first( &format!("SELECT {} FROM rows WHERE {} AND id = ?", j("last_message_at"), live("thread")), vec![text(arg(&args, "thread_id")?)], &["at"], ),"thread_external_key" => Ok(self .first(&format!("SELECT {} FROM rows WHERE {} AND id = ?", j("external_key"), live("thread")), vec![text(arg(&args, "thread_id")?)], &["key"])? .get("key") .cloned() .unwrap_or(Value::Null)),"unlinked_replies" => Ok(Value::Array(self.all( &format!("SELECT id, {} FROM rows WHERE {msg} AND {} = ? AND {} IS NULL AND {} IS NOT NULL ORDER BY created_at, id", j("reply_to_external_id"), j("thread_id"), j("reply_to_id"), j("reply_to_external_id") ), vec![text(arg(&args, "thread_id")?)], &["id", "reply_to_external_id"], )? .into_iter() .map(Value::Object) .collect(), )),"messages_by_external_ids" => Ok(Value::Array(self.all( &format!("SELECT id, {} FROM rows WHERE {msg} AND {} IN (SELECT value FROM json_each(?)) AND {} = ? AND {} = ? ORDER BY created_at, id", j("external_id"), j("external_id"), j("thread_id"), j("channel") ), vec![text(&ids(&args)?), text(arg(&args, "thread_id")?), text(arg(&args, "channel")?)], &["id", "external_id"], )? .into_iter() .map(Value::Object) .collect(), )),"held_without_media" => Ok(Value::Array(self.all( &format!("SELECT id, {}, {}, json_extract(data, '$.meta') FROM rows WHERE {msg} AND {} IN (SELECT value FROM json_each(?)) AND {} = ? AND {} = ? AND {} IS NULL AND COALESCE(json_array_length(data, '$.media'), 0) = 0 ORDER BY created_at, id", j("external_id"), j("body"), j("external_id"), j("thread_id"), j("channel"), j("deleted_at") ), vec![text(&ids(&args)?), text(arg(&args, "thread_id")?), text(arg(&args, "channel")?)], &["id", "external_id", "body", "meta"], )? .into_iter() .map(Value::Object) .collect(), )),"real_id_bodies_in_minute" => {let minute = arg(&args, "minute")?;Ok(Value::Array(self.all( &format!("SELECT {} FROM rows WHERE {msg} AND {} = ? AND {} >= ? || ':00' AND {} < ? || ':60' AND {} = ? AND {} IS NOT NULL AND {} NOT LIKE 'txt2:%' AND {} IS NOT NULL ORDER BY {}, id", j("body"), j("thread_id"), j("sent_at"), j("sent_at"), j("channel"), j("external_id"), j("external_id"), j("body"), j("sent_at") ), vec![text(arg(&args, "thread_id")?), text(minute), text(minute), text(arg(&args, "channel")?)], &["body"], )? .into_iter() .map(|r| r["body"].clone()) .collect(), )) }"rows_in_minute" => {let minute = arg(&args, "minute")?;Ok(Value::Array(self.all( &format!("SELECT id, {}, {}, {}, json_extract(data, '$.meta') FROM rows WHERE {msg} AND {} = ? AND {} >= ? || ':00' AND {} < ? || ':60' AND {} = ? ORDER BY {}, id", j("external_id"), j("direction"), j("body"), j("thread_id"), j("sent_at"), j("sent_at"), j("channel"), j("sent_at") ), vec![text(arg(&args, "thread_id")?), text(minute), text(minute), text(arg(&args, "channel")?)], &["id", "external_id", "direction", "body", "meta"], )? .into_iter() .map(Value::Object) .collect(), )) }"message_by_external_id" => {let r = self.first("SELECT m.id, json_extract(m.data, '$.thread_id'), json_extract(m.data, '$.meta'), json_extract(m.data, '$.media'), (json_extract(t.data, '$.last_message_at') IS json_extract(m.data, '$.sent_at')) FROM rows m LEFT JOIN rows t ON t.table_id = 'thread' AND t.deleted = 0 AND t.id = json_extract(m.data, '$.thread_id') WHERE m.table_id = 'message' AND m.deleted = 0 AND json_extract(m.data, '$.external_id') = ? AND json_extract(m.data, '$.channel') = ? ORDER BY json_extract(m.data, '$.sent_at') DESC LIMIT 1", vec![text(arg(&args, "external_id")?), text(arg(&args, "channel")?)], &["id", "thread_id", "meta", "media", "newest"], )?;if r.is_null() {returnOk(Value::Null); }let meta = parsed(&r["meta"]);let media = parsed(&r["media"]);Ok(json!({"id": r["id"],"thread_id": r["thread_id"].as_str().unwrap_or_default(),"meta": if meta.is_object() { meta } else { json!({}) },"media": if media.is_array() { media } else { json!([]) },"newest": r["newest"].as_i64() == Some(1), })) }// One database is one object here, as on the Worker: no workspace row holds self names."self_names_json" => Ok(Value::Null),"owner_region" => Ok(self.owner_region().map_or(Value::Null, Value::String)),"new_id" => Ok(Value::String(uuid_v4())), other => Err(format!("the importer's copy does not answer {other}")), } }}/// A fresh random id, uuid-shaped.pubfn uuid_v4() -> String { cotton_client::seams::uuid_v4(&cotton_client::seams::SystemRandom)}// ── plain writes to sealed tables ────────────────────────────────────────────/// What turns the Mac's plain row writes (mail, stories, the outbox's marks)/// into sealed ones (sealing plan L8): an [`ObjectClient`] carrying a door/// sends `create`, `update` and `delete` on a table the object seals through/// the copy instead, the row sealed whole over what the copy holds of it, its/// blind tokens beside it; a write to an open table goes as it always did./// One door per pass: the object's definitions and rows are read once, the/// first time a write needs them.pubstructSealDoor { open: Box<dynFn() -> std::result::Result<Arc<Copy>, String> + Send + Sync>, copy: std::sync::OnceLock<Arc<Copy>>, refreshed: std::sync::atomic::AtomicBool,/// The tables the object's definitions seal, read once per door: a pass/// that writes only open tables never opens the copy. sealed: std::sync::OnceLock<std::collections::BTreeSet<String>>,}impl std::fmt::DebugforSealDoor {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SealDoor").finish_non_exhaustive() }}fn refused(status: u16, code: &str, message: String) -> ObjectError {ObjectError::Refused { status, code: code.to_string(), message }}/// A copy's refusal as the object's kind: a seal refusal keeps its code with/// status 0 (nothing reached the object; the write waits for the next pass).fn as_object(error: CopyError) -> ObjectError {match error {CopyError::Object(error) => error,CopyError::Seal { code, message } | CopyError::Engine { code, message } => refused(0, &code, message),CopyError::File(message) => refused(0, "copy_unreadable", message), }}implSealDoor {/// A door over the copy `open` opens on first need.pubfn new(open: implFn() -> std::result::Result<Arc<Copy>, String> + Send + Sync + 'static) -> Arc<SealDoor> {Arc::new(SealDoor { open: Box::new(open), copy: std::sync::OnceLock::new(), refreshed: std::sync::atomic::AtomicBool::new(false), sealed: std::sync::OnceLock::new() }) }/// A door over `copy` as it stands.pubfn over(copy: Arc<Copy>) -> Arc<SealDoor> {let door = SealDoor::new(|| Err("the copy is already open".into()));let _ = door.copy.set(copy); door }/// The copy as it stands, opened on first need (its sealer opens a row with the DK alone).fn held_copy(&self) -> std::result::Result<&Arc<Copy>, ObjectError> {Ok(matchself.copy.get() {Some(copy) => copy,None => {let copy = (self.open)().map_err(|why| refused(0, "copy_unreadable", why))?;self.copy.get_or_init(|| copy) } }) }/// The copy, brought up to the object once per door.fn copy(&self, object: &ObjectClient) -> std::result::Result<&Arc<Copy>, ObjectError> {let copy = self.held_copy()?;if !self.refreshed.swap(true, std::sync::atomic::Ordering::SeqCst) {ifletErr(error) = copy.refresh(object) {self.refreshed.store(false, std::sync::atomic::Ordering::SeqCst);returnErr(as_object(error)); } }Ok(copy) }/// `act` on `table`, sealed, when the object seals `table`; `None` when it/// does not (the caller sends it as it is). The answer mirrors the/// object's refusals: a create on a held id is `409 duplicate_id`, an/// update or delete of a row the copy does not hold `404 no_such_record`,/// a key the table has no column for `400 bad_column`.pubfn act(&self, object: &ObjectClient, act: crate::object::Act, table: &str, id: &str, data: &Value) -> std::result::Result<Option<Value>, ObjectError> {if !self.seals(object, table)? {returnOk(None); }let copy = self.copy(object)?;// A sealed row is sealed whole: `Copy::landing` reads the copy up to the object before the patch is laid,// never over the copy this door read first (a film job's second write, an hour on, sealed back an old track// list, FILMS TRUE 25 Nov 2026).letmut held = copy.row(table, id).map_err(as_object)?;if held.is_none() && act != crate::object::Act::Create {// A row made since this door's refresh (the phone queued a send// meanwhile): the copy reads up to the object once more first. copy.refresh(object).map_err(as_object)?; held = copy.row(table, id).map_err(as_object)?; }let patch = match act {crate::object::Act::Delete => {if held.is_none() {returnErr(refused(404, "no_such_record", format!("no {table} {id}"))); }None }crate::object::Act::Create | crate::object::Act::Update => {if act == crate::object::Act::Create && held.is_some() {returnErr(refused(409, "duplicate_id", format!("{table} {id} is held already"))); }if act == crate::object::Act::Update && held.is_none() {returnErr(refused(404, "no_such_record", format!("no {table} {id}"))); }let patch = data.as_object().cloned().unwrap_or_default();ifletSome(stray) = patch.keys().find(|key| !copy.has_column(table, key)) {returnErr(refused(400, "bad_column", format!("{table} has no column {stray:?}"))); }Some(patch) } };let change = Change { table: table.to_string(), id: id.to_string(), patch };let ((), landed) = copy.landing(object, |landing| landing.apply_as_named(std::slice::from_ref(&change))).map_err(as_object)?;Ok(Some(json!({ "sealed": true, "calls": landed.calls }))) }/// Whether the object's definitions seal `table`, read once per door.fn seals(&self, object: &ObjectClient, table: &str) -> std::result::Result<bool, ObjectError> {ifletSome(sealed) = self.sealed.get() {returnOk(sealed.contains(table)); }let served = object.definitions()?;letmut sealed = std::collections::BTreeSet::new();for definition in served["tables"].as_array().into_iter().flatten() {if definition.get("seal").is_some_and(|s| !s.is_null()) { sealed.insert(definition["id"].as_str().unwrap_or_default().to_string()); } }Ok(self.sealed.get_or_init(|| sealed).contains(table)) }/// Every live row of `table` as the object holds it now, read over/// `/v1/sync` as a device may (the object's `/mcp` takes tokens, never a/// device's sign-in) and opened here when sealed: each `{ id, data }`./// One row of `table` as the object holds it now, opened: the copy read up (one sync from its cursor) and the/// row read from it. What a long run decides "only if empty" on just before it writes (STALE WRITES 2).pubfn row_now(&self, object: &ObjectClient, table: &str, id: &str) -> std::result::Result<Option<Map<String, Value>>, ObjectError> {let copy = self.copy(object)?; copy.read_up(object).map_err(as_object)?; copy.row(table, id).map_err(as_object) }pubfn rows(&self, object: &ObjectClient, table: &str) -> std::result::Result<Vec<Value>, ObjectError> {letmut held: BTreeMap<String, Option<Value>> = BTreeMap::new();letmut cursor: Option<String> = None;loop {let page = object.sync_page(0, &[table], cursor.as_deref())?;for row in page["rows"].as_array().into_iter().flatten() {if row["table"].as_str() != Some(table) {continue; }letSome(id) = row["id"].as_str() else { continue };let live = row.get("deleted") != Some(&Value::Bool(true)) && row["data"].is_object(); held.insert(id.to_string(), live.then(|| json!({ "id": id, "data": row["data"] }))); }match page.get("next").and_then(Value::as_str) {Some(next) => cursor = Some(next.to_string()),None => break, } }self.open_listed(object, table, held.into_values().flatten().collect()) }/// One live row of `table` by its id, opened when sealed: `{ id, data }`,/// or `None` when the object holds no live row by that id. Read over/// `/v1/sync` from `since` (a version before the row's last change, as/// `GET /v1/films/subtitles/asked` names it; 0 reads the table whole) and/// opened with the DK alone, never bringing the whole copy up nor opening/// any other row (17 Nov 2026: `rows` opened both/// film tables whole to read one film, ten minutes a table).pubfn row(&self, object: &ObjectClient, table: &str, id: &str, since: i64) -> std::result::Result<Option<Value>, ObjectError> {letmut found: Option<Value> = None;letmut cursor: Option<String> = None;loop {let page = object.sync_page(since.max(0), &[table], cursor.as_deref())?;for row in page["rows"].as_array().into_iter().flatten() {if row["table"].as_str() != Some(table) || row["id"].as_str() != Some(id) {continue; }let live = row.get("deleted") != Some(&Value::Bool(true)) && row["data"].is_object(); found = live.then(|| row["data"].clone()); }match page.get("next").and_then(Value::as_str) {Some(next) => cursor = Some(next.to_string()),None => break, } }letSome(Value::Object(data)) = found else { returnOk(None) };let data = if stored_row::is_sealed(&data) { self.held_copy()?.open_served(table, id, &data).map_err(as_object)? } else { data };Ok(Some(json!({ "id": id, "data": data }))) }/// Rows a list route served (the outbox's), each opened when sealed: a/// row whose seal does not open stops the list by name.pubfn open_listed(&self, object: &ObjectClient, table: &str, rows: Vec<Value>) -> std::result::Result<Vec<Value>, ObjectError> {if !rows.iter().any(|row| row.get("data").and_then(Value::as_object).or_else(|| row.as_object()).is_some_and(stored_row::is_sealed)) {returnOk(rows); }// Opened with the DK alone, as `row` opens one: bringing the whole copy up// to open a list pulled every table of the object (ten minutes a table on// the owner's, and its load answered 500 to uploads in flight, 18 Nov 2026).let _ = object;let copy = self.held_copy()?; rows.into_iter() .map(|mut row| {let id = row["id"].as_str().unwrap_or_default().to_string();ifletSome(data) = row.get("data").and_then(Value::as_object).filter(|d| stored_row::is_sealed(d)) { row["data"] = Value::Object(copy.open_served(table, &id, data).map_err(as_object)?); } elseifletSome(flat) = row.as_object().filter(|r| stored_row::is_sealed(r)) {letmut opened = copy.open_served(table, &id, flat).map_err(as_object)?; opened.insert("id".into(), Value::String(id)); row = Value::Object(opened); }Ok(row) }) .collect() }}