Cotton code
198 lines · 9.3 KB · RustRaw
//! The whole mailbox, newest first (owner, 24 Nov 2026: "pull ALL mail history newest year first ... and keep for//! every mail List-Unsubscribe, List-Unsubscribe-Post, List-Id, Precedence, Auto-Submitted, the Gmail category//! labels and the Seen flag (re-read these for mail already held)").//!//! The walk is the backfill's ([`super`]: the newest year first, newest UID first, [`super::BACKFILL_PER_RUN`]//! a run), begun again once from the top of the mailbox when a cursor has not walked it with these facts yet//! ([`HISTORY`]). Every page's metadata carries the five headers ([`HEADER_FIELDS`], a few hundred bytes a mail,//! never the body), so://!//! - a mail the person's database already holds gets only what changed on it: the headers, its Gmail categories//!   and labels, read or not, starred, in the inbox. Nothing at all is sent when nothing changed;//! - a mail it does not hold is fetched whole and lands as the backfill always landed it, with those facts.//!//! Gmail's categories are not IMAP labels; Gmail's own search finds them (`X-GM-RAW "category:social"`, one search//! per category over the page's UID span), and they are kept as the Gmail API spells them (`CATEGORY_SOCIAL`), in//! the row's `labels` like every other label.//!//! How far it has come is in the cursor (`historyDone` of `historyTotal`, back to `historyReached`), which the//! Mac's panel reads, and in the person's `mail_history` row, which the phones read. Neither says a word of any//! mail. A run that leaves more to walk asks for the next after [`HISTORY_REST`], never at once, so the walk is//! a steady trickle the person's database takes in small pieces; new mail is read first in every run and IDLE//! wakes a run the moment it lands, so the walk never holds new mail back.//!//! Size: the walk stops bringing mail it does not hold once what it brought would weigh [`HISTORY_BYTES_MAX`]//! (the person's database must stay well under the 10 GB a Durable Object holds; coordinator, 24 Nov 2026://! stop before 7 GB), and says so (`held`). The re-read of held mail goes on: it adds a few hundred bytes a mail.use std::collections::HashSet;use std::time::Duration;use serde_json::{Map, Value};/// The cursor's mark that this mailbox is walked with the headers, categories and Seen kept.pub const HISTORY: u32 = 2;/// The headers a page's metadata carries: the Message-ID (which row a mail is) and the five kept.pub const HEADER_FIELDS: &str =    "BODY.PEEK[HEADER.FIELDS (MESSAGE-ID LIST-UNSUBSCRIBE LIST-UNSUBSCRIBE-POST LIST-ID PRECEDENCE AUTO-SUBMITTED)]";/// Each kept header and the `email` column it fills.pub const HEADER_COLUMNS: [(&str, &str); 5] = [    ("list-unsubscribe", "list_unsubscribe"),    ("list-unsubscribe-post", "list_unsubscribe_post"),    ("list-id", "list_id"),    ("precedence", "precedence"),    ("auto-submitted", "auto_submitted"),];/// Gmail's categories: the search word and the label the Gmail API gives it.pub const CATEGORIES: [(&str, &str); 4] = [    ("social", "CATEGORY_SOCIAL"),    ("promotions", "CATEGORY_PROMOTIONS"),    ("updates", "CATEGORY_UPDATES"),    ("forums", "CATEGORY_FORUMS"),];/// A kept header's longest value: a List-Unsubscribe line is a URL or two.const HEADER_MAX: usize = 2048;/// How long after a run with more to walk the next one starts.pub const HISTORY_REST: Duration = Duration::from_secs(20);/// What the walk may add in mail the database did not hold, in bytes as the object keeps them.pub const HISTORY_BYTES_MAX: u64 = 3_000_000_000;/// What one brought mail weighs at the object beyond its row's own bytes: its conversation's share, its people/// and its search tokens (subject and the body's first 2 KB, a token row each), measured on his copy as about/// 7 KB a mail beyond the sealed row.pub const MAIL_OVERHEAD_BYTES: u64 = 7_000;/// The headers out of a `HEADER.FIELDS` answer.#[derive(Debug, Clone, Default, PartialEq)]pub struct Headers {    pub message_id: Option<String>,    /// Every kept column, `null` when the mail has no such header.    pub columns: Map<String, Value>,}pub fn headers(raw: &[u8]) -> Headers {    let text = String::from_utf8_lossy(raw);    // Unfold: a line that starts with white space continues the one before.    let mut lines: Vec<String> = Vec::new();    for line in text.split("\r\n").flat_map(|l| l.split('\n')) {        if line.starts_with([' ', '\t']) {            if let Some(last) = lines.last_mut() {                last.push(' ');                last.push_str(line.trim());                continue;            }        }        if !line.trim().is_empty() {            lines.push(line.to_string());        }    }    let mut out = Headers::default();    for (_, column) in HEADER_COLUMNS {        out.columns.insert(column.to_string(), Value::Null);    }    for line in lines {        let Some((name, value)) = line.split_once(':') else { continue };        let name = name.trim().to_ascii_lowercase();        let value = value.trim();        if value.is_empty() {            continue;        }        if name == "message-id" {            out.message_id.get_or_insert_with(|| value.to_string());            continue;        }        if let Some((_, column)) = HEADER_COLUMNS.iter().find(|(header, _)| *header == name) {            if out.columns[*column].is_null() {                let mut clipped: String = value.chars().take(HEADER_MAX).collect();                // Senders 3 (CONTRACT): `precedence` is kept lower-cased (bulk, list, junk).                if *column == "precedence" {                    clipped = clipped.to_ascii_lowercase();                }                out.columns.insert((*column).to_string(), Value::from(clipped));            }        }    }    out}/// `labels` with the Gmail categories the searches found for this mail, each once.pub fn with_categories(mut labels: Vec<String>, categories: &[&str]) -> Vec<String> {    for label in categories {        if !labels.iter().any(|have| have == label) {            labels.push((*label).to_string());        }    }    labels}/// The mail's Gmail category as Senders 3 keeps it (`gmail_category`): `promotions`, `updates`, `social`, `forums`,/// or `primary` when Gmail's searches put it in none.pub fn gmail_category(categories: &[&str]) -> &'static str {    CATEGORIES.iter().find(|(_, label)| categories.contains(label)).map(|(word, _)| *word).unwrap_or("primary")}/// What of `wanted` differs from the row the database holds: labels compare as sets, a missing value is `null`.pub fn changed(wanted: &Map<String, Value>, held: &Map<String, Value>) -> Map<String, Value> {    let set = |value: Option<&Value>| -> HashSet<String> {        value.and_then(Value::as_array).into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect()    };    wanted        .iter()        .filter(|(key, value)| {            let have = held.get(key.as_str());            if key.as_str() == "labels" {                return set(Some(value)) != set(have);            }            match have {                None => !value.is_null(),                Some(have) => have != *value,            }        })        .map(|(key, value)| (key.clone(), value.clone()))        .collect()}/// Whether a held row's `sent_at` is a date a mail can carry (`mail_date`'s years, 1900 to 2100).pub fn believable_at(at: &str) -> bool {    at.get(..4).and_then(|y| y.parse::<i32>().ok()).is_some_and(|year| super::mail_date::YEARS.contains(&year))}/// `2015-03-04T…` → `2015-03-04`: how far back, never a time.pub fn day_of(at: &str) -> Option<String> {    (at.len() >= 10 && at.as_bytes()[4] == b'-').then(|| at[..10].to_string())}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    #[test]    fn the_five_headers_are_read_unfolded_and_the_missing_are_null() {        let raw = b"Message-ID: <a@example.org>\r\nList-Unsubscribe: <https://example.org/u/1>,\r\n <mailto:u@example.org>\r\nList-Unsubscribe-Post: List-Unsubscribe=One-Click\r\nPRECEDENCE: Bulk\r\n\r\n";        let read = headers(raw);        assert_eq!(read.message_id.as_deref(), Some("<a@example.org>"));        assert_eq!(read.columns["list_unsubscribe"], "<https://example.org/u/1>, <mailto:u@example.org>");        assert_eq!(read.columns["list_unsubscribe_post"], "List-Unsubscribe=One-Click");        assert_eq!(read.columns["precedence"], "bulk", "lower-cased");        assert!(read.columns["list_id"].is_null() && read.columns["auto_submitted"].is_null());    }    #[test]    fn only_what_moved_is_sent_and_labels_are_a_set() {        let wanted = json!({ "labels": ["INBOX", "CATEGORY_UPDATES"], "unread": false, "list_id": null, "precedence": "bulk" });        let held = json!({ "labels": ["CATEGORY_UPDATES", "INBOX"], "unread": true });        let moved = changed(wanted.as_object().unwrap(), held.as_object().unwrap());        assert_eq!(Value::Object(moved), json!({ "unread": false, "precedence": "bulk" }));        assert_eq!(with_categories(vec!["INBOX".into()], &["CATEGORY_SOCIAL", "INBOX"]), vec!["INBOX", "CATEGORY_SOCIAL"]);        assert_eq!(day_of("2015-03-04T10:00:00.000Z").as_deref(), Some("2015-03-04"));        assert!(believable_at("2015-03-04T10:00:00.000Z") && !believable_at("2611-09-16T10:00:00.000Z"));        assert_eq!((gmail_category(&["CATEGORY_PROMOTIONS"]), gmail_category(&[])), ("promotions", "primary"));    }}