Cotton code
173 lines · 6.0 KB · RustRaw
//! The identity of an ingested email — the idempotency key that makes//! re-importing the same mail free.//!//! Two forms://!//! - `mid:` the RFC 5322 Message-ID, normalized and hashed. The mail world's//!   own primary key; present on virtually all real mail.//! - `eml2:` the content-fingerprint fallback for mail with no Message-ID —//!   the txt2 discipline verbatim: UTC minute bucket, normalized subject,//!   normalized body, occurrence index. NO sender, NO recipient, NO address//!   anywhere in the material, so identifying a person later changes nothing//!   about what a re-import skips.use std::collections::HashMap;use super::Result;use crate::fingerprint::message::{    digest32, material, minute_bucket, normalize_body_for_id,};use crate::js;pub const MESSAGE_ID_EXTERNAL_ID_PREFIX: &str = "mid:";pub const EMAIL_CONTENT_EXTERNAL_ID_PREFIX: &str = "eml2:";/// Message-ID as compared: angle brackets and whitespace stripped, lowercased.////// RFC 5322 local parts are case-sensitive in theory; no real mail system/// re-cases a Message-ID in flight, and a case-folded match that deduplicates/// one email is strictly better than a case-exact miss that duplicates it.////// The order is the TypeScript's exactly: `trim()`, then ONE leading `<`, then/// ONE trailing `>`, then `trim()` again, then lowercase.pub fn normalize_message_id(message_id: &str) -> String {    let trimmed = js_trim(message_id);    let without_open = trimmed.strip_prefix('<').unwrap_or(trimmed);    let without_close = without_open.strip_suffix('>').unwrap_or(without_open);    js_trim(without_close).to_lowercase()}/// JS `String.prototype.trim` — the ECMAScript whitespace class, not Rust's.fn js_trim(value: &str) -> &str {    value.trim_matches(js::is_js_whitespace)}/// `mid:<32 hex>` — hashed rather than stored verbatim so the column is/// uniform and never carries an unbounded header. `None` for an empty or/// whitespace Message-ID, so the caller falls through to the content form.pub fn message_id_external_id(message_id: Option<&str>) -> Option<String> {    let normalized = normalize_message_id(message_id?);    if normalized.is_empty() {        return None;    }    Some(format!(        "{MESSAGE_ID_EXTERNAL_ID_PREFIX}{}",        digest32(&material(&[normalized.into()]))    ))}/// Subject as identity material: whitespace collapsed, reply/forward chains/// stripped case-insensitively, lowercased — a re-export can re-case and/// re-wrap, never re-word.pub fn normalize_subject_for_id(subject: Option<&str>) -> String {    strip_reply_prefixes(subject.unwrap_or("")).to_lowercase()}/// The human reading of a thread's subject: `Re:`/`Fwd:` chains stripped,/// whitespace collapsed, casing kept.////// The TypeScript regex is `/^(\s*(re|fwd?|fw)\s*(\[\d+\])?\s*:)+/i` — one or/// more repetitions of the whole group, anchored, matched ONCE from the start.pub fn strip_reply_prefixes(subject: &str) -> String {    let rest = strip_prefix_chain(subject);    js::collapse_whitespace_and_trim(rest)}/// The anchored `(…)+` of the TypeScript regex, applied greedily.fn strip_prefix_chain(subject: &str) -> &str {    let mut rest = subject;    let mut matched_any = false;    loop {        match match_one_prefix(rest) {            Some(next) => {                rest = next;                matched_any = true;            }            // `(…)+` needs at least one repetition; with none the whole match            // fails and nothing is stripped.            None => return if matched_any { rest } else { subject },        }    }}/// One `\s* (re|fwd?|fw) \s* (\[\d+\])? \s* :` repetition.fn match_one_prefix(input: &str) -> Option<&str> {    let rest = skip_ws(input);    // Alternation order matters: `fwd?` is tried before `fw`, and `re` first.    let rest = ["re", "fwd", "fw"]        .into_iter()        .find_map(|word| strip_prefix_ci(rest, word))?;    let rest = skip_ws(rest);    let rest = strip_bracketed_digits(rest).unwrap_or(rest);    let rest = skip_ws(rest);    rest.strip_prefix(':')}fn skip_ws(input: &str) -> &str {    input.trim_start_matches(js::is_js_whitespace)}fn strip_prefix_ci<'a>(input: &'a str, needle: &str) -> Option<&'a str> {    let head: String = input.chars().take(needle.chars().count()).collect();    if head.to_lowercase() == needle {        Some(&input[head.len()..])    } else {        None    }}/// `(\[\d+\])?` — the `Re [2]:` form some clients write.fn strip_bracketed_digits(input: &str) -> Option<&str> {    let rest = input.strip_prefix('[')?;    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();    if digits.is_empty() {        return None;    }    rest[digits.len()..].strip_prefix(']')}pub struct EmailContentFingerprintInput<'a> {    pub sent_at: &'a str,    pub subject: Option<&'a str>,    pub body: &'a str,    /// 0 for the first email with this (minute, subject, body), 1 for the next.    pub occurrence: u64,}pub fn email_content_fingerprint(input: &EmailContentFingerprintInput<'_>) -> Result<String> {    let material = material(&[        minute_bucket(input.sent_at)?.into(),        normalize_subject_for_id(input.subject).into(),        normalize_body_for_id(input.body).into(),        input.occurrence.into(),    ]);    Ok(format!(        "{EMAIL_CONTENT_EXTERNAL_ID_PREFIX}{}",        digest32(&material)    ))}/// Occurrence counting for the fallback form, keyed on the same material the/// hash uses — one counter per thread.#[derive(Default)]pub struct EmailOccurrenceCounter {    seen: HashMap<String, u64>,}impl EmailOccurrenceCounter {    pub fn new() -> Self {        Self::default()    }    pub fn next(&mut self, sent_at: &str, subject: Option<&str>, body: &str) -> Result<u64> {        let key = material(&[            minute_bucket(sent_at)?.into(),            normalize_subject_for_id(subject).into(),            normalize_body_for_id(body).into(),        ]);        let count = self.seen.entry(key).or_insert(0);        let value = *count;        *count += 1;        Ok(value)    }}