Cotton code
1484 lines · 66.9 KB · RustRaw
//! Mail, read over IMAP with the owner's address and an app password.//!//! The protocol layers are copied from `cotton-server`'s `mailbox` (that//! crate retires on its own and its copies are left as they are): the wire//! ([`proto`]), the client ([`client`]), MIME ([`mime`]), the date bounds//! ([`mail_date`]) and Gmail's labels ([`labels`]). What wrote into the old//! store is replaced by [`map`], which turns a message into plain `email`,//! `email_thread` and `email_participant` rows, and [`tally`], which folds a//! thread's count, dates and participants the way the old ingest did.//!//! A run reads, as `imap_sync` did: what is new first (oldest first, so a run//! cut short resumes where it was), then on Gmail the labels that moved since//! the last run (CONDSTORE), then a slice of the backfill — the newest year//! first, newest UID first, found by the server's own dates. A Gmail account//! reads its `\All` mailbox, any other INBOX. Every page (at most [`PAGE`]//! messages) is sent before the cursor moves past it. A run reads at most//! [`BACKFILL_PER_RUN`] older messages and then asks for another run at once//! (through the wake [`Importer::watch`] gave it), so new mail is never//! queued behind a decade of backfill. Between runs INBOX is held in IDLE on//! its own thread, which wakes the source when new mail lands.//!//! THE CURSOR is JSON, one entry per mailbox read, by its name://!//! ```json//! {"v":1,"mailboxes":{"[Gmail]/All Mail":{//!   "uidValidity":3857529045,"topUid":81234,"backfillBelow":1,//!   "highestModseq":9912345,"backfillYear":2014,"backfillCeiling":80001}}}//! ```//!//! — exactly the columns `imap_sync` kept in `_imap_cursors` per connection://! `uidValidity` (a different one renumbers every UID: the mailbox is read//! afresh), `topUid` (the highest UID read; everything above is new),//! `backfillBelow` (within `backfillYear`, every UID at or above it is read;//! 1 is a finished backfill), `highestModseq` (CONDSTORE's counter at the last//! read, absent on a server without it), `backfillYear` and `backfillCeiling`//! (the year the backfill is reading and the UID it reads below; both absent//! until the walk begins). An old cursor row maps one to one, under its//! `mailbox` column's name.//!//! What the old reader did that the Mac does not: the deletion sweep (Gmail//! ids the server no longer holds) and the INBOX flag sweep, which both read//! the rows the store held, and the merge of labels the OAuth path had//! written, which needs the row's labels. The object holds the rows now; the//! Mac reads nothing back.pub mod client;pub mod history;pub mod labels;pub mod map;pub mod proto;pub mod tally;pub mod acts;pub mod page;pub mod trash;// The decoder is shared with the Worker (cotton-rules `mail`).pub use cotton_rules::mail::{mail_date, mime, text};use std::collections::{BTreeMap, HashMap, HashSet};use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};use std::time::Duration;use serde::{Deserialize, Serialize};use serde_json::Value;use crate::importer::{Importer, Need, Probe, RunContext, RunError, Schedule, SourceKey};use crate::object::{Act, ObjectError};use crate::sources::QUARTER_HOUR;use client::{dial, Fetched, Idled, ImapClient, ImapError, MailboxState, Server, Stream};use map::{Ids, Page};use mime::{decode, GmailFacts, MailFlags};use tally::{Owned, Tally};/// UIDs looked at per page.pub const PAGE: u32 = 200;/// Bodies per FETCH: each may be large, so few at a time.const BODY_BATCH: usize = 25;/// How many older messages one run reads before it hands over to the next.pub const BACKFILL_PER_RUN: u32 = 1000;/// The empty years one run may step past before it yields.const EMPTY_YEARS_PER_RUN: u32 = 25;/// How long one IDLE is held before it is renewed: under Gmail's 29 minutes.pub const IDLE_WINDOW: Duration = Duration::from_secs(25 * 60);/// The longest wait between two IDLE connections that failed.const IDLE_BACKOFF_MAX: Duration = Duration::from_secs(5 * 60);/// Dials a server: TLS for a real one ([`client::dial`]), anything for a test.pub type Dialer = Arc<dyn Fn(&Server) -> Result<Box<dyn Stream>, ImapError> + Send + Sync>;pub type Wake = Arc<dyn Fn() + Send + Sync>;pub type Stopping = Arc<dyn Fn() -> bool + Send + Sync>;/// The address and app password, held in memory only: the app keeps them in/// the Mac's keychain and sends them at every launch.#[derive(Clone)]struct Credentials {    address: String,    password: String,    server: Option<Server>,}/// Where the IMAP server for `address` is: the well-known server for its/// domain, as `mailbox::imap_sync::server_of` knew them.pub fn server_for(address: &str) -> Option<Server> {    let domain = address.rsplit_once('@')?.1.to_ascii_lowercase();    let host = match domain.as_str() {        "gmail.com" | "googlemail.com" => "imap.gmail.com",        "icloud.com" | "me.com" | "mac.com" => "imap.mail.me.com",        "fastmail.com" | "fastmail.fm" => "imap.fastmail.com",        "outlook.com" | "hotmail.com" | "live.com" => "outlook.office365.com",        "yahoo.com" => "imap.mail.yahoo.com",        _ => return None,    };    Some(Server { host: host.to_string(), port: 993, tls: true })}/// `host` or `host:port` (993 when absent).fn parse_host(text: &str, tls: bool) -> Option<Server> {    let text = text.trim();    if text.is_empty() {        return None;    }    let (host, port) = match text.rsplit_once(':') {        Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => (host, port.parse().ok()?),        _ => (text, 993),    };    Some(Server { host: host.to_string(), port, tls })}/// Where one mailbox's read stands (the module header).#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MailboxCursor {    pub uid_validity: u32,    pub top_uid: u32,    pub backfill_below: u32,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub highest_modseq: Option<u64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub backfill_year: Option<i32>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub backfill_ceiling: Option<u32>,    /// [`history::HISTORY`] once the walk with the headers, categories and Seen has begun from the top.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub history: Option<u32>,    /// Mail the walk has looked at, of `history_total` the mailbox held at the last run.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub history_done: Option<u64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub history_total: Option<u32>,    /// The day of the oldest mail walked: how far back it has reached.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub history_reached: Option<String>,    /// What the mail it brought weighs at the object, about: the walk stops bringing at [`history::HISTORY_BYTES_MAX`].    #[serde(default, skip_serializing_if = "Option::is_none")]    pub history_bytes: Option<u64>,}impl MailboxCursor {    /// Where the walk stands, as the panel and the phones say it: `walking`, `done` or `held` (stopped at size).    pub fn history_state(&self) -> Option<&'static str> {        self.history?;        Some(if self.history_bytes.unwrap_or(0) >= history::HISTORY_BYTES_MAX {            "held"        } else if self.backfill_below <= 1 {            "done"        } else {            "walking"        })    }}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct MailCursor {    pub v: u32,    pub mailboxes: BTreeMap<String, MailboxCursor>,}impl MailCursor {    pub fn parse(text: Option<&str>) -> Result<MailCursor, String> {        match text.filter(|t| !t.trim().is_empty()) {            None => Ok(MailCursor { v: 1, mailboxes: BTreeMap::new() }),            Some(text) => serde_json::from_str(text).map_err(|e| format!("the mail cursor does not read: {e}")),        }    }    pub fn text(&self) -> String {        serde_json::to_string(self).unwrap_or_default()    }}struct Shared {    credentials: Mutex<Option<Credentials>>,    /// The server's last refusal of the app password, until new ones come.    refused: Mutex<Option<String>>,    tally_path: PathBuf,    tally: Mutex<Option<Arc<Tally>>>,    dialer: Dialer,    wake: Mutex<Option<Wake>>,    /// Whether this launch has taken up the mail acts an earlier Mac refused ([`acts::OLD_REFUSALS`]).    retried: std::sync::atomic::AtomicBool,    /// This launch looked once for the mail it counted that never reached the database.    rechecked: std::sync::atomic::AtomicBool,}pub struct MailImporter {    shared: Arc<Shared>,}/// Fresh connections a run makes after the server dropped one, each with half the batches of the last.pub const RECONNECTS: u32 = 3;impl MailImporter {    /// One connection's reading. A failure answers the error, the connection's own failure when it was that    /// (so a fresh one may go on), and the cursor the last whole page left.    fn read_once(        &self,        credentials: &Credentials,        cursor: Option<&str>,        ctx: &mut RunContext<'_>,        attempt: u32,    ) -> Result<String, (RunError, Option<String>, Option<String>)> {        let lost = |error: ImapError| {            let gone = (!matches!(error, ImapError::SignIn(_))).then(|| error.to_string());            (failed(error), gone, None)        };        let parsed = MailCursor::parse(cursor).map_err(|e| (RunError::Failed(e), None, None))?;        let tally = self.shared.tally().map_err(|e| (e, None, None))?;        let mut client = self.shared.connect(credentials).map_err(lost)?;        let gmail = client.can("X-GM-EXT-1");        let mailbox = if gmail {            client.special_use().map_err(lost)?.all.unwrap_or_else(|| "INBOX".to_string())        } else {            "INBOX".to_string()        };        let state = client.examine(&mailbox).map_err(lost)?;        let ids = Ids::new(ctx.sink.database_id());        let mut read = Read {            ctx,            client: &mut client,            tally,            ids,            account: credentials.address.clone(),            gmail,            mailbox: mailbox.clone(),            cursor: parsed,            page: (PAGE >> attempt).max(PAGE / 8),            body_batch: (BODY_BATCH >> attempt).max(1),            saved: None,            lost: None,            takes_headers: false,            takes_category: false,            page_oldest: None,            page_bytes: 0,            recheck: false,        };        let sink = read.ctx.sink;        if let Ok(copy) = sink.copy() {            // The copy as the object holds it now: which mail is held, and the columns it takes.            let _ = copy.refresh(sink.object());            read.takes_headers = copy.has_column(map::EMAIL, "list_id");            read.takes_category = copy.has_column(map::EMAIL, "gmail_category");            read.recheck = gmail && !self.shared.rechecked.swap(true, std::sync::atomic::Ordering::SeqCst);        }        let fresh = match read.cursor.mailboxes.get(&mailbox) {            Some(at) => at.uid_validity != state.uid_validity,            None => true,        };        if fresh {            // First read, or the server renumbered the mailbox (a new            // UIDVALIDITY): every UID is new again. What was sent is sent to            // the same ids, so a re-read writes nothing twice.            read.cursor.mailboxes.insert(                mailbox.clone(),                MailboxCursor {                    uid_validity: state.uid_validity,                    top_uid: state.uid_next.saturating_sub(1),                    backfill_below: state.uid_next.max(1),                    highest_modseq: state.highest_modseq,                    backfill_year: None,                    backfill_ceiling: None,                    ..MailboxCursor::default()                },            );        }        {            // The whole mailbox walked once more from the top, now with the headers, categories and Seen kept            // (`history`): a cursor that walked it before them, or never walked it (owner, 24 Nov 2026).            let at = read.at();            if at.history != Some(history::HISTORY) {                at.backfill_below = at.top_uid.saturating_add(1).max(1);                at.backfill_year = None;                at.backfill_ceiling = None;                at.history = Some(history::HISTORY);                at.history_done = Some(0);                at.history_reached = None;                at.history_bytes = Some(0);            }            at.history_total = Some(state.exists);        }        let more = match read.catch_up(&state) {            Ok(more) => more,            Err(error) => return Err((error, read.lost.take(), read.saved.take())),        };        let text = read.cursor.text();        let standing = read.cursor.mailboxes.get(&mailbox).cloned();        if let (Some(at), Ok(copy)) = (standing.as_ref(), sink.copy()) {            history_row(sink, copy, at);        }        client.logout();        if more {            self.shared.wake_after(history::HISTORY_REST);        }        Ok(text)    }    /// `data_dir` holds `mail.db`, the thread fold.    pub fn new(data_dir: &Path) -> MailImporter {        MailImporter::with_dialer(data_dir, Arc::new(dial))    }    pub fn with_dialer(data_dir: &Path, dialer: Dialer) -> MailImporter {        MailImporter {            shared: Arc::new(Shared {                credentials: Mutex::new(None),                refused: Mutex::new(None),                tally_path: data_dir.join("mail.db"),                tally: Mutex::new(None),                dialer,                wake: Mutex::new(None),                retried: std::sync::atomic::AtomicBool::new(false),                rechecked: std::sync::atomic::AtomicBool::new(false),            }),        }    }}impl Shared {    fn credentials(&self) -> Option<Credentials> {        self.credentials.lock().unwrap_or_else(|p| p.into_inner()).clone()    }    fn server(credentials: &Credentials) -> Option<Server> {        credentials.server.clone().or_else(|| server_for(&credentials.address))    }    fn tally(&self) -> Result<Arc<Tally>, RunError> {        let mut held = self.tally.lock().unwrap_or_else(|p| p.into_inner());        if let Some(tally) = held.as_ref() {            return Ok(Arc::clone(tally));        }        let tally = Arc::new(Tally::open(&self.tally_path).map_err(|e| RunError::Failed(e.to_string()))?);        *held = Some(Arc::clone(&tally));        Ok(tally)    }    /// Dial and sign in. A refused password is kept for the card.    fn connect(&self, credentials: &Credentials) -> Result<ImapClient, ImapError> {        let server = Self::server(credentials).ok_or_else(|| {            ImapError::Connect(format!("no mail server is known for {}", credentials.address))        })?;        let mut client = ImapClient::start((self.dialer)(&server)?)?;        match client.login(&credentials.address, &credentials.password) {            Ok(()) => Ok(client),            Err(ImapError::SignIn(said)) => {                *self.refused.lock().unwrap_or_else(|p| p.into_inner()) = Some(said.clone());                Err(ImapError::SignIn(said))            }            Err(other) => Err(other),        }    }    /// `test { address, password, imapHost?, imapTls? }`, before the account is added: sign in, look (read only)    /// at the mailbox a run would read, and answer what is there — `{ tested: true, mailbox, count, oldest? }`    /// (`oldest` in ms) — or `{ tested: false, said, askServer? }` in the panel's words. Nothing is kept: the    /// account the source reads changes only with `credentials`.    fn test(&self, args: &Value) -> Value {        let say = |line: &str| crate::panel::say(&format!("mail_test.{line}"), &[]);        let refused = |line: &str, ask_server: bool| serde_json::json!({ "tested": false, "said": say(line), "askServer": ask_server });        let address = args.get("address").and_then(Value::as_str).unwrap_or("").trim().to_string();        let password = args.get("password").and_then(Value::as_str).unwrap_or("").to_string();        if address.is_empty() || password.is_empty() {            return refused("empty", false);        }        let tls = args.get("imapTls").and_then(Value::as_bool).unwrap_or(true);        let server = args.get("imapHost").and_then(Value::as_str).and_then(|host| parse_host(host, tls));        let credentials = Credentials { address, password, server };        let Some(server) = Self::server(&credentials) else {            return refused("no_server", true);        };        let looked = (|| -> Result<(String, u32, Option<i64>), ImapError> {            let mut client = ImapClient::start((self.dialer)(&server)?)?;            client.login(&credentials.address, &credentials.password)?;            // As a run chooses: All Mail where the server names one, else INBOX.            let mailbox = client.special_use().ok().and_then(|u| u.all).unwrap_or_else(|| "INBOX".to_string());            let state = client.examine(&mailbox)?;            // The oldest is a nicety: a server that will not say leaves it out.            let oldest = client                .uid_search("ALL")                .ok()                .and_then(|uids| uids.into_iter().min())                .and_then(|uid| client.uid_fetch(&uid.to_string(), "UID INTERNALDATE", None).ok())                .and_then(|fetched| fetched.first().and_then(|f| f.internal_date));            client.logout();            Ok((mailbox, state.exists, oldest))        })();        match looked {            Ok((mailbox, count, oldest)) => serde_json::json!({ "tested": true, "mailbox": mailbox, "count": count, "oldest": oldest }),            Err(ImapError::SignIn(_)) => refused("refused", false),            Err(ImapError::Connect(_)) | Err(ImapError::Timeout(_)) => refused("unreachable", credentials.server.is_some()),            Err(_) => refused("failed", false),        }    }    fn wake(&self) {        let wake = self.wake.lock().unwrap_or_else(|p| p.into_inner()).clone();        if let Some(wake) = wake {            wake();        }    }    /// Ask for a run after `rest`: the history walk's pace ([`history::HISTORY_REST`]).    fn wake_after(self: &Arc<Self>, rest: Duration) {        let shared = Arc::clone(self);        std::thread::spawn(move || {            std::thread::sleep(rest);            shared.wake();        });    }}fn failed(error: ImapError) -> RunError {    RunError::Failed(error.to_string())}fn store_failed(error: rusqlite::Error) -> RunError {    RunError::Failed(format!("mail.db: {error}"))}/// What a metadata fetch asks for.fn metadata_items(gmail: bool) -> String {    if gmail {        format!("UID X-GM-MSGID X-GM-THRID X-GM-LABELS FLAGS {}", history::HEADER_FIELDS)    } else {        format!("UID FLAGS {}", history::HEADER_FIELDS)    }}/// The person's `mail_history` row (one, by the database's id): how far the walk has reached, for the phones./// Counts and a day only. Written once a run, and only when the object's definitions have the table./// A mail's designed page and attachments onto its row (the phone's `mail_page`, [`page`]): each a sealed file, then/// one update of the row. The page goes in the row's `media` (`{key, contentType, size, fileKey, name: "page.html"}`),/// each attachment's file beside its name in `attachments` (`key`, `fileKey`). Answers `{page, files}`./// Erases the email rows of mail a sender's Delete everything moved to Trash (DELETE FAST question 2), found by/// Gmail's id where the import wrote one, else by the Message-ID's `external_id`, and each conversation left with/// no mail. Rows already gone (the phone erased its 90 days) are passed over. Answers how many email rows went.pub fn erase_trashed(object: &crate::object::ObjectClient, copy: &crate::copy::Copy, gone: &[trash::GoneMail]) -> Result<usize, String> {    let found = |g: &trash::GoneMail| -> Result<Option<(String, serde_json::Map<String, Value>)>, String> {        if let Some(gmail_id) = &g.gmail_id {            if let Some(row) = copy.email_by_gmail_id(gmail_id).map_err(|e| e.to_string())? {                return Ok(Some(row));            }        }        match &g.external {            Some(external) => copy.email_by_external_id(external).map_err(|e| e.to_string()),            None => Ok(None),        }    };    let gone_already = |e: &ObjectError| matches!(e, ObjectError::Refused { status: 404, .. });    let mut erased = 0;    let mut threads: Vec<String> = Vec::new();    for g in gone {        let Some((id, row)) = found(g)? else { continue };        match object.act(Act::Delete, map::EMAIL, &id, &serde_json::json!({})) {            Ok(_) => erased += 1,            Err(e) if gone_already(&e) => continue,            Err(e) => return Err(e.to_string()),        }        if let Some(thread) = row.get("thread_id").and_then(Value::as_str).filter(|t| !t.is_empty()) {            if !threads.iter().any(|t| t == thread) {                threads.push(thread.to_string());            }        }    }    for thread in threads {        if copy.emails_in_thread(&thread).map_err(|e| e.to_string())? == 0 {            match object.act(Act::Delete, map::THREAD, &thread, &serde_json::json!({})) {                Ok(_) => {}                Err(e) if gone_already(&e) => {}                Err(e) => return Err(e.to_string()),            }        }    }    Ok(erased)}pub fn land_page(sink: &crate::sink::ObjectSink<'_>, copy: &crate::copy::Copy, external: &str, raw: &[u8]) -> Result<Value, String> {    let (id, row) = copy.email_by_external_id(external).map_err(|e| e.to_string())?.ok_or_else(|| acts::GONE.to_string())?;    let opened = page::open(raw).ok_or_else(|| "the message could not be read".to_string())?;    let mut sent = crate::sink::Sent::default();    let scratch = tempfile::tempdir().map_err(|e| e.to_string())?;    let mut put = |name: &str, mime: &str, bytes: &[u8]| -> Result<Option<Value>, String> {        let path = scratch.path().join("part");        std::fs::write(&path, bytes).map_err(|e| e.to_string())?;        let up = sink.put_sealed_file(&path, Some(name), Some(mime), &mut sent).map_err(|e| e.to_string())?;        Ok(up.map(|(key, content_type, size, file_key)| serde_json::json!({ "key": key, "contentType": content_type, "size": size, "fileKey": file_key, "name": name })))    };    // A column kept as JSON text or as JSON, read either way and written back the way it came.    let list_of = |value: Option<&Value>| -> (Vec<Value>, bool) {        match value {            Some(Value::Array(list)) => (list.clone(), false),            Some(Value::String(text)) => (serde_json::from_str(text).unwrap_or_default(), true),            _ => (Vec::new(), false),        }    };    let back = |list: Vec<Value>, as_text: bool| if as_text { Value::from(serde_json::to_string(&list).unwrap_or_default()) } else { Value::Array(list) };    let mut patch = serde_json::Map::new();    let mut page_kept = false;    let (media, media_text) = list_of(row.get("media"));    let has_page = media.iter().any(|m| m.get("name").and_then(Value::as_str) == Some("page.html"));    if let (Some(html), false, true) = (&opened.html, has_page, copy.has_column(map::EMAIL, "media")) {        if let Some(file) = put("page.html", "text/html", html.as_bytes())? {            let mut media = media.clone();            media.push(file);            patch.insert("media".into(), back(media, media_text));            page_kept = true;        }    }    let (mut list, list_text) = list_of(row.get("attachments"));    let mut files = 0;    for part in &opened.attachments {        let Some(entry) = list.get_mut(part.index).and_then(Value::as_object_mut) else { continue };        if part.bytes.is_empty() || entry.contains_key("key") {            continue;        }        if let Some(file) = put(&part.name, &part.mime, &part.bytes)? {            entry.insert("key".into(), file["key"].clone());            entry.insert("fileKey".into(), file["fileKey"].clone());            files += 1;        }    }    if files > 0 {        patch.insert("attachments".into(), back(list, list_text));    }    if !patch.is_empty() {        sink.object().act_as(Act::Update, map::EMAIL, &id, &Value::Object(patch), true).map_err(|e| e.to_string())?;    }    Ok(serde_json::json!({ "page": page_kept || has_page, "files": files }))}fn history_row(sink: &crate::sink::ObjectSink<'_>, copy: &crate::copy::Copy, at: &MailboxCursor) {    let Some(state) = at.history_state() else { return };    if !copy.has_column("mail_history", "done") {        return;    }    let id = cotton_rules::ids::derived_id("mail_history", &[sink.database_id()]);    let data = serde_json::json!({        "state": state,        "reached_at": at.history_reached,        "done": at.history_done.unwrap_or(0),        "total": at.history_total,        "at": cotton_client::seams::iso(chrono::Utc::now()),    });    if let Err(error) = sink.object().upsert_as("mail_history", &id, &data, true) {        eprintln!("cotton-mac: the mail history row was not written: {error}");    }}/// 1 January of `year` as IMAP's SEARCH writes a date (`1-Jan-2026`).fn imap_date(year: i32) -> String {    format!("1-Jan-{year}")}fn is_refusal(error: &ObjectError, status: u16, code: &str) -> bool {    matches!(error, ObjectError::Refused { status: s, code: c, .. } if *s == status && c == code)}/// What refreshing a held mail found.enum Refreshed {    /// The object holds it; the date it was given when its own was unbelievable.    Held(Option<String>),    /// Only this Mac's count knew it and the object has no such row: it goes again, whole.    Missing,}/// Whether a failed write may go again on a later read: the object was away, failing or busy, or this Mac lost/// its way to it. A refusal of the row itself (a 4xx such as `bad_column`) would be refused again, and a mail/// that can never land must not hold up every mail after it.fn goes_again(error: &ObjectError) -> bool {    match error {        ObjectError::Refused { status, .. } => !(400..500).contains(status) || matches!(status, 401 | 408 | 429),        ObjectError::SignedOut | ObjectError::Transport(_) | ObjectError::Decode(_) => true,        ObjectError::File(_) => false,    }}/// A push that failed: the object's own answer, kept typed so it can be told whether it goes again.enum Pushed {    Object(ObjectError),    Run(RunError),}impl From<ObjectError> for Pushed {    fn from(error: ObjectError) -> Pushed {        Pushed::Object(error)    }}impl From<RunError> for Pushed {    fn from(error: RunError) -> Pushed {        Pushed::Run(error)    }}impl Pushed {    fn goes_again(&self) -> bool {        match self {            Pushed::Object(error) => goes_again(error),            // Paused, signed out, or this Mac's own file: the mail goes again on a later read.            Pushed::Run(_) => true,        }    }    fn into_run(self) -> RunError {        match self {            Pushed::Object(error) => error.into(),            Pushed::Run(error) => error,        }    }}/// An object refusal by its status and code alone, for the log (never its words, which may name a mail).fn refusal_code(error: &ObjectError) -> String {    match error {        ObjectError::Refused { status, code, .. } => format!("{status} {code}"),        other => other.to_string().chars().take(40).collect(),    }}/// One run's reading of one mailbox.struct Read<'r, 'c> {    ctx: &'r mut RunContext<'c>,    client: &'r mut ImapClient,    tally: Arc<Tally>,    ids: Ids,    account: String,    gmail: bool,    mailbox: String,    cursor: MailCursor,    /// UIDs looked at per page and bodies per FETCH: [`PAGE`] and [`BODY_BATCH`], smaller on each retry after    /// the server dropped the connection.    page: u32,    body_batch: usize,    /// The cursor as the last whole page left it at the object: where a retry starts.    saved: Option<String>,    /// The connection failed under this run (the server said BYE, stopped answering, or the wire broke): a    /// fresh connection may go on.    lost: Option<String>,    /// The person's database has the header columns (`email.list_id` and its kin): until the Worker serves them,    /// none is sent, so no mail is refused for a column it does not know.    takes_headers: bool,    /// The database keeps Gmail's category in its own column (`gmail_category`, Senders 3).    takes_category: bool,    /// The day of the oldest mail the last page held.    page_oldest: Option<String>,    /// What the mail the last page brought weighs at the object, about.    page_bytes: u64,    /// The first run since launch: look for the mail this Mac counted that the database does not hold.    recheck: bool,}impl Read<'_, '_> {    /// An IMAP answer: a refused sign-in fails the run; any other failure is the connection's, kept so the run    /// can go on over a fresh one.    fn imap<T>(&mut self, answer: Result<T, ImapError>) -> Result<T, RunError> {        answer.map_err(|error| {            if !matches!(error, ImapError::SignIn(_)) {                self.lost = Some(error.to_string());            }            failed(error)        })    }    fn at(&mut self) -> &mut MailboxCursor {        self.cursor.mailboxes.entry(self.mailbox.clone()).or_default()    }    fn act(&self, act: Act, table: &str, id: &str, data: &Value) -> Result<(), ObjectError> {        // The mail reader's writes are an import's: the object logs only that they happened.        self.ctx.sink.object().act_as(act, table, id, data, true).map(|_| ())    }    /// The page's rows are at the object: move the cursor with them.    fn brought(&mut self, rows: i64) -> Result<(), RunError> {        let text = self.cursor.text();        self.ctx.brought(rows, 0, Some(&text))?;        self.saved = Some(text);        Ok(())    }    /// Read UIDs `lo..=hi`: one page of new mail.    fn read_range(&mut self, lo: u32, hi: u32) -> Result<i64, RunError> {        let answer = self.client.uid_fetch(&format!("{lo}:{hi}"), &metadata_items(self.gmail), None);        let metadata: Vec<Fetched> = self            .imap(answer)?            .into_iter()            // `n:*` answers the last message even below n; keep the range.            .filter(|f| f.uid >= lo && f.uid <= hi)            .collect();        self.read_fetched(metadata, true)    }    /// The mail this Mac counted (Gmail's, by its id) that the database holds no row of, found in the mailbox by    /// its Gmail id and read again as new mail: its row is created (SYNC GAP, 25 Nov 2026). Mail no longer in the    /// mailbox (binned in Gmail, or deleted from Cotton, which bins it there) is not found and stays gone. Counts    /// only in the log.    fn recover(&mut self, top: u32) -> Result<(), RunError> {        let Ok(copy) = self.ctx.sink.copy() else { return Ok(()) };        // The copy knows what the database holds of mail only while it keeps the (sealed) email table.        if !copy.sealed_tables().iter().any(|t| t == map::EMAIL) {            return Ok(());        }        let mut missing = 0usize;        let mut uids: Vec<u32> = Vec::new();        for (id, gmail_id) in self.tally.gmail_emails().map_err(store_failed)? {            let held = copy.row(map::EMAIL, &id).map_err(|e| RunError::Failed(e.to_string()))?.is_some()                || copy.email_by_gmail_id(&gmail_id).map_err(|e| RunError::Failed(e.to_string()))?.is_some();            let Ok(msgid) = u64::from_str_radix(&gmail_id, 16) else { continue };            if held {                continue;            }            missing += 1;            self.ctx.check()?;            let found = self.client.uid_search(&format!("X-GM-MSGID {msgid}"));            uids.extend(self.imap(found)?.into_iter().filter(|uid| *uid <= top));        }        if missing == 0 {            return Ok(());        }        uids.sort_unstable();        uids.dedup();        let mut sent = 0;        for page in uids.chunks(self.page.max(1) as usize) {            let brought = self.read_uids_as(page, true)?;            sent += brought;            self.brought(brought)?;        }        eprintln!("mail: {missing} counted mail(s) the database lacked; {} found in the mailbox, {sent} sent again", uids.len());        Ok(())    }    /// Read exactly these UIDs (one page of the backfill).    fn read_uids(&mut self, uids: &[u32]) -> Result<i64, RunError> {        self.read_uids_as(uids, false)    }    /// Read exactly these UIDs; `live` as [`Self::read_fetched`] takes it.    fn read_uids_as(&mut self, uids: &[u32], live: bool) -> Result<i64, RunError> {        if uids.is_empty() {            return Ok(0);        }        let wanted: HashSet<u32> = uids.iter().copied().collect();        let set: Vec<String> = uids.iter().map(u32::to_string).collect();        let answer = self.client.uid_fetch(&set.join(","), &metadata_items(self.gmail), None);        let metadata: Vec<Fetched> = self            .imap(answer)?            .into_iter()            .filter(|f| wanted.contains(&f.uid))            .collect();        self.read_fetched(metadata, live)    }    /// Metadata in hand: a Gmail message this Mac sent before gets its state,    /// the rest are fetched whole and sent. `live` is new mail, as opposed    /// to the backfill. Answers the emails sent.    fn read_fetched(&mut self, mut metadata: Vec<Fetched>, live: bool) -> Result<i64, RunError> {        self.ctx.check()?;        metadata.sort_by_key(|f| f.uid);        if metadata.is_empty() {            return Ok(0);        }        self.page_oldest = None;        self.page_bytes = 0;        let sink = self.ctx.sink;        let copy = sink.copy().ok();        // Gmail's categories for this page, by Gmail's own search over its UID span (`history`).        let categories = if self.gmail { self.categories(&metadata)? } else { HashMap::new() };        let mut held: Vec<(String, Fetched, Option<serde_json::Map<String, Value>>)> = Vec::new();        let mut new = Vec::new();        for meta in metadata {            let gmail_id = meta.gm_msgid.filter(|_| self.gmail).map(mime::api_id);            let mut known = match &gmail_id {                Some(gmail_id) => self.tally.email_by_gmail_id(gmail_id).map_err(store_failed)?.map(|id| (id, None)),                None => None,            };            if let Some(copy) = copy {                // What the person's database holds, whoever brought it there (the earlier app's import too).                let in_copy = match &gmail_id {                    Some(gmail_id) => copy.email_by_gmail_id(gmail_id).map_err(|e| RunError::Failed(e.to_string()))?,                    None => {                        let header = meta.body.as_deref().map(history::headers).unwrap_or_default();                        match cotton_rules::fingerprint::email::message_id_external_id(header.message_id.as_deref()) {                            Some(external) => {                                let id = self.ids.email(&external);                                copy.row(map::EMAIL, &id).map_err(|e| RunError::Failed(e.to_string()))?.map(|row| (id, row))                            }                            None => None,                        }                    }                };                if let Some((id, row)) = in_copy {                    known = Some((id, Some(row)));                }            }            match known {                Some((id, row)) => held.push((id, meta, row)),                None => new.push(meta),            }        }        for (id, meta, row) in held {            let found = categories.get(&meta.uid).cloned().unwrap_or_default();            let redated = match self.refresh(&id, &meta, &found, row.as_ref())? {                Refreshed::Held(redated) => redated,                Refreshed::Missing => {                    new.push(meta);                    continue;                }            };            let sent_at = redated.or_else(|| row.as_ref().and_then(|r| r.get("sent_at")).and_then(Value::as_str).map(str::to_string));            if let Some(day) = sent_at.as_deref().filter(|at| history::believable_at(at)).and_then(history::day_of) {                self.older(day);            }        }        // The walk brings no more mail the database does not hold once it has brought its share of the size.        if !live && self.at().history_bytes.unwrap_or(0) >= history::HISTORY_BYTES_MAX {            return Ok(0);        }        let mut page = Page::new();        let mut rows = Vec::new();        for batch in new.chunks(self.body_batch.max(1)) {            self.ctx.check()?;            let set: Vec<String> = batch.iter().map(|f| f.uid.to_string()).collect();            // INTERNALDATE with the body: the date a message is given when its            // own `Date` header is not believable (`mail_date`).            let answer = self.client.uid_fetch(&set.join(","), "UID INTERNALDATE BODY.PEEK[]", None);            let bodies: HashMap<u32, (Vec<u8>, Option<i64>)> = self                .imap(answer)?                .into_iter()                .filter_map(|f| Some((f.uid, (f.body?, f.internal_date))))                .collect();            for meta in batch {                let Some((raw, received)) = bodies.get(&meta.uid) else {                    // Expunged between the two fetches: nothing to read.                    continue;                };                let found = categories.get(&meta.uid).cloned().unwrap_or_default();                let facts = GmailFacts {                    msgid: meta.gm_msgid,                    thrid: meta.gm_thrid,                    labels: if self.gmail { history::with_categories(labels::api_labels(&meta.gm_labels, &meta.flags), &found) } else { Vec::new() },                    received: *received,                };                let Ok(mut email) = decode(raw, &self.account, &facts) else {                    // Spam, bin, a draft, or no sender or date: not archived.                    continue;                };                if !self.gmail {                    email.flags = Some(MailFlags::of(&meta.flags));                }                let mut row = page.email(&self.ids, &email).map_err(RunError::Failed)?;                if self.takes_headers {                    let header = meta.body.as_deref().map(history::headers).unwrap_or_default();                    if let Some(data) = row.data.as_object_mut() {                        data.extend(header.columns);                    }                }                if self.takes_category && self.gmail {                    if let Some(data) = row.data.as_object_mut() {                        data.insert("gmail_category".into(), Value::from(history::gmail_category(&found)));                    }                }                if let Some(day) = Some(row.sent_at.as_str()).filter(|at| history::believable_at(at)).and_then(history::day_of) {                    self.older(day);                }                // Sealed, a row weighs about a third more than its words; its conversation, people and tokens more.                self.page_bytes += (row.data.to_string().len() as u64) * 4 / 3 + history::MAIL_OVERHEAD_BYTES;                rows.push(row);            }        }        self.send(rows, live)    }    /// The oldest day this page reached.    fn older(&mut self, day: String) {        if self.page_oldest.as_ref().is_none_or(|have| day < *have) {            self.page_oldest = Some(day);        }    }    /// Which of this page's mails Gmail files under each category: one search a category over the page's UIDs.    fn categories(&mut self, metadata: &[Fetched]) -> Result<HashMap<u32, Vec<&'static str>>, RunError> {        let mut out: HashMap<u32, Vec<&'static str>> = HashMap::new();        let (Some(lo), Some(hi)) = (metadata.iter().map(|f| f.uid).min(), metadata.iter().map(|f| f.uid).max()) else {            return Ok(out);        };        let page: HashSet<u32> = metadata.iter().map(|f| f.uid).collect();        for (word, label) in history::CATEGORIES {            let answer = self.client.uid_search(&format!("UID {lo}:{hi} X-GM-RAW \"category:{word}\""));            for uid in self.imap(answer)? {                if page.contains(&uid) {                    out.entry(uid).or_default().push(label);                }            }        }        Ok(out)    }    /// A mail the database holds: only what changed on it goes (its labels and categories, read or not, starred,    /// in the inbox, and the five headers once the database takes them). Nothing is sent when nothing changed.    /// Answers the date it gave a mail whose own was unbelievable.    fn refresh(&mut self, id: &str, meta: &Fetched, categories: &[&str], held: Option<&serde_json::Map<String, Value>>) -> Result<Refreshed, RunError> {        self.ctx.check()?;        let mut wanted = if self.gmail {            let labels = history::with_categories(labels::api_labels(&meta.gm_labels, &meta.flags), categories);            match map::state_patch(&labels) {                Value::Object(patch) => patch,                _ => serde_json::Map::new(),            }        } else {            // Any other server: read or not, and flagged, as its flags say (the row's own two columns).            let flags = MailFlags::of(&meta.flags);            let mut patch = serde_json::Map::new();            patch.insert("unread".into(), Value::from(flags.unread));            patch.insert("starred".into(), Value::from(flags.starred));            patch        };        if self.takes_headers {            wanted.extend(meta.body.as_deref().map(history::headers).unwrap_or_default().columns);        }        if self.takes_category && self.gmail {            wanted.insert("gmail_category".into(), Value::from(history::gmail_category(categories)));        }        let mut patch = match held {            Some(row) => {                wanted.remove("sync_state");                history::changed(&wanted, row)            }            None => wanted,        };        // A date no mail can carry (the earlier import kept a notice "sent" in 2611): the mailbox's own receipt        // time instead, as the import itself has dated mail since (`mail_date`), and its conversation's dates with it.        if let Some(bad) = held.and_then(|row| row.get("sent_at")).and_then(Value::as_str).filter(|at| !history::believable_at(at)) {            let answer = self.client.uid_fetch(&meta.uid.to_string(), "UID INTERNALDATE", None);            let received = self.imap(answer)?.into_iter().find(|f| f.uid == meta.uid).and_then(|f| f.internal_date);            if let Some(at) = received.and_then(mail_date::believable).and_then(chrono::DateTime::from_timestamp_millis) {                let at = at.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();                patch.insert("sent_at".into(), Value::from(at.clone()));                self.redate_thread(held.and_then(|row| row.get("thread_id")).and_then(Value::as_str), bad, &at)?;            }        }        let redated = patch.get("sent_at").and_then(Value::as_str).map(str::to_string);        if patch.is_empty() {            return Ok(Refreshed::Held(None));        }        match self.act(Act::Update, map::EMAIL, id, &Value::Object(patch)) {            Ok(()) => Ok(Refreshed::Held(redated)),            // Counted by this Mac alone (the copy does not hold it) and the object has no such row: its push never            // landed (SYNC GAP, 25 Nov 2026), so it is fetched whole and sent. A row the copy held that is gone now            // was deleted meanwhile, and stays gone.            Err(error) if is_refusal(&error, 404, "no_such_record") && held.is_none() => Ok(Refreshed::Missing),            Err(error) if is_refusal(&error, 404, "no_such_record") => Ok(Refreshed::Held(None)),            Err(error) => Err(error.into()),        }    }    /// Fold the page into its threads, then send threads, their people and    /// the emails, in the order the object's links need.    fn send(&mut self, rows: Vec<map::EmailRow>, live: bool) -> Result<i64, RunError> {        let sent = rows.len() as i64;        // A message that came to the person's own domain first (OWN-MAIL.md "Beside the Gmail mail") is the same        // row: its conversation is the one it arrived in, so only Gmail's word on it goes.        let arrived = self.arrived(&rows)?;        let (held, rows): (Vec<map::EmailRow>, Vec<map::EmailRow>) = rows.into_iter().partition(|row| arrived.contains(&row.id));        for row in &held {            self.ctx.check()?;            // The state the mailbox says now (Gmail's labels, or IMAP's flags), never its content or conversation.            let mut patch = serde_json::Map::new();            for key in ["labels", "unread", "starred", "in_inbox", "sync_state", "gmail_id", "gmail_account"] {                if let Some(value) = row.data.get(key).filter(|v| !v.is_null()) {                    patch.insert(key.to_string(), value.clone());                }            }            let patch = Value::Object(patch);            match self.act(Act::Update, map::EMAIL, &row.id, &patch) {                Ok(()) => {}                Err(error) if is_refusal(&error, 404, "no_such_record") => {}                Err(error) => return Err(error.into()),            }        }        let mut threads: Vec<String> = Vec::new();        let mut newest: HashMap<String, String> = HashMap::new();        // Counted now, so each thread is sent folded with its new mail; un-counted again below when the push does        // not reach the object, so a failed push is never taken for a sent one (SYNC GAP, 25 Nov 2026: the email of        // 19:30 was counted, its push met the object's 500, and every later read took it for sent).        let mut counted: Vec<String> = Vec::new();        for row in &rows {            if self                .tally                .add(&row.id, &row.thread_key, row.gmail_id.as_deref(), &row.sent_at, &row.thread_subject, &row.addresses)                .map_err(store_failed)?            {                counted.push(row.id.clone());            }            if !threads.contains(&row.thread_key) {                threads.push(row.thread_key.clone());            }            let at = newest.entry(row.thread_key.clone()).or_default();            if row.sent_at > *at {                *at = row.sent_at.clone();            }        }        let mut landed: HashSet<String> = HashSet::new();        if let Err(pushed) = self.push_page(&rows, &threads, &newest, live, &mut landed) {            if pushed.goes_again() {                for id in counted.iter().filter(|id| !landed.contains(*id)) {                    self.tally.forget(id).map_err(store_failed)?;                }            }            return Err(pushed.into_run());        }        Ok(sent)    }    /// The page's threads, their people, then its emails. Each email that lands is put in `landed`. A thread or    /// email the object refuses for itself (a 4xx) is passed over, counted, and the rest go on; any other failure    /// stops the page.    fn push_page(&mut self, rows: &[map::EmailRow], threads: &[String], newest: &HashMap<String, String>, live: bool, landed: &mut HashSet<String>) -> Result<(), Pushed> {        let mut refused: HashSet<&str> = HashSet::new();        for key in threads {            self.ctx.check()?;            match self.send_thread(key, live.then(|| newest.get(key).map(String::as_str)).flatten()) {                Ok(()) => {}                Err(Pushed::Object(error)) if !goes_again(&error) => {                    eprintln!("mail: the object refused a conversation ({})", refusal_code(&error));                    refused.insert(key.as_str());                }                Err(error) => return Err(error),            }        }        for row in rows.iter().filter(|row| !refused.contains(row.thread_key.as_str())) {            self.ctx.check()?;            match self.ctx.sink.object().upsert_as(map::EMAIL, &row.id, &row.data, true) {                Ok(_) => {                    landed.insert(row.id.clone());                }                Err(error) if !goes_again(&error) => eprintln!("mail: the object refused an email ({})", refusal_code(&error)),                Err(error) => return Err(error.into()),            }        }        Ok(())    }    /// Which of `rows` the object already holds from the person's own domain. A server with no own-domain mail    /// (the route not there, 404) holds none.    fn arrived(&self, rows: &[map::EmailRow]) -> Result<std::collections::HashSet<String>, RunError> {        let mut out = std::collections::HashSet::new();        for chunk in rows.chunks(1000) {            let ids: Vec<&str> = chunk.iter().map(|r| r.id.as_str()).collect();            match self.ctx.sink.object().post_route("/v1/mail/arrived", &serde_json::json!({ "ids": ids })) {                Ok(answer) => out.extend(answer["arrived"].as_array().into_iter().flatten().filter_map(|i| i.as_str().map(str::to_string))),                Err(ObjectError::Refused { status: 404, .. }) => return Ok(out),                Err(error) => return Err(error.into()),            }        }        Ok(out)    }    /// A thread's row and its participants. A thread this Mac made is sent    /// whole from its fold; one the object held first (brought over from the    /// old store) only has its latest date moved, by new mail.    fn send_thread(&mut self, key: &str, live_last: Option<&str>) -> Result<(), Pushed> {        let Some(thread) = self.tally.thread(key).map_err(store_failed)? else {            return Ok(());        };        let id = self.ids.thread(key);        let data = map::thread_data(&thread);        let owned = match thread.owned {            Owned::Unsent => match self.act(Act::Create, map::THREAD, &id, &data) {                Ok(()) => Owned::Mine,                Err(error) if is_refusal(&error, 409, "duplicate_id") => Owned::Foreign,                Err(error) => return Err(error.into()),            },            Owned::Mine => {                match self.act(Act::Update, map::THREAD, &id, &data) {                    Ok(()) => {}                    Err(error) if is_refusal(&error, 404, "no_such_record") => {                        self.act(Act::Create, map::THREAD, &id, &data)?                    }                    Err(error) => return Err(error.into()),                }                Owned::Mine            }            Owned::Foreign => Owned::Foreign,        };        if owned != thread.owned {            self.tally.set_owned(key, owned).map_err(store_failed)?;        }        if owned == Owned::Foreign {            if let Some(at) = live_last {                match self.act(Act::Update, map::THREAD, &id, &serde_json::json!({ "last_at": at })) {                    Ok(()) => {}                    Err(error) if is_refusal(&error, 404, "no_such_record") => {}                    Err(error) => return Err(error.into()),                }            }        }        for person in self.tally.participants(key).map_err(store_failed)? {            let pid = self.ids.participant(&id, &person.email);            let data = map::participant_data(&id, &person);            if owned == Owned::Mine {                self.ctx.check()?;                self.ctx.sink.object().upsert_as(map::PARTICIPANT, &pid, &data, true)?;            } else {                match self.act(Act::Create, map::PARTICIPANT, &pid, &data) {                    Ok(()) => {}                    Err(error) if is_refusal(&error, 409, "duplicate_id") => {}                    Err(error) => return Err(error.into()),                }            }        }        Ok(())    }    /// A Gmail message this Mac sent before: its labels and state as IMAP    /// says them now.    /// A conversation dated by a mail's unbelievable date takes the mail's true one.    fn redate_thread(&mut self, thread_id: Option<&str>, bad: &str, at: &str) -> Result<(), RunError> {        let Some(thread_id) = thread_id else { return Ok(()) };        let Ok(copy) = self.ctx.sink.copy() else { return Ok(()) };        let Some(thread) = copy.row(map::THREAD, thread_id).map_err(|e| RunError::Failed(e.to_string()))? else { return Ok(()) };        let mut patch = serde_json::Map::new();        for key in ["first_at", "last_at"] {            if thread.get(key).and_then(Value::as_str) == Some(bad) {                patch.insert(key.to_string(), Value::from(at));            }        }        if patch.is_empty() {            return Ok(());        }        match self.act(Act::Update, map::THREAD, thread_id, &Value::Object(patch)) {            Ok(()) => Ok(()),            Err(error) if is_refusal(&error, 404, "no_such_record") => Ok(()),            Err(error) => Err(error.into()),        }    }    fn restate(&mut self, id: &str, meta: &Fetched) -> Result<(), RunError> {        self.ctx.check()?;        let labels = labels::api_labels(&meta.gm_labels, &meta.flags);        match self.act(Act::Update, map::EMAIL, id, &map::state_patch(&labels)) {            Ok(()) => Ok(()),            Err(error) if is_refusal(&error, 404, "no_such_record") => Ok(()),            Err(error) => Err(error.into()),        }    }    /// Read what is new, what moved, and a slice of the backfill. Answers    /// whether the backfill has more.    fn catch_up(&mut self, state: &MailboxState) -> Result<bool, RunError> {        // 1. New mail, oldest first, so a cut-short run resumes where it was.        let newest = state.uid_next.saturating_sub(1);        while self.at().top_uid < newest {            let lo = self.at().top_uid + 1;            let hi = self.at().top_uid.saturating_add(self.page).min(newest);            let sent = self.read_range(lo, hi)?;            self.at().top_uid = hi;            self.brought(sent)?;        }        // 1b. Once a launch: mail this Mac counted that the database does not hold, read again.        if std::mem::take(&mut self.recheck) {            self.recover(newest)?;        }        // 2. Labels and flags that moved since the last run (CONDSTORE).        let (seen, top) = (self.at().highest_modseq, self.at().top_uid);        if let (Some(seen), Some(now)) = (seen, state.highest_modseq) {            if now > seen && self.gmail && top > 0 {                // In slices, not one FETCH over the whole mailbox: after a fortnight away that answer is                // large, and Gmail drops a connection under it ("BYE System Error", 22 Nov 2026).                let mut changed = Vec::new();                let slice = self.page.saturating_mul(50).max(1);                let mut lo = 1u32;                while lo <= top {                    let hi = lo.saturating_add(slice - 1).min(top);                    let answer = self.client.uid_fetch(&format!("{lo}:{hi}"), "UID X-GM-MSGID X-GM-LABELS FLAGS", Some(seen));                    changed.extend(self.imap(answer)?.into_iter().filter(|f| f.uid >= lo && f.uid <= hi));                    lo = hi.saturating_add(1);                    if hi == u32::MAX {                        break;                    }                }                for meta in &changed {                    let Some(msgid) = meta.gm_msgid else { continue };                    if let Some(id) = self.tally.email_by_gmail_id(&mime::api_id(msgid)).map_err(store_failed)? {                        self.restate(&id, meta)?;                    }                }            }        }        if state.highest_modseq.is_some() {            self.at().highest_modseq = state.highest_modseq;        }        self.brought(0)?;        // 3. A slice of the backfill: the newest year first, newest UID first.        self.backfill()?;        Ok(self.at().backfill_below > 1)    }    /// Up to [`BACKFILL_PER_RUN`] older messages, year by year, newest first.    /// Every page moves the cursor, so a run cut short resumes where it was    /// and never reads a message twice.    fn backfill(&mut self) -> Result<(), RunError> {        if self.at().backfill_below <= 1 {            return Ok(());        }        let this_year = chrono::Datelike::year(&chrono::Utc::now());        // The walk begins: everything at or above the cursor is already read.        let ceiling = {            let at = self.at();            let below = at.backfill_below;            *at.backfill_ceiling.get_or_insert(below)        };        let mut year = *self.at().backfill_year.get_or_insert(this_year);        if ceiling <= 1 {            self.at().backfill_below = 1;            return self.brought(0);        }        let below_ceiling = format!("UID 1:{}", ceiling - 1);        let mut budget = BACKFILL_PER_RUN;        // Empty years cost a SEARCH each and no budget; a mailbox with one        // message dated 1601 must not make one run walk four centuries.        let mut empty_years = 0;        while budget > 0 && empty_years < EMPTY_YEARS_PER_RUN {            self.ctx.check()?;            // This year's UIDs not yet read, newest first. The year being            // lived in has no upper bound: a message dated ahead is still read.            let mut criteria = format!("{below_ceiling} SINCE {}", imap_date(year));            if year < this_year {                criteria.push_str(&format!(" BEFORE {}", imap_date(year + 1)));            }            let below = self.at().backfill_below;            let answer = self.client.uid_search(&criteria);            let mut left: Vec<u32> = self                .imap(answer)?                .into_iter()                .filter(|uid| *uid < below && *uid < ceiling)                .collect();            left.sort_unstable_by(|a, b| b.cmp(a));            if left.is_empty() {                // Nothing older anywhere below the ceiling: the backfill is done.                let answer = self.client.uid_search(&format!("{below_ceiling} BEFORE {}", imap_date(year)));                let older = self.imap(answer)?;                if older.is_empty() {                    self.at().backfill_below = 1;                    return self.brought(0);                }                year -= 1;                empty_years += 1;                self.at().backfill_year = Some(year);                self.at().backfill_below = ceiling;                self.brought(0)?;                continue;            }            for chunk in left.chunks(self.page.max(1) as usize) {                let take = chunk.len().min(budget as usize);                let chunk = &chunk[..take];                let sent = self.read_uids(chunk)?;                budget = budget.saturating_sub(take as u32);                let lowest = chunk.iter().copied().min().unwrap_or(below);                let (oldest, bytes) = (self.page_oldest.take(), self.page_bytes);                let at = self.at();                at.backfill_below = lowest;                if at.history.is_some() {                    at.history_done = Some(at.history_done.unwrap_or(0) + take as u64);                    at.history_bytes = Some(at.history_bytes.unwrap_or(0) + bytes);                    if let Some(day) = oldest {                        if at.history_reached.as_ref().is_none_or(|have| day < *have) {                            at.history_reached = Some(day);                        }                    }                }                self.brought(sent)?;                if budget == 0 {                    break;                }            }        }        Ok(())    }}impl Importer for MailImporter {    fn key(&self) -> SourceKey {        SourceKey::Mail    }    fn schedule(&self) -> Schedule {        Schedule::Every(QUARTER_HOUR)    }    fn probe(&self) -> Probe {        let Some(credentials) = self.shared.credentials() else {            return Probe::needs(Need::Credentials);        };        if let Some(said) = self.shared.refused.lock().unwrap_or_else(|p| p.into_inner()).clone() {            return Probe {                ready: false,                need: Some(Need::Credentials),                detail: Some(format!("The mail server refused the app password: {said}")),            };        }        if Shared::server(&credentials).is_none() {            return Probe {                ready: false,                need: Some(Need::Credentials),                detail: Some(format!("No mail server is known for {}; name its IMAP host.", credentials.address)),            };        }        Probe::ready()    }    /// A run: read over one connection; when the server drops it (Gmail's "BYE System Error", a stall, a broken    /// wire), go on from the last page the object took over a fresh connection with smaller batches, up to    /// [`RECONNECTS`] times. Only then does the run fail, in words a person reads on the panel; the app tries    /// again later by itself and nothing is lost, since the cursor moves only with what the object took.    fn run(&self, cursor: Option<&str>, ctx: &mut RunContext<'_>) -> Result<String, RunError> {        let credentials = self            .shared            .credentials()            .ok_or_else(|| RunError::Failed("no address and app password".to_string()))?;        // What the owner asked of this account from the phone (read, archive, Trash, unsubscribe, a sender's count        // and their mail to Trash) goes first: he is waiting on it. A failure here is the row's, said on it; reading        // goes on.        let copy = ctx.sink.copy().ok();        if let Some(copy) = copy {            let _ = copy.refresh(ctx.sink.object());        }        let tally = self.shared.tally().ok();        let find = |external: &str| copy.and_then(|copy| copy.email_by_external_id(external).ok().flatten()).map(|(_, row)| acts::Mail::of_row(&row));        let retry_failed = !self.shared.retried.swap(true, std::sync::atomic::Ordering::SeqCst);        let sink = ctx.sink;        let land = |external: &str, raw: &[u8]| match copy {            Some(copy) => land_page(sink, copy, external, raw),            None => Err("this Mac holds no copy of your database yet".to_string()),        };        let erase = |gone: &[trash::GoneMail]| match copy {            Some(copy) => erase_trashed(sink.object(), copy, gone),            None => Err("this Mac holds no copy of your database yet".to_string()),        };        let helps = acts::Helps { mail: &find, post: &acts::post_one_click, listed: tally.as_deref(), retry_failed, land_page: &land, erase: &erase };        let _ = trash::drain(ctx.sink.object(), &credentials.address, &mut || self.shared.connect(&credentials), &helps);        let mut cursor = cursor.map(str::to_string);        let mut attempt = 0;        loop {            match self.read_once(&credentials, cursor.as_deref(), ctx, attempt) {                Ok(text) => return Ok(text),                Err((error, None, _)) => return Err(error),                Err((error, Some(lost), saved)) => {                    if saved.is_some() {                        cursor = saved;                    }                    if attempt >= RECONNECTS {                        return Err(match error {                            RunError::Failed(_) => RunError::Failed(format!("{} ({lost})", crate::panel::say("mail_test.dropped", &[]))),                            other => other,                        });                    }                    attempt += 1;                    ctx.check()?;                    std::thread::sleep(Duration::from_secs(2 * u64::from(attempt)));                }            }        }    }    fn command(&self, name: &str, args: &Value) -> Result<Value, String> {        match name {            "credentials" => {                let address = args.get("address").and_then(Value::as_str).unwrap_or("").trim().to_string();                let password = args.get("password").and_then(Value::as_str).unwrap_or("").to_string();                if address.is_empty() || password.is_empty() {                    // Removed on the panel: no account, so nothing refused either; the panel offers Add.                    *self.shared.refused.lock().unwrap_or_else(|p| p.into_inner()) = None;                    *self.shared.credentials.lock().unwrap_or_else(|p| p.into_inner()) = None;                    return Ok(serde_json::json!({}));                }                let tls = args.get("imapTls").and_then(Value::as_bool).unwrap_or(true);                let server = args.get("imapHost").and_then(Value::as_str).and_then(|host| parse_host(host, tls));                *self.shared.credentials.lock().unwrap_or_else(|p| p.into_inner()) =                    Some(Credentials { address, password, server });                *self.shared.refused.lock().unwrap_or_else(|p| p.into_inner()) = None;                Ok(serde_json::json!({}))            }            "test" => Ok(self.shared.test(args)),            other => Err(format!("mail takes no {other}")),        }    }    fn watch(&self, wake: Wake, stopping: Stopping) {        *self.shared.wake.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::clone(&wake));        let shared = Arc::clone(&self.shared);        let _ = std::thread::Builder::new()            .name("cotton-mail-idle".to_string())            .spawn(move || idle_loop(&shared, &wake, &stopping));    }}/// Sleep `wait`, looking up every second; `false` when the app is stopping.fn rest(wait: Duration, stopping: &Stopping) -> bool {    let mut left = wait;    while !left.is_zero() {        if stopping() {            return false;        }        let step = left.min(Duration::from_secs(1));        std::thread::sleep(step);        left -= step;    }    !stopping()}/// INBOX in IDLE until the app stops: each change wakes the source, a/// dropped connection is dialled again with a growing wait.fn idle_loop(shared: &Shared, wake: &Wake, stopping: &Stopping) {    let mut backoff = Duration::from_secs(5);    while !stopping() {        let Some(credentials) = shared.credentials() else {            if !rest(Duration::from_secs(5), stopping) {                return;            }            continue;        };        if shared.refused.lock().unwrap_or_else(|p| p.into_inner()).is_some() {            if !rest(Duration::from_secs(30), stopping) {                return;            }            continue;        }        let wait = match idle_session(shared, &credentials, wake, stopping) {            Ok(()) => return,            // The server has no IDLE: the schedule reads it.            Err(None) => QUARTER_HOUR,            Err(Some(_)) => {                let wait = backoff;                backoff = (backoff * 2).min(IDLE_BACKOFF_MAX);                wait            }        };        if !rest(wait, stopping) {            return;        }    }}/// One connection's IDLE; `Ok` only when the app stops. `Err(None)` is a/// server without IDLE.fn idle_session(shared: &Shared, credentials: &Credentials, wake: &Wake, stopping: &Stopping) -> Result<(), Option<ImapError>> {    let mut client = shared.connect(credentials).map_err(Some)?;    if !client.can("IDLE") {        client.logout();        return Err(None);    }    client.examine("INBOX").map_err(Some)?;    loop {        match client.idle(IDLE_WINDOW, &**stopping).map_err(Some)? {            Idled::Changed => wake(),            Idled::Quiet => {}            Idled::Stopped => {                client.logout();                return Ok(());            }        }    }}