Cotton code
213 lines · 11.7 KB · RustRaw
//! MAIL PREDICATE phase 2 and PHASE 2 PHONE 2 (the coordinator, 27 Nov 2026): the landing times of mail this copy held//! before schema 157. A mail cut covers mail by when it landed on the server, which a row pulled since 157 carries//! (`cotton_emails.landed_at`, kept in `_mail_landed` by the store's triggers). Mail held before it has none, and no//! cut covers it (rule 1) until this fills it: never by pulling his gigabytes again, but by a paged read of the//! object's (id, landed_at) for mail alone (`GET /v1/landed`), applied after a pass in short holds of the writer,//! resumable from the last id applied (`_landed_fill`, device-local).//!//! It writes `_mail_landed` only, beside the mail row, never the row itself: a NULL turned to text on the wide row//! rewrites the whole record, body and overflow pages included (item 5, measured: the lane report has the numbers).//!//! Once the pages are done, mail the object gave no time for is asked for again by id once a day//! ([`reask`]); after one such round, a Delete says plainly that those are not covered, never that they will go.//!//! Cost at 300,000 mails: 60 pages of 5,000 (about 70 bytes a mail: some 21 MB in all, far less compressed, since//! most share the object's one moment), and 300 writes of 1,000 narrow rows by primary key, each a short hold.use std::time::{Duration, Instant};use rusqlite::OptionalExtension;use serde_json::Value;use crate::shell::client::ClientController;use cotton_core::rules::mail_predicate::cuts;/// What the object is asked for at once.pub(crate) const PAGE: usize = 5_000;/// How many rows one hold of the writer applies.pub(crate) const SLICE: usize = 1_000;/// How long one pass's turn fills before the next pass goes on.pub(crate) const BUDGET: Duration = Duration::from_secs(3);/// How often mail the pages gave no time for is asked for again, by id.pub(crate) const REASK: chrono::Duration = chrono::Duration::days(1);/// The most ids one re-ask names (the object answers at most 500 a request).pub(crate) const REASK_IDS: usize = 500;const STATE: &str = "_landed_fill";fn state_table(file: &rusqlite::Connection) -> Result<(), String> {    file.execute_batch(&format!("CREATE TABLE IF NOT EXISTS {STATE} (one INTEGER PRIMARY KEY CHECK (one = 1), after TEXT, done INTEGER NOT NULL DEFAULT 0, asked_at TEXT, rounds INTEGER NOT NULL DEFAULT 0)"))        .map_err(|error| format!("the landing fill could not be written ({error})"))}/// Mail this copy holds with no landing time, as SQL true of `e`.fn unlanded(e: &str) -> String {    format!("NOT EXISTS (SELECT 1 FROM {} l WHERE l.id = {e}.id)", cuts::LANDED)}/// The fill's place: none owed, or owed from after this id (`""` from the first).pub(crate) fn owed(file: &rusqlite::Connection) -> Result<Option<String>, String> {    let e = |error: rusqlite::Error| format!("the landing fill could not be read ({error})");    let has_state = file.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [STATE], |_| Ok(())).optional().map_err(e)?.is_some();    if has_state {        return file.query_row(&format!("SELECT CASE WHEN done = 1 THEN NULL ELSE coalesce(after, '') END FROM {STATE}"), [], |r| r.get(0)).optional().map_err(e).map(Option::flatten);    }    // First look: owed only when some mail held has no landing time.    let missing = file.query_row(&format!("SELECT 1 FROM {} e WHERE {} LIMIT 1", cuts::EMAILS, unlanded("e")), [], |_| Ok(())).optional().map_err(e)?.is_some();    Ok(missing.then(String::new))}/// One slice applied: each held mail without a landing time takes the object's, pinned, in `_mail_landed` (the/// mail row is never written); the place moves to the last id of the slice, and `done` once the object said no more/// follow. A re-ask (`place` false) leaves the place as it is.pub(crate) fn apply(file: &rusqlite::Connection, rows: &[(String, String)], done: bool) -> Result<usize, String> {    apply_in(file, rows, Some(done))}fn apply_in(file: &rusqlite::Connection, rows: &[(String, String)], done: Option<bool>) -> Result<usize, String> {    let e = |error: rusqlite::Error| format!("the landing fill could not be written ({error})");    let autocommit = file.is_autocommit();    if autocommit {        file.execute_batch("BEGIN IMMEDIATE").map_err(e)?;    }    let result = (|| {        state_table(file)?;        let key = format!("{}(from_email)", cuts::KEY_FUNCTION);        let mut statement = file            .prepare_cached(&format!(                "INSERT INTO {} (id, landed_at, \"key\", domain) SELECT id, ?2, {key}, substr({key}, instr({key}, '@')) FROM {} WHERE id = ?1 AND from_email IS NOT NULL ON CONFLICT (id) DO NOTHING",                cuts::LANDED,                cuts::EMAILS            ))            .map_err(e)?;        let mut filled = 0;        for (id, at) in rows {            let Some(at) = cuts::normalise_time(at) else { continue };            filled += statement.execute([id.as_str(), at.as_str()]).map_err(e)?;        }        if let Some(done) = done {            let after = rows.last().map(|(id, _)| id.clone());            file.execute(&format!("INSERT INTO {STATE} (one, after, done) VALUES (1, ?1, ?2) ON CONFLICT (one) DO UPDATE SET after = coalesce(excluded.after, after), done = excluded.done"), rusqlite::params![after, done as i64]).map_err(e)?;        }        Ok(filled)    })();    if autocommit {        file.execute_batch(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }).map_err(e)?;    }    result}/// The pages of one answer of `GET /v1/landed`: its rows, and whether more follow.pub(crate) fn page_of(answer: &Value) -> (Vec<(String, String)>, bool) {    let rows = answer["rows"].as_array().into_iter().flatten().filter_map(|r| Some((r.get(0)?.as_str()?.to_string(), r.get(1)?.as_str()?.to_string()))).collect();    (rows, answer["after"].is_string())}fn query_part(value: &str) -> String {    value.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()}/// After a pass: pages from the object applied in slices, for at most [`BUDGET`]; once they are done, the daily/// re-ask ([`reask`]). Answers whether the fill is done.pub(crate) fn fill(client: &ClientController) -> Result<bool, String> {    let started = Instant::now();    loop {        let Some(after) = client.with_file(|replica| owed(replica.driver.connection())).map_err(|e| e.to_string())? else {            reask(client)?;            return Ok(true);        };        // Owed: the place is kept from now, so `_mail_landed`'s indexes wait for the fill's end (index_later).        client.with_writer(|replica| begin(replica.driver.connection())).map_err(|e| e.to_string())?;        let Some(door) = client.object_door() else { return Ok(false) };        let path = if after.is_empty() { format!("/v1/landed?limit={PAGE}") } else { format!("/v1/landed?limit={PAGE}&after={}", query_part(&after)) };        let answer = door.send("GET", &path, None).map_err(|refused| format!("the object's landing times were not read ({})", refused.message))?;        let (rows, more) = page_of(&answer);        let slices: Vec<&[(String, String)]> = if rows.is_empty() { vec![&[]] } else { rows.chunks(SLICE).collect() };        let last = slices.len() - 1;        for (n, slice) in slices.into_iter().enumerate() {            client.with_writer(|replica| apply(replica.driver.connection(), slice, n == last && !more)).map_err(|e| e.to_string())?;            std::thread::sleep(Duration::from_millis(10));        }        if !more {            return Ok(true);        }        if started.elapsed() >= BUDGET {            return Ok(false);        }    }}/// The fill's place, made where it is not yet: from then `_mail_landed`'s indexes wait until it is done, so the fill/// writes the bare table in id order and the indexes are made once after (`cotton_store::index_later`).pub(crate) fn begin(file: &rusqlite::Connection) -> Result<(), String> {    state_table(file)?;    file.execute(&format!("INSERT OR IGNORE INTO {STATE} (one, done) VALUES (1, 0)"), []).map(|_| ()).map_err(|error| format!("the landing fill could not be written ({error})"))}/// Up to `limit` ids of mail this copy holds with no landing time.pub(crate) fn missing(file: &rusqlite::Connection, limit: usize) -> Result<Vec<String>, String> {    let e = |error: rusqlite::Error| format!("the mail with no landing time could not be read ({error})");    let mut statement = file.prepare(&format!("SELECT e.id FROM {} e WHERE {} LIMIT {limit}", cuts::EMAILS, unlanded("e"))).map_err(e)?;    let ids = statement.query_map([], |r| r.get(0)).map_err(e)?.collect::<Result<Vec<String>, _>>().map_err(e)?;    Ok(ids)}/// Whether a re-ask is due at `now`: the pages done, and none asked within [`REASK`].pub(crate) fn reask_due(file: &rusqlite::Connection, now: chrono::DateTime<chrono::Utc>) -> Result<bool, String> {    let e = |error: rusqlite::Error| format!("the landing fill could not be read ({error})");    let row: Option<(i64, Option<String>)> = file.query_row(&format!("SELECT done, asked_at FROM {STATE}"), [], |r| Ok((r.get(0)?, r.get(1)?))).optional().map_err(e)?;    Ok(match row {        Some((1, None)) => true,        Some((1, Some(at))) => chrono::DateTime::parse_from_rfc3339(&at).map_or(true, |at| now - at.with_timezone(&chrono::Utc) >= REASK),        _ => false,    })}/// A round of the re-ask written: the rows the object answered, and when it was asked.pub(crate) fn asked(file: &rusqlite::Connection, rows: &[(String, String)], now: chrono::DateTime<chrono::Utc>) -> Result<usize, String> {    let filled = apply_in(file, rows, None)?;    file.execute(&format!("UPDATE {STATE} SET asked_at = ?1, rounds = rounds + 1"), [now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)])        .map_err(|error| format!("the landing fill could not be written ({error})"))?;    Ok(filled)}/// Once a day after the pages: the mail still without a landing time asked for by id (at most [`REASK_IDS`]).pub(crate) fn reask(client: &ClientController) -> Result<(), String> {    let now = client.clock().now();    let ids = client        .with_file(|replica| {            let file = replica.driver.connection();            if !reask_due(file, now)? {                return Ok(None);            }            missing(file, REASK_IDS).map(Some)        })        .map_err(|e| e.to_string())?;    let Some(ids) = ids else { return Ok(()) };    let rows = if ids.is_empty() {        Vec::new()    } else {        let Some(door) = client.object_door() else { return Ok(()) };        let path = format!("/v1/landed?{}", ids.iter().map(|id| format!("id={}", query_part(id))).collect::<Vec<_>>().join("&"));        let answer = door.send("GET", &path, None).map_err(|refused| format!("the object's landing times were not read ({})", refused.message))?;        page_of(&answer).0    };    client.with_writer(|replica| asked(replica.driver.connection(), &rows, now)).map_err(|e| e.to_string())?;    Ok(())}/// Whether this copy has asked for every landing time it can: the pages done and one re-ask made. From then, mail/// still without one is said to be not covered, never to be waiting.pub(crate) fn caught_up(file: &rusqlite::Connection) -> Result<bool, String> {    let e = |error: rusqlite::Error| format!("the landing fill could not be read ({error})");    let has_state = file.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [STATE], |_| Ok(())).optional().map_err(e)?.is_some();    if !has_state {        // Never owed: every mail held came with its time.        return Ok(owed(file)?.is_none());    }    Ok(file.query_row(&format!("SELECT done = 1 AND rounds > 0 FROM {STATE}"), [], |r| r.get::<_, bool>(0)).optional().map_err(e)?.unwrap_or(false))}#[cfg(test)]#[path = "landed_tests.rs"]mod tests;