Cotton code
423 lines · 11.7 KB · RustRaw
//! What the budget may take, and in what order — against a real seeded file.//!//! Every instant is explicit and every row is synthetic//! ([nothing-real-ever-goes-in-cotton-s-public-tree]): the crate reads no clock,//! so a failure here is reproducible.use super::*;use crate::media_holdings::holding_id;use crate::test_support::{seeded_file, WORKSPACE};const THIS_PHONE: &str = "device:01J0000000000000000000000A";const THE_MAC: &str = "device:01J0000000000000000000000B";const AN_OLD_PHONE: &str = "device:01J0000000000000000000000C";const NOW: &str = "2026-09-16T09:00:00.000Z";fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn key(letter: char) -> String {    format!("{WORKSPACE}/photos/{}.heic", letter.to_string().repeat(64))}fn file() -> Driver {    let db = seeded_file(THIS_PHONE);    for (device, name) in [        (THIS_PHONE, "The invented phone"),        (THE_MAC, "The invented Mac"),        (AN_OLD_PHONE, "An older invented phone"),    ] {        db.run(            "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \             approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",            &[                text(&format!("dev:{device}")),                text(WORKSPACE),                text(device),                text(name),                text("2026-09-01T09:00:00.000Z"),                text(THIS_PHONE),                text("2026-09-01T09:00:00.000Z"),                text("2026-09-01T09:00:00.000Z"),            ],        )        .expect("the device row");    }    db}/// One `_media` row, written straight in so a test can state every column the/// eviction predicate reads without going through four setters.struct Filed<'a> {    key: &'a str,    tier: Option<&'a str>,    pinned: bool,    captured_here: bool,    last_viewed_at: Option<&'a str>,    size_bytes: i64,    local_path: Option<&'a str>,}impl Default for Filed<'_> {    fn default() -> Filed<'static> {        Filed {            key: "",            tier: Some("original"),            pinned: false,            captured_here: false,            last_viewed_at: None,            size_bytes: 1_000_000,            local_path: Some("/tmp/invented"),        }    }}fn file_row(db: &Driver, row: &Filed<'_>) {    db.run(        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, attempts, created_at, updated_at, tier, pinned, last_viewed_at, captured_here) \         VALUES (?,?,?,?,?,?,'synced',0,?,?,?,?,?,?)",        &[            text(row.key),            text(WORKSPACE),            text(&"f".repeat(64)),            text("image/heic"),            SqlValue::Integer(row.size_bytes),            row.local_path.map_or(SqlValue::Null, text),            text(NOW),            text(NOW),            row.tier.map_or(SqlValue::Null, text),            SqlValue::Integer(i64::from(row.pinned)),            row.last_viewed_at.map_or(SqlValue::Null, text),            SqlValue::Integer(i64::from(row.captured_here)),        ],    )    .expect("the ledger row");}/// A hold recorded by another device — what a peer's op folds to when it/// arrives.fn a_peers_hold(db: &Driver, device_id: &str, object_key: &str) {    let id = holding_id(device_id, object_key, Tier::Original);    db.run(        "INSERT INTO cotton_media_holdings (id, workspace_id, object_key, device_id, tier, \         bytes, verified_at, created_at, updated_at, _hlc) VALUES (?,?,?,?,?,?,?,?,?,?)",        &[            text(&id),            text(WORKSPACE),            text(object_key),            text(device_id),            text(Tier::Original.as_str()),            SqlValue::Integer(4_194_304),            text(NOW),            text(NOW),            text(NOW),            text(&format!("1789549200000:0001:{device_id}")),        ],    )    .expect("the peer's hold");}fn keys(db: &Driver) -> Vec<String> {    eviction_candidates(db, WORKSPACE, 50)        .expect("the candidates")        .into_iter()        .map(|candidate| candidate.key)        .collect()}#[test]fn a_photo_this_phone_captured_is_never_evicted() {    let db = file();    let mine = key('a');    let theirs = key('b');    file_row(        &db,        &Filed {            key: &mine,            captured_here: true,            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &theirs,            ..Filed::default()        },    );    assert_eq!(keys(&db), vec![theirs.clone()]);    // And it is not in the number a screen prints either, even with the whole    // household holding it: `captured_here` is the fence, not the holdings.    a_peers_hold(&db, THE_MAC, &mine);    a_peers_hold(&db, THE_MAC, &theirs);    assert_eq!(        evictable_bytes(&db, WORKSPACE, THIS_PHONE).expect("the bytes"),        1_000_000,        "only the photo this phone did not take"    );}#[test]fn least_recently_viewed_goes_first_and_pinned_never_goes() {    let db = file();    let never_viewed = key('a');    let viewed_long_ago = key('b');    let viewed_today = key('c');    let pinned_and_never_viewed = key('d');    file_row(        &db,        &Filed {            key: &viewed_today,            last_viewed_at: Some("2026-09-16T08:00:00.000Z"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &viewed_long_ago,            last_viewed_at: Some("2026-01-01T08:00:00.000Z"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &never_viewed,            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &pinned_and_never_viewed,            pinned: true,            ..Filed::default()        },    );    assert_eq!(        keys(&db),        vec![never_viewed, viewed_long_ago, viewed_today],        "never viewed first, then oldest — and the pinned one is not in the list at all"    );}#[test]fn thumbs_are_never_candidates_and_do_not_count() {    let db = file();    let original = key('a');    let display = key('b');    let thumb = key('c');    let a_tier_this_build_cannot_name = key('d');    let no_tier_at_all = key('e');    file_row(        &db,        &Filed {            key: &original,            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &display,            tier: Some("display"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &thumb,            tier: Some("thumb"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &a_tier_this_build_cannot_name,            tier: Some("d3200"),            ..Filed::default()        },    );    // A row from before schema v12, or a document, or a film's poster: NO tier    // at all. It is not the original — reading it as one is what would start    // the first eviction pass on the oldest rows in the file.    file_row(        &db,        &Filed {            key: &no_tier_at_all,            tier: None,            ..Filed::default()        },    );    for object in [        &original,        &display,        &thumb,        &a_tier_this_build_cannot_name,        &no_tier_at_all,    ] {        a_peers_hold(&db, THE_MAC, object);    }    assert_eq!(keys(&db), vec![original, display]);    assert_eq!(        evictable_bytes(&db, WORKSPACE, THIS_PHONE).expect("the bytes"),        2_000_000,        "the thumbnail's bytes are not the budget's, and neither are a rendition this \         build has never heard of, nor a row that names no rendition at all"    );}#[test]fn a_row_with_no_file_on_this_device_is_not_a_candidate() {    let db = file();    let gone = key('a');    file_row(        &db,        &Filed {            key: &gone,            local_path: None,            ..Filed::default()        },    );    assert!(keys(&db).is_empty());}#[test]fn the_number_a_screen_prints_counts_only_what_a_live_other_device_holds() {    let db = file();    let only_here = key('a');    let also_on_the_mac = key('b');    let only_on_a_revoked_phone = key('c');    for object in [&only_here, &also_on_the_mac, &only_on_a_revoked_phone] {        file_row(            &db,            &Filed {                key: object,                ..Filed::default()            },        );    }    // This phone holds all three; the question is who ELSE does.    for object in [&only_here, &also_on_the_mac, &only_on_a_revoked_phone] {        a_peers_hold(&db, THIS_PHONE, object);    }    a_peers_hold(&db, THE_MAC, &also_on_the_mac);    a_peers_hold(&db, AN_OLD_PHONE, &only_on_a_revoked_phone);    db.run(        "UPDATE cotton_devices SET revoked_at = ? WHERE device_id = ?",        &[text("2026-09-15T09:00:00.000Z"), text(AN_OLD_PHONE)],    )    .expect("the revocation");    assert_eq!(        evictable_bytes(&db, WORKSPACE, THIS_PHONE).expect("the bytes"),        1_000_000,        "a revoked phone is not a second holder, and this phone is not its own"    );}#[test]fn the_budget_total_counts_files_this_device_holds_and_never_a_thumbnail() {    let db = file();    let original = key('a');    let display = key('b');    let thumb = key('c');    let gone_from_here = key('d');    file_row(        &db,        &Filed {            key: &original,            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &display,            tier: Some("display"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &thumb,            tier: Some("thumb"),            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &gone_from_here,            local_path: None,            ..Filed::default()        },    );    assert_eq!(        budgeted_bytes(&db, WORKSPACE).expect("the total"),        2_000_000,        "the original and the display rendition — never the thumbnail, which is \         never evicted, and never a row whose file left this device"    );    // A PINNED file and a CAPTURE still COUNT, although neither can ever be    // taken. They occupy the disk, so a total that left them out would tell a    // person their phone is emptier than it is — and the budget is about what    // is there, not about what could go. What could go is `evictable_bytes`.    file_row(        &db,        &Filed {            key: &key('e'),            pinned: true,            ..Filed::default()        },    );    file_row(        &db,        &Filed {            key: &key('f'),            captured_here: true,            ..Filed::default()        },    );    assert_eq!(budgeted_bytes(&db, WORKSPACE).expect("the total"), 4_000_000);}#[test]fn an_evicted_row_keeps_everything_but_the_path() {    let db = file();    let object = key('a');    file_row(        &db,        &Filed {            key: &object,            last_viewed_at: Some("2026-01-01T08:00:00.000Z"),            ..Filed::default()        },    );    mark_evicted(&db, &object, "2026-09-16T10:00:00.000Z").expect("the eviction");    let row = crate::media_ledger::media_by_key(&db, &object)        .expect("the read")        .expect("the row");    assert_eq!(row.local_path, None);    assert_eq!(        row.last_viewed_at.as_deref(),        Some("2026-01-01T08:00:00.000Z"),        "a file taken and fetched again must not jump the queue for having been taken"    );    assert_eq!(row.state, "synced", "the bytes are still up; they are just not here");    assert!(keys(&db).is_empty(), "and it is no longer a candidate");}