//! A source, as the app runs it: what it is, when it wakes, whether this Mac//! can read it, and one run past its cursor.//!//! The readers `cotton-client` already has (`IngestSource`: call history,//! Photos, the WhatsApp helper) run through [`IngestImporter`]; a source that//! writes plain rows (Mail) implements [`Importer`] itself and sends//! through [`RunContext::upsert`].use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::Duration;use cotton_client::ingest::{IngestBatch, IngestNotes, IngestSource, SourceState};use serde::Serialize;use serde_json::Value;usecrate::object::{ObjectClient, ObjectError};usecrate::sink::{ObjectSink, SinkError};usecrate::store::Store;/// The cards, in the order the popover draws them.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]#[serde(rename_all = "lowercase")]pubenumSourceKey {Whatsapp,Mail,Photos,Calls,Texts,}implSourceKey {pubconst ALL: [SourceKey; 5] = [SourceKey::Whatsapp,SourceKey::Mail,SourceKey::Photos,SourceKey::Calls,SourceKey::Texts, ];pubconstfn as_str(self) -> &'static str {matchself {SourceKey::Whatsapp => "whatsapp",SourceKey::Mail => "mail",SourceKey::Photos => "photos",SourceKey::Calls => "calls",SourceKey::Texts => "texts", } }pubfn parse(value: &str) -> Option<SourceKey> {SourceKey::ALL.into_iter().find(|key| key.as_str() == value) }}/// When a source wakes on its own.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumSchedule {/// As its input fills: polled this often, and a run is cheap when there/// is nothing new (WhatsApp's helper outbox).Continuous(Duration),/// Every so often (Mail also keeps IDLE open between these).Every(Duration),}implSchedule {pubfn interval(self) -> Duration {matchself {Schedule::Continuous(every) | Schedule::Every(every) => every, } }pubfn label(self) -> String {matchself {Schedule::Continuous(_) => "Continuous".to_string(),Schedule::Every(every) => {let minutes = every.as_secs() / 60;if minutes >= 60 && minutes % 60 == 0 {if minutes == 60 {"Hourly".to_string() } else { format!("Every {} h", minutes / 60) } } else { format!("Every {minutes} min") } } } }}/// What a source needs from the person before it can read.#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(tag = "kind", rename_all = "camelCase")]pubenumNeed {/// Photos and Calls: the System Settings pane, which no app can grant.FullDiskAccess,/// WhatsApp: link a number, by a code typed into WhatsApp (first) or a/// QR it scans. `by` is the pairing under way (`"code"` or `"qr"`),/// `None` until the person picks one; `code` and `qr` are the helper's,/// `None` while it is still asking WhatsApp. `passkey` is WhatsApp's/// passkey step once it asks for one: `asking` (Chrome shows the sheet),/// `retry` (Chrome could not ask; `detail` says why), `sent`, `confirm`/// (`confirm` is the code the phone shows too) and `linking`.Pair { by: Option<String>, code: Option<String>, qr: Option<String>, passkey: Option<String>, confirm: Option<String>, },/// Mail: the address and an app password, kept in the Mac's/// keychain and never sent to the object.Credentials,}#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(rename_all = "camelCase")]pubstructProbe {pub ready: bool, #[serde(skip_serializing_if = "Option::is_none")]pub need: Option<Need>,/// One sentence, when there is something to say. #[serde(skip_serializing_if = "Option::is_none")]pub detail: Option<String>,}implProbe {pubfn ready() -> Probe {Probe { ready: true, need: None, detail: None } }pubfn needs(need: Need) -> Probe {Probe { ready: false, need: Some(need), detail: None } }pubfn unavailable(detail: implInto<String>) -> Probe {Probe { ready: false, need: None, detail: Some(detail.into()) } }}/// What a run has done so far, drawn inside the card.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pubstructProgress {/// The source's things the object has taken this run (its progress).pub sent: i64,/// Of those, the ones new at the object: what the run adds to the source's count.pub brought: i64,/// Files put this run.pub uploaded: i64,/// How many rows the source holds, when it could say. #[serde(skip_serializing_if = "Option::is_none")]pub total: Option<i64>,}#[derive(Debug, thiserror::Error, PartialEq)]pubenumRunError {/// The person paused it, or the app is quitting: the cursor stays where/// the last whole batch left it. #[error("paused")]Paused,/// The object no longer takes the token. #[error("signed out")]SignedOut, #[error("{0}")]Failed(String),}/// What a source's card says while its rows wait for the data key: this Mac/// is not let in to the person's data yet (the vault line above says how),/// so nothing went up, in the clear or otherwise, and nothing is dropped.pubconst WAITS_FOR_THE_VAULT: &str = "Waiting until this Mac is let in to your data (see above). Nothing is lost: it is sent then.";implFrom<SinkError> forRunError {fn from(error: SinkError) -> RunError {let waits = |code: Option<&str>| code == Some(cotton_client::seal::SEAL_KEY_MISSING);match error {SinkError::Object(ObjectError::SignedOut) => RunError::SignedOut,SinkError::Object(ref object) if waits(object.code()) => RunError::Failed(WAITS_FOR_THE_VAULT.to_string()),SinkError::Copy(ref copy) if waits(copy.code()) => RunError::Failed(WAITS_FOR_THE_VAULT.to_string()), other => RunError::Failed(other.to_string()), } }}implFrom<ObjectError> forRunError {fn from(error: ObjectError) -> RunError {RunError::from(SinkError::Object(error)) }}/// One run's seam to the object and to the cursor store.pubstructRunContext<'a> {pub sink: &'a ObjectSink<'a>, store: &'a Store, source: SourceKey, cancel: &'a AtomicBool, on_progress: &'a (dynFn(Progress) + Sync), progress: Progress, notes: IngestNotes,/// Set when a send failed inside a reader's emit, which only carries a/// string back: the run answers this rather than the reader's wrapping. failure: Option<RunError>,}impl<'a> RunContext<'a> {pubfn new( sink: &'a ObjectSink<'a>, store: &'a Store, source: SourceKey, cancel: &'a AtomicBool, on_progress: &'a (dynFn(Progress) + Sync), ) -> RunContext<'a> {RunContext { sink, store, source, cancel, on_progress, progress: Progress::default(), notes: IngestNotes::new(), failure: None, } }pubfn cancelled(&self) -> bool {self.cancel.load(Ordering::SeqCst) }pubfn check(&self) -> Result<(), RunError> {ifself.cancelled() {Err(RunError::Paused) } else {Ok(()) } }pubfn progress(&self) -> Progress {self.progress }pubfn notes(&self) -> &IngestNotes { &self.notes }pubfn set_total(&mutself, total: Option<i64>) {self.progress.total = total; (self.on_progress)(self.progress); }fn now() -> String { cotton_client::seams::iso(chrono::Utc::now()) }/// Rows are at the object, every one new: count them and, when given, move the cursor (Mail's own rows).pubfn brought(&mutself, rows: i64, uploaded: i64, cursor: Option<&str>) -> Result<(), RunError> {self.brought_new(rows, rows, uploaded, cursor) }/// `rows` of the source's things are at the object, `new` of them new there: the run's progress moves by/// `rows`, the source's count by `new` only, and the cursor when given.pubfn brought_new(&mutself, rows: i64, new: i64, uploaded: i64, cursor: Option<&str>) -> Result<(), RunError> {self.store .advance(self.source.as_str(), cursor, new, &Self::now()) .map_err(|e| RunError::Failed(e.to_string()))?;if rows > 0 {let _ = self.store.set_fact("last_push_at", Some(&Self::now())); }self.progress.sent += rows;self.progress.brought += new;self.progress.uploaded += uploaded; (self.on_progress)(self.progress);Ok(()) }/// One reader batch to the object.pubfn send(&mutself, batch: IngestBatch) -> Result<(), RunError> {self.check()?;let cursor = batch.cursor.clone();let sent = self.sink.send(batch)?;for (key, value) in sent.notes { *self.notes.entry(key).or_insert(0) += value; }self.brought_new(sent.rows, sent.new, sent.uploaded, cursor.as_deref()) }/// One plain row by its own id (create, or update when it is there),/// said as an import's: the object logs only that it happened.pubfn upsert(&mutself, table: &str, id: &str, data: &Value) -> Result<(), RunError> {self.check()?;self.sink.object().upsert_as(table, id, data, true)?;Ok(()) }/// The emit callback a reader takes: a failure is kept here, typed, and/// the reader is handed a string to stop on.pubfn emit(&mutself, batch: IngestBatch) -> Result<(), String> {matchself.send(batch) {Ok(()) => Ok(()),Err(error) => {let text = error.to_string();self.failure = Some(error);Err(text) } } }/// The run's answer when a reader stopped on an error: the typed one an/// emit kept, else the reader's own.pubfn failed(&mutself, reader_error: String) -> RunError {self.failure.take().unwrap_or(RunError::Failed(reader_error)) }}/// One source.pubtraitImporter: Send + Sync {fn key(&self) -> SourceKey;fn schedule(&self) -> Schedule;/// Can this Mac read it right now? Cheap: the popover calls it often.fn probe(&self) -> Probe;/// Read past `cursor`, sending as it goes, and answer the new cursor.fn run(&self, cursor: Option<&str>, ctx: &mutRunContext<'_>) -> Result<String, RunError>;/// What the card asks of this source: `credentials`, `openChrome`, …/// Most sources have none.fn command(&self, name: &str, _args: &Value) -> Result<Value, String> {Err(format!("{} takes no {name}", self.key().as_str())) }/// Called once when the app starts its sources: a source that can hear/// its input change between runs (Mail's IDLE) watches on its own thread,/// calls `wake` to ask for a run now, and ends when `stopping` answers/// true. Most sources only run on their schedule.fn watch(&self, _wake: Arc<dynFn() + Send + Sync>, _stopping: Arc<dynFn() -> bool + Send + Sync>) {}/// The app is stopping: end what this source started outside the/// process (WhatsApp's helper), and start nothing again. Called before/// the source threads are joined, so a run still finishing cannot hold/// it up. Most sources start nothing.fn stop(&self) {}/// Called on each pass the source cannot run because it needs the person/// (its probe is not ready), signed in: what it must tell the owner's/// object while it waits (WhatsApp files a todo to link it again). Most/// sources have nothing to say.fn while_needed(&self, _object: &ObjectClient) -> Result<(), ObjectError> {Ok(()) }}/// A `cotton-client` reader, run against the object.pubstructIngestImporter<S: IngestSource + Sync> { key: SourceKey, schedule: Schedule, source: S,/// What a `not_found` from the reader asks of the person (WhatsApp's is/// pairing); `None` when it only means "nothing here". not_found_need: Option<Need>,}impl<S: IngestSource + Sync> IngestImporter<S> {pubfn new(key: SourceKey, schedule: Schedule, source: S) -> IngestImporter<S> {IngestImporter { key, schedule, source, not_found_need: None, } }pubfn when_not_found(mutself, need: Need) -> IngestImporter<S> {self.not_found_need = Some(need);self }pubfn source(&self) -> &S { &self.source }}impl<S: IngestSource + Sync> ImporterforIngestImporter<S> {fn key(&self) -> SourceKey {self.key }fn schedule(&self) -> Schedule {self.schedule }fn probe(&self) -> Probe {let status = self.source.probe();match status.state {SourceState::Ready => Probe::ready(),SourceState::NoPermission => Probe { ready: false, need: Some(Need::FullDiskAccess), detail: status.detail, },SourceState::NotFound => match &self.not_found_need {Some(need) => Probe { ready: false, need: Some(need.clone()), detail: status.detail },None => Probe::unavailable(status.detail.unwrap_or_else(|| "Nothing to read on this Mac.".to_string())), },SourceState::Error => Probe::unavailable(status.detail.unwrap_or_else(|| "The source could not be read.".to_string())), } }fn run(&self, cursor: Option<&str>, ctx: &mutRunContext<'_>) -> Result<String, RunError> {let outcome = {letmut emit = |batch: IngestBatch| ctx.emit(batch);self.source.read(cursor, &mut emit) };match outcome {Ok(outcome) => Ok(outcome.cursor),Err(error) => Err(ctx.failed(error)), } }}#[cfg(test)]mod words {usesuper::*;usecrate::copy::CopyError; #[test]fn a_write_waiting_for_the_data_key_says_so_in_words_and_others_keep_theirs() {let copy = SinkError::Copy(CopyError::Seal { code: "seal_key_missing".into(), message: "no key for the data key of db".into() }); assert_eq!(RunError::from(copy), RunError::Failed(WAITS_FOR_THE_VAULT.to_string()));let object = SinkError::Object(ObjectError::Refused { status: 0, code: "seal_key_missing".into(), message: "this Mac holds no data key yet".into() }); assert_eq!(RunError::from(object), RunError::Failed(WAITS_FOR_THE_VAULT.to_string())); assert_eq!(RunError::from(SinkError::Object(ObjectError::SignedOut)), RunError::SignedOut);let refused = ObjectError::Refused { status: 400, code: "sealed_in_clear".into(), message: "email_thread keeps subject sealed".into() };let said = refused.to_string(); assert_eq!(RunError::from(refused), RunError::Failed(said)); assert_eq!(ObjectError::SignedOut.to_string(), "Cotton signed this Mac out: sign in again"); }}