Cotton code
440 lines · 15.2 KB · RustRaw
//! 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;use crate::object::{ObjectClient, ObjectError};use crate::sink::{ObjectSink, SinkError};use crate::store::Store;/// The cards, in the order the popover draws them.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]#[serde(rename_all = "lowercase")]pub enum SourceKey {    Whatsapp,    Mail,    Photos,    Calls,    Texts,}impl SourceKey {    pub const ALL: [SourceKey; 5] = [        SourceKey::Whatsapp,        SourceKey::Mail,        SourceKey::Photos,        SourceKey::Calls,        SourceKey::Texts,    ];    pub const fn as_str(self) -> &'static str {        match self {            SourceKey::Whatsapp => "whatsapp",            SourceKey::Mail => "mail",            SourceKey::Photos => "photos",            SourceKey::Calls => "calls",            SourceKey::Texts => "texts",        }    }    pub fn 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)]pub enum Schedule {    /// 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),}impl Schedule {    pub fn interval(self) -> Duration {        match self {            Schedule::Continuous(every) | Schedule::Every(every) => every,        }    }    pub fn label(self) -> String {        match self {            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")]pub enum Need {    /// 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")]pub struct Probe {    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>,}impl Probe {    pub fn ready() -> Probe {        Probe { ready: true, need: None, detail: None }    }    pub fn needs(need: Need) -> Probe {        Probe { ready: false, need: Some(need), detail: None }    }    pub fn unavailable(detail: impl Into<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")]pub struct Progress {    /// 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)]pub enum RunError {    /// 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.pub const WAITS_FOR_THE_VAULT: &str = "Waiting until this Mac is let in to your data (see above). Nothing is lost: it is sent then.";impl From<SinkError> for RunError {    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()),        }    }}impl From<ObjectError> for RunError {    fn from(error: ObjectError) -> RunError {        RunError::from(SinkError::Object(error))    }}/// One run's seam to the object and to the cursor store.pub struct RunContext<'a> {    pub sink: &'a ObjectSink<'a>,    store: &'a Store,    source: SourceKey,    cancel: &'a AtomicBool,    on_progress: &'a (dyn Fn(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> {    pub fn new(        sink: &'a ObjectSink<'a>,        store: &'a Store,        source: SourceKey,        cancel: &'a AtomicBool,        on_progress: &'a (dyn Fn(Progress) + Sync),    ) -> RunContext<'a> {        RunContext {            sink,            store,            source,            cancel,            on_progress,            progress: Progress::default(),            notes: IngestNotes::new(),            failure: None,        }    }    pub fn cancelled(&self) -> bool {        self.cancel.load(Ordering::SeqCst)    }    pub fn check(&self) -> Result<(), RunError> {        if self.cancelled() {            Err(RunError::Paused)        } else {            Ok(())        }    }    pub fn progress(&self) -> Progress {        self.progress    }    pub fn notes(&self) -> &IngestNotes {        &self.notes    }    pub fn set_total(&mut self, 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).    pub fn brought(&mut self, 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.    pub fn brought_new(&mut self, 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.    pub fn send(&mut self, 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.    pub fn upsert(&mut self, 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.    pub fn emit(&mut self, batch: IngestBatch) -> Result<(), String> {        match self.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.    pub fn failed(&mut self, reader_error: String) -> RunError {        self.failure.take().unwrap_or(RunError::Failed(reader_error))    }}/// One source.pub trait Importer: 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: &mut RunContext<'_>) -> 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<dyn Fn() + Send + Sync>, _stopping: Arc<dyn Fn() -> 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.pub struct IngestImporter<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> {    pub fn new(key: SourceKey, schedule: Schedule, source: S) -> IngestImporter<S> {        IngestImporter {            key,            schedule,            source,            not_found_need: None,        }    }    pub fn when_not_found(mut self, need: Need) -> IngestImporter<S> {        self.not_found_need = Some(need);        self    }    pub fn source(&self) -> &S {        &self.source    }}impl<S: IngestSource + Sync> Importer for IngestImporter<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: &mut RunContext<'_>) -> Result<String, RunError> {        let outcome = {            let mut 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 {    use super::*;    use crate::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");    }}