941 lines · 43.8 KB · RustRaw
//! The app's one object: sign-in, the sources, their threads, and the status//! the popover draws. The FFI is JSON over [`App::call`].//!//! Each source runs on its own thread: it sleeps until its schedule is due,//! a card's click asks for a run now, or the app stops; a paused source only//! wakes for resume. A run that the object answers 401 signs the app out —//! the token is forgotten here and Swift drops it from the keychain.use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Condvar, Mutex, RwLock};use std::thread::JoinHandle;use std::time::{Duration, Instant};use serde::Deserialize;use serde_json::{json, Value};use crate::importer::{Importer, Probe, Progress, RunContext, RunError, SourceKey};use crate::object::{DeviceFacts, ObjectClient, ObjectError};use crate::sink::ObjectSink;use crate::store::Store;use crate::vault::{ImporterVault, Keyring, Pass, VaultLine};/// What Swift hands the core at launch.#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Config { /// `~/Library/Application Support/Cotton`. pub data_dir: PathBuf, /// The open host, `https://cottondb.com`. pub object_url: String, /// This install's device id, the one sign-in binds the token to. pub device_id: String, /// This Mac's name, for provenance on the rows its readers write. pub machine: String, /// The name the person gave this Mac ("Asha's Mac mini"): its device /// row's name on the object. pub device_name: String, /// The running app's version, as its device row says it. pub app_version: String, /// The person's home, where the sources live. pub home: PathBuf, /// `Contents/Helpers` of the running app: the WhatsApp helper and the /// Chrome broker. #[serde(default)] pub helpers_dir: Option<PathBuf>,}impl Config { pub fn importer_db(&self) -> PathBuf { self.data_dir.join("importer.db") }}#[derive(Debug, Default)]struct SlotState { running: bool, run_now: bool, /// `bringAgain`: the next run reads the source from its start (the cursor forgotten, nothing erased). again: bool, /// The run under way reads the source from its start (a `bringAgain`): the page says so until it ends. again_running: bool, progress: Progress, probe: Option<Probe>, probed_at: Option<Instant>,}struct Slot { importer: Box<dyn Importer>, state: Mutex<SlotState>, wake: Condvar, cancel: AtomicBool,}struct Inner { config: Config, store: Store, object: RwLock<ObjectClient>, phone: RwLock<Option<String>>, database_id: RwLock<Option<String>>, slots: Vec<Arc<Slot>>, stopping: AtomicBool, signed_out: AtomicBool, /// Where this Mac's vault key lives: the login Keychain on a Mac. keyring: Box<dyn Keyring>, /// One vault pass at a time, so two sources' threads never mint two keys. vault_pass: Mutex<()>, /// What the last vault pass found, for the popover. Never a key. vault_line: Mutex<Option<VaultLine>>, /// The database's data key, opened by a vault pass from the object's /// `seal_key` row with the VMK and held in memory only: the Mac's /// Keychain already holds what opens it again on every pass. data_keys: Arc<cotton_client::seal::HeldDataKeys>, /// The importer's own copy (`copy.db`), which messages are decided over; /// opened once the database is known. copy: Mutex<Option<Arc<crate::copy::Copy>>>, /// This Mac's device key, whose public half is its device id /// ([`crate::approval`]): the app's own; a test or a tool runs without. device: Option<crate::approval::DeviceKey>, /// The approval ask this Mac stands on, while the sign-in screen shows it. asking: Mutex<Option<crate::approval::Asking>>, /// Why this Mac was signed out, in words for the sign-in screen. sign_in_note: Mutex<Option<String>>, /// When this Mac last looked to hand Your Claude's grants their keys ([`crate::hand`]), and the object version /// it looks for changes from: `None` until the first open vault pass after launch, which always looks. hand_at: Mutex<(Option<Instant>, Option<i64>)>,}/// How often a vault pass looks for a grant or a key version that changed, at most ([`crate::hand`]): each source/// passes every few minutes, and a look that finds nothing changed is one small read.pub const HAND_EVERY: Duration = Duration::from_secs(60);/// What the sign-in screen says when a credential this Mac kept was minted/// for the device id it had before its device key (an app from before 22 Nov/// 2026), so nothing it holds would be let into the vault.pub const NOTE_NEW_IDENTITY: &str = "Sign in again: this Mac now signs in with a key of its own. Then scan the code it shows from a Cotton app on your phone, and this Mac opens your things in the same step.";/// What the sign-in screen says after the object refused this Mac's sign-in (401).pub const NOTE_SIGNED_OUT: &str = "Cotton signed this Mac out. Sign in again with your number and the code we text you.";pub struct App { inner: Arc<Inner>, threads: Mutex<Vec<JoinHandle<()>>>,}fn now() -> String { cotton_client::seams::iso(chrono::Utc::now())}const PROBE_TTL: Duration = Duration::from_secs(5);impl App { /// Open the importer over `importers`, in card order, keeping its vault /// key in `keyring` ([`crate::vault::system_keyring`] in the app). Threads /// start at [`App::start`], once a token is in hand. pub fn open(config: Config, importers: Vec<Box<dyn Importer>>, keyring: Box<dyn Keyring>) -> Result<App, String> { App::open_as(config, importers, keyring, None) } /// [`App::open`] as the device `device` is: its public half becomes the /// config's device id, the one every sign-in, device row and vault row /// names ([`crate::approval`]). The app's entry point opens so. pub fn open_as(mut config: Config, importers: Vec<Box<dyn Importer>>, keyring: Box<dyn Keyring>, device: Option<crate::approval::DeviceKey>) -> Result<App, String> { if let Some(device) = &device { config.device_id = device.id(); } let store = Store::open(&config.importer_db()).map_err(|e| e.to_string())?; let object = ObjectClient::new(config.object_url.clone(), None).map_err(|e| e.to_string())?; let database_id = store.fact("database_id").map_err(|e| e.to_string())?; let phone = store.fact("phone").map_err(|e| e.to_string())?; let slots = importers .into_iter() .map(|importer| { Arc::new(Slot { importer, state: Mutex::new(SlotState::default()), wake: Condvar::new(), cancel: AtomicBool::new(false), }) }) .collect(); Ok(App { inner: Arc::new(Inner { config, store, object: RwLock::new(object), phone: RwLock::new(phone), database_id: RwLock::new(database_id), slots, stopping: AtomicBool::new(false), signed_out: AtomicBool::new(false), keyring, vault_pass: Mutex::new(()), vault_line: Mutex::new(None), data_keys: cotton_client::seal::HeldDataKeys::new(), copy: Mutex::new(None), device, asking: Mutex::new(None), sign_in_note: Mutex::new(None), hand_at: Mutex::new((None, None)), }), threads: Mutex::new(Vec::new()), }) } pub fn config(&self) -> &Config { &self.inner.config } /// One JSON method, for the FFI. Answers `{ ok: true, … }` or /// `{ ok: false, error, code? }`. pub fn call(&self, method: &str, args: &Value) -> Value { let answer = match method { "status" => Ok(self.status()), "askCode" => self.ask_code(args), "signIn" => self.sign_in(args), "start" => self.start_with(args), "signOut" => { self.sign_out(); Ok(json!({})) } "openByCode" => self.open_by_code(args), "askApproval" => self.ask_approval(args), "askPoll" => self.ask_poll(), "askCancel" => { *self.inner.asking.lock().unwrap_or_else(|p| p.into_inner()) = None; Ok(json!({})) } "runNow" => self.with_slot(args, |slot| { let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.run_now = true; slot.wake.notify_all(); Ok(json!({})) }), "bringAgain" => self.with_slot(args, |slot| { // A run under way ends first, so its cursor cannot land after the reset; the next run resets it. slot.cancel.store(true, Ordering::SeqCst); let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.again = true; state.run_now = true; slot.wake.notify_all(); Ok(json!({})) }), "pause" => self.set_paused(args, true), "resume" => self.set_paused(args, false), "command" => self.with_slot(args, |slot| { let name = args.get("name").and_then(Value::as_str).unwrap_or(""); let result = slot.importer.command(name, args.get("args").unwrap_or(&Value::Null)); // The person let a source go (WhatsApp unlinked on the panel): the panel offers it as Add, never as // a problem, until it is set up again. if result.is_ok() && name == "unlink" { let _ = self.inner.store.set_fact(&let_go_fact(slot.importer.key()), Some(&chrono::Utc::now().to_rfc3339())); } // What a command changed (credentials, a pairing) shows at once. slot.state.lock().unwrap_or_else(|p| p.into_inner()).probed_at = None; result.map_err(|e| (e, None)) }), "stop" => { self.stop(); Ok(json!({})) } other => Err((format!("unknown method {other}"), Some("unknown_method".to_string()))), }; match answer { Ok(Value::Object(mut map)) => { map.insert("ok".to_string(), Value::Bool(true)); Value::Object(map) } Ok(other) => json!({ "ok": true, "value": other }), Err((error, code)) => json!({ "ok": false, "error": error, "code": code }), } } fn with_slot( &self, args: &Value, f: impl FnOnce(&Arc<Slot>) -> Result<Value, (String, Option<String>)>, ) -> Result<Value, (String, Option<String>)> { let key = args .get("source") .and_then(Value::as_str) .and_then(SourceKey::parse) .ok_or_else(|| ("no such source".to_string(), Some("bad_source".to_string())))?; let slot = self .inner .slots .iter() .find(|slot| slot.importer.key() == key) .ok_or_else(|| ("no such source".to_string(), Some("bad_source".to_string())))?; f(slot) } fn set_paused(&self, args: &Value, paused: bool) -> Result<Value, (String, Option<String>)> { let store = &self.inner.store; self.with_slot(args, |slot| { store .set_paused(slot.importer.key().as_str(), paused) .map_err(|e| (e.to_string(), None))?; if paused { slot.cancel.store(true, Ordering::SeqCst); } // As in `stop`: the lock first, so the loop cannot miss this. drop(slot.state.lock().unwrap_or_else(|p| p.into_inner())); slot.wake.notify_all(); Ok(json!({})) }) } fn object_error(error: ObjectError) -> (String, Option<String>) { let code = match &error { ObjectError::SignedOut => Some("signed_out".to_string()), ObjectError::Refused { code, .. } => Some(code.clone()), ObjectError::Transport(_) | ObjectError::File(_) => Some("offline".to_string()), ObjectError::Decode(_) => Some("bad_answer".to_string()), }; (error.to_string(), code) } fn ask_code(&self, args: &Value) -> Result<Value, (String, Option<String>)> { let phone = args.get("phone").and_then(Value::as_str).unwrap_or("").trim().to_string(); let object = self.inner.object.read().unwrap_or_else(|p| p.into_inner()).with_token(None); let asked = object .ask_code(&phone, &self.inner.config.device_id) .map_err(Self::object_error)?; Ok(json!({ "challengeId": asked.challenge_id, "databaseId": asked.database_id })) } /// The code, for the token. Swift keeps the credential in the keychain /// and calls `start` with it, now and at every launch. fn sign_in(&self, args: &Value) -> Result<Value, (String, Option<String>)> { let database = args.get("databaseId").and_then(Value::as_str).unwrap_or(""); let challenge = args.get("challengeId").and_then(Value::as_str).unwrap_or(""); let code = args.get("code").and_then(Value::as_str).unwrap_or("").trim(); let object = self.inner.object.read().unwrap_or_else(|p| p.into_inner()).with_token(None); let signed = object .sign_in(database, challenge, code, &self.inner.config.device_id) .map_err(Self::object_error)?; let phone = signed.person.get("phone").and_then(Value::as_str).map(str::to_string); self.signed_in(&signed.database_id); Ok(json!({ "credential": signed.credential, "phone": phone })) } /// A sign-in landed: the database it names, and the device it was minted for. fn signed_in(&self, database_id: &str) { let _ = self.inner.store.set_fact("database_id", Some(database_id)); let _ = self.inner.store.set_fact("signed_in_device", Some(&self.inner.config.device_id)); *self.inner.database_id.write().unwrap_or_else(|p| p.into_inner()) = Some(database_id.to_string()); *self.inner.sign_in_note.lock().unwrap_or_else(|p| p.into_inner()) = None; } /// `askApproval { phone }`: ask to be approved from a phone already signed /// in to `phone` ([`crate::approval`]), naming this Mac's device key and /// vault key. Answers the card the sign-in screen draws. fn ask_approval(&self, args: &Value) -> Result<Value, (String, Option<String>)> { let inner = &self.inner; let device = inner.device.as_ref().ok_or_else(|| ("this Mac has no device key to ask with".to_string(), Some("device_key_unreadable".to_string())))?; // From the not-let-in panel no number is typed: the number this Mac signed in with. let typed = args.get("phone").and_then(Value::as_str).unwrap_or("").trim().to_string(); let phone = if typed.is_empty() { inner.phone.read().unwrap_or_else(|p| p.into_inner()).clone().unwrap_or_default() } else { typed }; let vault = ImporterVault::new(inner.keyring.as_ref(), &inner.config.device_id, &inner.config.device_name); // Without a vault key the ask signs in only; the vault then waits for the recovery code. let vault_public = vault.public_key().ok(); let object = inner.object.read().unwrap_or_else(|p| p.into_inner()).with_token(None); let asking = crate::approval::ask(&object, device, &phone, &inner.config.device_name, vault_public.as_deref()).map_err(Self::object_error)?; let card = crate::approval::card(&asking, &crate::approval::Polled::Waiting { code: None }); *inner.asking.lock().unwrap_or_else(|p| p.into_inner()) = Some(asking); Ok(card) } /// `askPoll`: where this Mac's ask stands. Approved, the credential is /// claimed and answered with the card, for Swift to keep and `start` with. fn ask_poll(&self) -> Result<Value, (String, Option<String>)> { let inner = &self.inner; let device = inner.device.as_ref().ok_or_else(|| ("this Mac has no device key to ask with".to_string(), Some("device_key_unreadable".to_string())))?; let Some(mut asking) = inner.asking.lock().unwrap_or_else(|p| p.into_inner()).clone() else { return Ok(crate::approval::lost()); }; let object = inner.object.read().unwrap_or_else(|p| p.into_inner()).with_token(None); let polled = crate::approval::poll(&object, device, &mut asking).map_err(Self::object_error)?; let mut card = crate::approval::card(&asking, &polled); match &polled { crate::approval::Polled::Approved { credential, database_id, person } => { self.signed_in(database_id); // Let in by the same approval: every source looks at once (Swift starts with the credential next). wake_all(inner); let phone = person.get("phone").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| asking.phone.clone()); card["credential"] = Value::String(credential.clone()); card["phone"] = Value::String(phone); *inner.asking.lock().unwrap_or_else(|p| p.into_inner()) = None; } crate::approval::Polled::Ended { .. } => *inner.asking.lock().unwrap_or_else(|p| p.into_inner()) = None, crate::approval::Polled::Waiting { .. } => *inner.asking.lock().unwrap_or_else(|p| p.into_inner()) = Some(asking), } Ok(card) } /// The recovery code, typed once (e2e rulings R7c): this Mac opens the /// vault with it and becomes a device of it, with no phone at hand. The /// code is used and dropped; the popover's line says what it found. fn open_by_code(&self, args: &Value) -> Result<Value, (String, Option<String>)> { let code = args.get("code").and_then(Value::as_str).unwrap_or(""); let inner = &self.inner; let object = inner.object.read().unwrap_or_else(|p| p.into_inner()).clone(); if !object.signed_in() { return Err(("sign in first".to_string(), Some("signed_out".to_string()))); } { let _one = inner.vault_pass.lock().unwrap_or_else(|p| p.into_inner()); let vault = ImporterVault::new(inner.keyring.as_ref(), &inner.config.device_id, &inner.config.device_name); vault.open_by_code(&object, &object, code).map_err(|error| match error { crate::vault::VaultError::Object(error) => Self::object_error(error), crate::vault::VaultError::Code(code) => (error.to_string(), Some(code.to_string())), other => (other.to_string(), Some("recovery_refused".to_string())), })?; } if inner.database_id.read().unwrap_or_else(|p| p.into_inner()).is_none() { let _ = database_id(inner, &object); } vault_pass(inner, &object); // Every source may send now. wake_all(inner); Ok(json!({ "vault": inner.vault_line.lock().unwrap_or_else(|p| p.into_inner()).clone() })) } fn start_with(&self, args: &Value) -> Result<Value, (String, Option<String>)> { let token = args .get("token") .and_then(Value::as_str) .filter(|t| !t.is_empty()) .ok_or_else(|| ("start needs the token".to_string(), Some("bad_request".to_string())))?; if let Some(phone) = args.get("phone").and_then(Value::as_str) { let _ = self.inner.store.set_fact("phone", Some(phone)); *self.inner.phone.write().unwrap_or_else(|p| p.into_inner()) = Some(phone.to_string()); } // A credential kept from before this Mac had its device key names another device: the object would never // let this one into the vault with it. The person signs in again, told why. if self.inner.device.is_some() { let minted_for = self.inner.store.fact("signed_in_device").ok().flatten(); if minted_for.as_deref() != Some(self.inner.config.device_id.as_str()) { *self.inner.sign_in_note.lock().unwrap_or_else(|p| p.into_inner()) = Some(NOTE_NEW_IDENTITY.to_string()); forget_token(&self.inner); return Err((NOTE_NEW_IDENTITY.to_string(), Some("signed_out".to_string()))); } } self.start(token.to_string()); Ok(json!({})) } /// Hold `token` and start every source's thread (once). pub fn start(&self, token: String) { { let mut object = self.inner.object.write().unwrap_or_else(|p| p.into_inner()); *object = object.with_token(Some(token)); } self.inner.signed_out.store(false, Ordering::SeqCst); let mut threads = self.threads.lock().unwrap_or_else(|p| p.into_inner()); if !threads.is_empty() { // A new sign-in (an approval from a phone, say): every source runs at once, its vault pass first. wake_all(&self.inner); return; } for slot in &self.inner.slots { let inner = Arc::clone(&self.inner); let slot = Arc::clone(slot); let name = format!("cotton-{}", slot.importer.key().as_str()); let handle = std::thread::Builder::new() .name(name) .spawn(move || run_loop(inner, slot)) .expect("spawn a source thread"); threads.push(handle); } // A source that hears its input change between runs asks for a run // now; its watcher ends when the app stops. The wake holds the slot // weakly, since the slot holds the importer that keeps the wake. for slot in &self.inner.slots { let held = Arc::downgrade(slot); let wake: Arc<dyn Fn() + Send + Sync> = Arc::new(move || { if let Some(slot) = held.upgrade() { slot.state.lock().unwrap_or_else(|p| p.into_inner()).run_now = true; slot.wake.notify_all(); } }); let inner = Arc::downgrade(&self.inner); let stopping: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(move || inner.upgrade().is_none_or(|inner| inner.stopping.load(Ordering::SeqCst))); slot.importer.watch(wake, stopping); } } pub fn sign_out(&self) { forget_token(&self.inner); // The person signed out themselves: nothing to explain. *self.inner.sign_in_note.lock().unwrap_or_else(|p| p.into_inner()) = None; } pub fn stop(&self) { self.inner.stopping.store(true, Ordering::SeqCst); for slot in &self.inner.slots { slot.cancel.store(true, Ordering::SeqCst); // Taken before the notify: the run loop holds this lock from its // `stopping` check to its wait, so a notify sent between the two // would be lost and an hourly source would sleep its hour out. drop(slot.state.lock().unwrap_or_else(|p| p.into_inner())); slot.wake.notify_all(); slot.importer.stop(); } let threads: Vec<JoinHandle<()>> = std::mem::take(&mut *self.threads.lock().unwrap_or_else(|p| p.into_inner())); for handle in threads { let _ = handle.join(); } } /// What the popover draws. pub fn status(&self) -> Value { let inner = &self.inner; let object = inner.object.read().unwrap_or_else(|p| p.into_inner()); let sources: Vec<Value> = inner .slots .iter() .map(|slot| { let key = slot.importer.key(); let record = inner.store.record(key.as_str()).unwrap_or_default(); let probe = cached_probe(slot); let state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); let phase = if record.paused { "paused" } else if state.running { "running" } else if !probe.ready { "needs" } else if record.last_error.is_some() { "error" } else { "idle" }; json!({ "source": key.as_str(), "schedule": slot.importer.schedule().label(), "phase": phase, "probe": probe, "progress": if state.running { serde_json::to_value(state.progress).unwrap_or(Value::Null) } else { Value::Null }, "lastBrought": record.last_brought, "lastBroughtAt": record.last_brought_at, "lastRunAt": record.last_run_at, "total": record.total, "error": record.last_error, }) }) .collect(); // The panel as the person sees it (crate::panel): its screen, headline and rows. let records: Vec<(crate::store::SourceRecord, Probe, bool, Option<Progress>, bool, bool)> = inner .slots .iter() .map(|slot| { let record = inner.store.record(slot.importer.key().as_str()).unwrap_or_default(); let state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); let running = state.running; let progress = running.then_some(state.progress); let again = state.again || state.again_running; drop(state); let probe = cached_probe(slot); let key = let_go_fact(slot.importer.key()); // Set up again: the person's letting go is over. let let_go = match inner.store.fact(&key).ok().flatten() { Some(_) if probe.ready => { let _ = inner.store.set_fact(&key, None); false } held => held.is_some(), }; (record, probe, running, progress, let_go, again) }) .collect(); let vault = inner.vault_line.lock().unwrap_or_else(|p| p.into_inner()).clone(); let phone = inner.phone.read().unwrap_or_else(|p| p.into_inner()).clone(); let panel = crate::panel::panel(&crate::panel::PanelFacts { signed_in: object.signed_in(), vault: vault.as_ref().map(|line| line.state), phone: phone.as_deref(), rows: inner .slots .iter() .zip(&records) .map(|(slot, (record, probe, running, progress, let_go, again))| crate::panel::RowFacts { key: slot.importer.key(), let_go: *let_go, again: *again, paused: record.paused, running: *running, progress: *progress, probe, total: record.total, last_brought_at: record.last_brought_at.as_deref(), last_error: record.last_error.as_deref(), history: (slot.importer.key() == crate::importer::SourceKey::Mail) .then(|| crate::panel::History::of_cursor(record.cursor.as_deref())) .flatten(), }) .collect(), now: chrono::Utc::now(), }); json!({ "panel": panel, "signedIn": object.signed_in(), "signedOut": inner.signed_out.load(Ordering::SeqCst), "host": object.host(), "phone": *inner.phone.read().unwrap_or_else(|p| p.into_inner()), "lastPushAt": inner.store.fact("last_push_at").ok().flatten(), "sources": sources, // `waiting` until the phone approves this Mac, then `open`. "vault": inner.vault_line.lock().unwrap_or_else(|p| p.into_inner()).clone(), // Why this Mac was signed out, for the sign-in screen; none while signed in. "signInNote": inner.sign_in_note.lock().unwrap_or_else(|p| p.into_inner()).clone(), "askButton": inner.device.as_ref().map(|_| crate::approval::ask_button()), }) }}impl Drop for App { fn drop(&mut self) { self.stop(); }}fn cached_probe(slot: &Slot) -> Probe { { let state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); if let (Some(probe), Some(at)) = (&state.probe, state.probed_at) { if at.elapsed() < PROBE_TTL { return probe.clone(); } } } let probe = slot.importer.probe(); let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.probe = Some(probe.clone()); state.probed_at = Some(Instant::now()); probe}fn forget_token(inner: &Inner) { { let mut note = inner.sign_in_note.lock().unwrap_or_else(|p| p.into_inner()); if note.is_none() { *note = Some(NOTE_SIGNED_OUT.to_string()); } } let mut object = inner.object.write().unwrap_or_else(|p| p.into_inner()); *object = object.with_token(None); inner.signed_out.store(true, Ordering::SeqCst); for slot in &inner.slots { slot.cancel.store(true, Ordering::SeqCst); }}/// The database id every media key starts with, asked once and kept.fn database_id(inner: &Inner, object: &ObjectClient) -> Result<String, RunError> { if let Some(id) = inner.database_id.read().unwrap_or_else(|p| p.into_inner()).clone() { return Ok(id); } let id = object.database_id()?; let _ = inner.store.set_fact("database_id", Some(&id)); *inner.database_id.write().unwrap_or_else(|p| p.into_inner()) = Some(id.clone()); Ok(id)}/// The longest a source waits after runs that failed in a row.pub const RETRY_CEILING: Duration = Duration::from_secs(10 * 60);/// How long a source waits before its next run: its own interval, doubled for/// each run in a row that failed (refused by the object, or it could not be/// reached), at most [`RETRY_CEILING`]. A refusal does not heal in five/// seconds, and every retry reads and sends the same page again — WhatsApp's/// helper fetching its media from WhatsApp each time — so a failing source/// slows down instead of spending the network on it. A run that lands resets/// it; the card's run-now runs at once whatever the wait./// How soon a source tries again while its rows wait for this Mac to be let in: the approval can come at any moment/// (a phone, a recovery code), and nothing is gained by waiting ten minutes for it (owner at the Mac, 22 Nov 2026)./// The fact that says the person let `source` go on the panel.fn let_go_fact(source: SourceKey) -> String { format!("let_go.{}", source.as_str())}pub const VAULT_RETRY: Duration = Duration::from_secs(30);/// The wait before a source's next run: its schedule, doubled per failure up to [`RETRY_CEILING`], and never above/// [`VAULT_RETRY`] while the last run only waited for the vault.pub fn next_run_after(interval: Duration, failures: u32, waiting_for_vault: bool) -> Duration { let after = retry_after(interval, failures); if waiting_for_vault { after.min(VAULT_RETRY.max(interval)) } else { after }}/// Every source runs now: this Mac was just let in, or signed in anew.fn wake_all(inner: &Inner) { for slot in &inner.slots { slot.state.lock().unwrap_or_else(|p| p.into_inner()).run_now = true; slot.wake.notify_all(); }}pub fn retry_after(interval: Duration, failures: u32) -> Duration { if failures == 0 { return interval; } interval.saturating_mul(1 << failures.min(20)).min(RETRY_CEILING.max(interval))}fn run_loop(inner: Arc<Inner>, slot: Arc<Slot>) { let key = slot.importer.key(); let every = slot.importer.schedule().interval(); let mut last_run: Option<Instant> = None; // Runs in a row that ended `Failed`. let mut failures: u32 = 0; loop { let waiting = inner.store.record(key.as_str()).ok().and_then(|r| r.last_error).as_deref() == Some(crate::importer::WAITS_FOR_THE_VAULT); let interval = next_run_after(every, failures, waiting); // Wait until due, asked, or stopping. { let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); loop { if inner.stopping.load(Ordering::SeqCst) { return; } let paused = inner.store.record(key.as_str()).map(|r| r.paused).unwrap_or(false); let signed_in = inner.object.read().unwrap_or_else(|p| p.into_inner()).signed_in(); let due = last_run.is_none_or(|at| at.elapsed() >= interval); if signed_in && !paused && (state.run_now || due) { state.run_now = false; break; } let wait = match last_run { Some(at) if signed_in && !paused => interval.saturating_sub(at.elapsed()).max(Duration::from_millis(50)), _ => Duration::from_secs(5), }; state = slot.wake.wait_timeout(state, wait).unwrap_or_else(|p| p.into_inner()).0; } } last_run = Some(Instant::now()); let probe = slot.importer.probe(); { let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.probe = Some(probe.clone()); state.probed_at = Some(Instant::now()); } if !probe.ready { let object = inner.object.read().unwrap_or_else(|p| p.into_inner()).clone(); // What a waiting source tells the object (a todo, a passkey's use) goes sealed like a pass's writes. let object = match database_id(&inner, &object) { Ok(database_id) => sealing(&inner, &object, &database_id), Err(_) => object, }; if let Err(ObjectError::SignedOut) = slot.importer.while_needed(&object) { forget_token(&inner); } continue; } if run_once(&inner, &slot) { failures = 0; } else { failures = failures.saturating_add(1); } }}/// One run; `false` when it failed (the object refused, or could not be reached).fn run_once(inner: &Arc<Inner>, slot: &Slot) -> bool { let key = slot.importer.key(); slot.cancel.store(false, Ordering::SeqCst); { let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.running = true; state.progress = Progress::default(); } let object = inner.object.read().unwrap_or_else(|p| p.into_inner()).clone(); // Every pass names this Mac, quiet or not, so the object files its device row. let named = |database_id: String| { object.name_device(&DeviceFacts { name: inner.config.device_name.clone(), platform: "mac".to_string(), app_version: inner.config.app_version.clone(), })?; // Every pass reads this Mac's own vault key row too: it publishes the // key the first time and opens the vault once the phone approves. vault_pass(inner, &object); Ok::<_, RunError>(database_id) }; let result = database_id(inner, &object).and_then(named).and_then(|database_id| { let object = sealing(inner, &object, &database_id); let copy_for = database_id.clone(); let copy_for_count = database_id.clone(); let sink = ObjectSink::new(&object, database_id).with_copy_opener(move || copy_of(inner, ©_for)); let on_progress = |progress: Progress| { slot.state.lock().unwrap_or_else(|p| p.into_inner()).progress = progress; }; let again = { let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); let again = std::mem::take(&mut state.again); state.again_running = again; again }; if again { let _ = inner.store.forget_cursor(key.as_str()); } let cursor = inner.store.cursor(key.as_str()).ok().flatten(); let mut ctx = RunContext::new(&sink, &inner.store, key, &slot.cancel, &on_progress); let answer = slot.importer.run(cursor.as_deref(), &mut ctx); let sent = ctx.progress().sent; if answer.is_ok() { recount(inner, ©_for_count, key, again); } answer.map(|cursor| (cursor, sent)) }); let brought = slot.state.lock().unwrap_or_else(|p| p.into_inner()).progress.brought; let landed = !matches!(result, Err(RunError::Failed(_))); match result { Ok((cursor, _)) => { let _ = inner.store.advance(key.as_str(), Some(&cursor), 0, &now()); let _ = inner.store.finish(key.as_str(), brought, None, &now()); } Err(RunError::Paused) => { let _ = inner.store.finish(key.as_str(), brought, None, &now()); } Err(RunError::SignedOut) => { forget_token(inner); let _ = inner.store.finish(key.as_str(), brought, None, &now()); } Err(RunError::Failed(error)) => { let _ = inner.store.finish(key.as_str(), brought, Some(&error), &now()); } } let mut state = slot.state.lock().unwrap_or_else(|p| p.into_inner()); state.running = false; state.again_running = false; landed}/// The fact that says a source's count was set from the copy once (build 5): before it, the count added every row/// a batch carried (a picture and its sighting) and everything sent again.fn counted_fact(source: SourceKey) -> String { format!("counted.{}", source.as_str())}/// After a run that read the source from its start, and once for a count added up by an older build: the source's/// count becomes what the importer's copy really holds from it (no request: what this Mac lands is in the copy). A/// source the copy does not hold (Mail), or a copy never brought up to the object, keeps its count, to be tried/// again after the next run.fn recount(inner: &Inner, database_id: &str, key: SourceKey, again: bool) { let fact = counted_fact(key); if !again && inner.store.fact(&fact).ok().flatten().is_some() { return; } let Ok(copy) = copy_of(inner, database_id) else { return }; let Ok(Some(held)) = copy.held_from(key.as_str()) else { return }; if inner.store.set_total(key.as_str(), held).is_ok() { let _ = inner.store.set_fact(&fact, Some(&chrono::Utc::now().to_rfc3339())); }}/// `object` as a device that seals: every plain write to a sealed table goes/// sealed through the copy, and a person's files leave this Mac sealed with/// the data key the vault pass holds (e2e rulings R2, R6).fn sealing(inner: &Arc<Inner>, object: &ObjectClient, database_id: &str) -> ObjectClient { let (door_inner, door_for) = (Arc::clone(inner), database_id.to_string()); let object = object.sealing_with(crate::copy::SealDoor::new(move || copy_of(&door_inner, &door_for))); let keys: Arc<dyn cotton_client::seal::DataKeyStore> = inner.data_keys.clone(); object.sealing_files(Arc::new(cotton_client::media::sealed::PersonFiles::new(database_id.to_string(), keys)))}/// The importer's copy of `database_id`, opened once and kept.fn copy_of(inner: &Inner, database_id: &str) -> Result<Arc<crate::copy::Copy>, String> { let mut held = inner.copy.lock().unwrap_or_else(|p| p.into_inner()); if let Some(copy) = held.as_ref().filter(|copy| copy.database_id() == database_id) { return Ok(Arc::clone(copy)); } let keys: Arc<dyn cotton_client::seal::DataKeyStore> = inner.data_keys.clone(); let copy = Arc::new( crate::copy::Copy::open(&inner.config.data_dir.join("copy.db"), database_id, keys).map_err(|error| error.to_string())?, ); *held = Some(Arc::clone(©)); Ok(copy)}/// With the vault open, the database's data key from its `seal_key` row/// `dk`, held for the importer's seals; nothing while the phone has minted/// none yet (a sealed table's write then waits, by name).fn hold_data_key(inner: &Inner, object: &ObjectClient, vault: &crate::vault::OpenVault) -> Result<(), String> { let Some(database_id) = inner.database_id.read().unwrap_or_else(|p| p.into_inner()).clone() else { return Ok(()) }; let page = object.sync_page(0, &[cotton_client::seal::SEAL_KEY_TABLE], None).map_err(|e| e.to_string())?; let row = page["rows"] .as_array() .into_iter() .flatten() .find(|row| row["table"] == cotton_client::seal::SEAL_KEY_TABLE && row["id"] == cotton_client::seal::DK_ROW && row.get("deleted") != Some(&Value::Bool(true))); // The vault is open and no data key was ever made: a phone makes it at its first sign-in. let Some(data) = row.and_then(|row| row["data"].as_object()) else { return Err("This Mac opens your vault, but your account has no data key yet: open a Cotton app on your phone once.".to_string()); }; let dk = vault.data_key(data).map_err(|e| format!("{}: {e}", e.code()))?; inner.data_keys.hold(&database_id, &dk); Ok(())}/// One vault pass ([`crate::vault`]): what it found becomes the popover's/// line; the opened key is dropped as the pass ends. A pass that cannot finish/// says why there and never fails the source's run.fn vault_pass(inner: &Inner, object: &ObjectClient) { let _one = inner.vault_pass.lock().unwrap_or_else(|p| p.into_inner()); let vault = ImporterVault::new(inner.keyring.as_ref(), &inner.config.device_id, &inner.config.device_name); let line = match vault.pass(object) { Ok(Pass::Open(open)) => match hold_data_key(inner, object, &open) { Ok(()) => { hand_keys(inner, object); Pass::Open(open).line(&vault.fingerprint().unwrap_or_default()) } Err(detail) => VaultLine { state: "trouble", fingerprint: None, detail, ask: Some(crate::approval::ask_button()), sign_out: Some(crate::vault::SIGN_OUT.to_string()) }, }, Ok(pass) => { let fingerprint = match &pass { Pass::Waiting { fingerprint } => fingerprint.clone(), Pass::Open(_) => vault.fingerprint().unwrap_or_default(), }; pass.line(&fingerprint) } Err(error) => VaultLine { state: "trouble", fingerprint: None, detail: error.to_string(), ask: Some(crate::approval::ask_button()), sign_out: Some(crate::vault::SIGN_OUT.to_string()) }, }; *inner.vault_line.lock().unwrap_or_else(|p| p.into_inner()) = Some(line);}/// With the data key held: hand every live grant to your Claude the keys it covers and this Mac has not handed/// ([`crate::hand`]), at the first open vault pass after launch, then on a pass at most every [`HAND_EVERY`] when a/// grant or a key version changed. Counts only in the log; a hand-over that could not finish is asked again at the/// next due pass and never fails the source's run.fn hand_keys(inner: &Inner, object: &ObjectClient) { let since = { let mut at = inner.hand_at.lock().unwrap_or_else(|p| p.into_inner()); if at.0.is_some_and(|at| at.elapsed() < HAND_EVERY) { return; } at.0 = Some(Instant::now()); at.1 }; let Some(database_id) = inner.database_id.read().unwrap_or_else(|p| p.into_inner()).clone() else { return }; let keys: Arc<dyn cotton_client::seal::DataKeyStore> = inner.data_keys.clone(); match crate::hand::hand(object, &database_id, &keys, &inner.store, since) { Ok(pass) => { if pass.looked && (since.is_none() || pass.handed.grants > 0 || pass.handed.refused > 0) { eprintln!("{}", pass.handed.line()); } // No data key yet: the first look is still to come, and says its line. if pass.looked || since.is_some() { inner.hand_at.lock().unwrap_or_else(|p| p.into_inner()).1 = Some(pass.next_since); } } Err(error) => eprintln!("hand: not this pass ({error})"), }}/// The importers this Mac runs, in card order.pub fn importers(config: &Config) -> Vec<Box<dyn Importer>> { crate::sources::all(config)}