Cotton code
996 lines · 41.0 KB · RustRaw
//! The drain half of `apps/cotton/__tests__/client/media.test.ts`.use std::sync::{Arc, Mutex};use cotton_core::media::keys::message_media_key;use cotton_store::media_ledger::{enqueue_media, media_by_key, MediaEnqueueInput};use super::*;use crate::media::uploads::{Phase, UploadWatch};use crate::media::media_file_path;use crate::seams::{Clock, FixedClock};use crate::test_support::{open_test_replica, WORKSPACE};use crate::transport::ServerRefusal;use rusqlite::types::Value as SqlValue;const THREAD: &str = "77777777-7777-4777-8777-777777777777";#[derive(Debug, Default)]struct FakeDeps {    put: Mutex<Vec<(String, String, std::path::PathBuf)>>,    refusal: Mutex<Option<ServerRefusal>>,}impl FakeDeps {    fn keys(&self) -> Vec<String> {        self.put.lock().expect("the log").iter().map(|(key, _, _)| key.clone()).collect()    }}/// The upload is a round trip in the real transport, so the fake asks the/// guard first: a drain that uploads while it holds the replica panics in/// these tests rather than stalling every screen on a phone.impl MediaDrainDeps for FakeDeps {    fn upload(&self, row: &MediaRowRef, local_path: &std::path::Path) -> Result<Landed, ServerRefusal> {        cotton_store::held::must_not_wait("the bytes going up");        self.put.lock().expect("the log").push((row.key.clone(), row.content_type.clone(), local_path.to_path_buf()));        if let Some(refusal) = self.refusal.lock().expect("the slot").clone() {            return Err(refusal);        }        Ok(Landed::Stored)    }}type MediaRowRef = cotton_store::media_ledger::MediaRow;fn queue_one(    replica: &crate::Replica,    layout: &crate::Layout,    after: Option<&str>,) -> (String, std::path::PathBuf) {    let sha256 = "a".repeat(64);    let path = media_file_path(layout, WORKSPACE, &sha256, "jpg");    std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");    std::fs::write(&path, b"synthetic bytes").expect("the file");    let key = message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg");    enqueue_media(        &replica.driver,        &MediaEnqueueInput {            key: key.clone(),            workspace_id: WORKSPACE.to_string(),            sha256,            content_type: "image/jpeg".to_string(),            size_bytes: 15,            local_path: Some(path.to_string_lossy().to_string()),            state: None,            after: after.map(str::to_string),            after_row_id: None,            now: "2026-09-08T10:00:00.000Z".to_string(),            tier: None,            captured_here: false,        },    )    .expect("a ledger row");    (key, path)}fn clock() -> Arc<dyn Clock> {    Arc::new(FixedClock::default_start())}fn watch() -> Arc<UploadWatch> {    Arc::new(UploadWatch::new())}#[test]fn it_puts_the_file_and_marks_the_row_synced() {    let (_dir, layout, replica) = open_test_replica();    let (key, path) = queue_one(&replica, &layout, None);    let deps = FakeDeps::default();    let row = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(        upload_one(&replica, &deps, &row, &FixedClock::default_start()),        Uploaded::Uploaded    );    assert_eq!(        *deps.put.lock().expect("the log"),        vec![(key.clone(), "image/jpeg".to_string(), path.clone())],        "the row's key and content type, off the file the ledger names"    );    let after = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(after.state, "synced");    assert!(path.is_file(), "the bytes stay on this device: the object is the backup");}#[test]fn it_keeps_a_row_pending_and_backs_it_off_when_the_upload_merely_failed() {    let (_dir, layout, replica) = open_test_replica();    let (key, _path) = queue_one(&replica, &layout, None);    let deps = FakeDeps::default();    *deps.refusal.lock().expect("the slot") =        Some(ServerRefusal::new("the object is having an afternoon", 503));    let row = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(        upload_one(&replica, &deps, &row, &FixedClock::default_start()),        Uploaded::Retry    );    let after = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(after.state, "pending");    assert_eq!(after.attempts, 1);    assert!(after.next_attempt_at.is_some(), "backed off, still queued");    assert_eq!(        after.last_error.as_deref(),        Some("the object is having an afternoon")    );}#[test]fn it_gives_up_on_a_refusal_the_object_will_repeat_and_says_why() {    let (_dir, layout, replica) = open_test_replica();    let (key, _path) = queue_one(&replica, &layout, None);    let deps = FakeDeps::default();    *deps.refusal.lock().expect("the slot") = Some(        ServerRefusal::new("a media file is at most 100 MB", 413).with_code("too_big".to_string()),    );    let row = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(        upload_one(&replica, &deps, &row, &FixedClock::default_start()),        Uploaded::Failed    );    let after = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(after.state, "failed");    assert_eq!(after.last_error.as_deref(), Some("a media file is at most 100 MB"));}/// RULE (R6): a rendition this device made goes up under its own key like any/// file (sealed by the transport): the object can draw nothing from a sealed/// original. One with no file here is settled without a byte moving.#[test]fn a_rendition_the_device_made_goes_up_and_one_with_no_file_is_settled() {    let (_dir, layout, replica) = open_test_replica();    let sha256 = "c".repeat(64);    let path = media_file_path(&layout, WORKSPACE, &sha256, "jpg");    std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");    std::fs::write(&path, b"a synthetic thumbnail").expect("the file");    let file_id = crate::test_support::file_id();    for key in [        cotton_core::media::keys::photo_thumb_key(file_id, &sha256),        cotton_core::media::keys::photo_display_key(file_id, &sha256),    ] {        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: key.clone(),                workspace_id: WORKSPACE.to_string(),                sha256: sha256.clone(),                content_type: "image/jpeg".to_string(),                size_bytes: 21,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: "2026-09-08T10:00:00.000Z".to_string(),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");        let deps = FakeDeps::default();        let row = media_by_key(&replica.driver, &key).expect("a read").expect("a row");        assert_eq!(upload_one(&replica, &deps, &row, &FixedClock::default_start()), Uploaded::Uploaded, "{key}");        assert_eq!(deps.keys(), vec![key.clone()], "the device's own {key} went up");        assert_eq!(media_by_key(&replica.driver, &key).expect("a read").expect("a row").state, "synced");    }    let unmade = cotton_core::media::keys::photo_thumb_key(file_id, &"d".repeat(64));    enqueue_media(        &replica.driver,        &MediaEnqueueInput {            key: unmade.clone(),            workspace_id: WORKSPACE.to_string(),            sha256: "d".repeat(64),            content_type: "image/jpeg".to_string(),            size_bytes: 21,            local_path: None,            state: None,            after: None,            after_row_id: None,            now: "2026-09-08T10:00:00.000Z".to_string(),            tier: None,            captured_here: false,        },    )    .expect("a ledger row");    let deps = FakeDeps::default();    let row = media_by_key(&replica.driver, &unmade).expect("a read").expect("a row");    assert_eq!(upload_one(&replica, &deps, &row, &FixedClock::default_start()), Uploaded::Drawn);    assert!(deps.keys().is_empty());    assert_eq!(media_by_key(&replica.driver, &unmade).expect("a read").expect("a row").state, "synced");}#[test]fn it_tells_a_repeatable_refusal_from_one_worth_retrying() {    for status in [400u16, 403, 413, 415] {        assert!(            is_terminal_refusal(&ServerRefusal::new("no", status)),            "{status}"        );    }    for status in [0u16, 401, 404, 408, 429, 500, 502, 503] {        assert!(            !is_terminal_refusal(&ServerRefusal::new("later", status)),            "{status}"        );    }    assert!(        !is_terminal_refusal(&ServerRefusal::new("the parts did not make a file", 400).with_code("bad_upload".to_string())),        "parts that did not make a file go up again as a new upload"    );    // A full space waits for room (SPACE.md): the file is never given up on.    assert!(        !is_terminal_refusal(&ServerRefusal::new("Your space for photos and files is full.", 413).with_code("space_full".to_string())),        "a full space waits for room"    );}#[test]fn it_gives_up_on_a_row_whose_bytes_have_left_this_device() {    let (_dir, layout, replica) = open_test_replica();    let (key, path) = queue_one(&replica, &layout, None);    cotton_store::media_ledger::set_media_local_path(        &replica.driver,        &key,        None,        "2026-09-08T10:00:00.000Z",    )    .expect("the path clears");    std::fs::remove_file(&path).expect("the bytes go");    let deps = FakeDeps::default();    let row = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a row");    assert_eq!(        upload_one(&replica, &deps, &row, &FixedClock::default_start()),        Uploaded::Failed    );    assert!(deps.keys().is_empty(), "nothing went up for bytes that are not here");    assert_eq!(        media_by_key(&replica.driver, &key)            .expect("a read")            .expect("a row")            .last_error            .as_deref(),        Some("these bytes are not on this device any more")    );}#[test]fn a_key_outside_this_workspace_is_refused_before_a_byte_moves() {    let (_dir, layout, replica) = open_test_replica();    let (_key, _path) = queue_one(&replica, &layout, None);    let deps = FakeDeps::default();    let stray = MediaRowRef {        key: "another-workspace/messages/x/y.jpg".to_string(),        workspace_id: WORKSPACE.to_string(),        sha256: "b".repeat(64),        content_type: "image/jpeg".to_string(),        size_bytes: 1,        local_path: Some("/dev/null".to_string()),        state: "pending".to_string(),        after: None,        after_row_id: None,        attempts: 0,        last_error: None,        next_attempt_at: None,        tier: None,        captured_here: false,        pinned: false,        last_viewed_at: None,        last_code: None,        network: "any".to_string(),        asked_by: None,        source: None,        created_at: "2026-09-08T10:00:00.000Z".to_string(),        updated_at: "2026-09-08T10:00:00.000Z".to_string(),    };    assert_eq!(        upload_one(&replica, &deps, &stray, &FixedClock::default_start()),        Uploaded::Failed    );    assert!(deps.keys().is_empty());}#[tokio::test]async fn a_pass_claims_what_is_due_and_takes_it_up_at_most_three_at_a_time() {    let (_dir, layout, replica) = open_test_replica();    for n in 0..5u8 {        let sha256 = format!("{n:064x}");        let path = media_file_path(&layout, WORKSPACE, &sha256, "jpg");        std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");        std::fs::write(&path, [n; 8]).expect("the file");        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg"),                workspace_id: WORKSPACE.to_string(),                sha256,                content_type: "image/jpeg".to_string(),                size_bytes: 8,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: "2026-09-08T10:00:00.000Z".to_string(),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");    }    let replica = Arc::new(Mutex::new(replica));    let deps: Arc<dyn MediaDrainDeps> = Arc::new(FakeDeps::default());    let pass = drain_pass(&replica, &deps, &clock(), &watch()).await;    assert_eq!(pass.uploaded, 5);    assert_eq!(pass.failed, 0);    let replica = replica.lock().expect("the replica");    let counts = counts_of(&replica).expect("counts");    assert_eq!(counts.synced, 5);    assert_eq!(counts.pending, 0);}/// Deps that count the uploads in the air at once.#[derive(Debug, Default)]struct CountingDeps {    in_the_air: std::sync::atomic::AtomicUsize,    most: std::sync::atomic::AtomicUsize,}impl MediaDrainDeps for CountingDeps {    fn upload(&self, _row: &MediaRowRef, _local_path: &std::path::Path) -> Result<Landed, ServerRefusal> {        use std::sync::atomic::Ordering;        cotton_store::held::must_not_wait("the bytes going up");        let now = self.in_the_air.fetch_add(1, Ordering::SeqCst) + 1;        self.most.fetch_max(now, Ordering::SeqCst);        std::thread::sleep(std::time::Duration::from_millis(40));        self.in_the_air.fetch_sub(1, Ordering::SeqCst);        Ok(Landed::Stored)    }}/// RULE: A pass carries THREE uploads at once and never more: one at a time spends the pass on latency, a dozen starves the sync loop's push and pull.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn a_pass_carries_three_uploads_at_once_and_never_more() {    let (_dir, layout, replica) = open_test_replica();    for n in 0..9u8 {        let sha256 = format!("{n:064x}");        let path = media_file_path(&layout, WORKSPACE, &sha256, "jpg");        std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");        std::fs::write(&path, [n; 8]).expect("the file");        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg"),                workspace_id: WORKSPACE.to_string(),                sha256,                content_type: "image/jpeg".to_string(),                size_bytes: 8,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: "2026-09-08T10:00:00.000Z".to_string(),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");    }    let replica = Arc::new(Mutex::new(replica));    let counting = Arc::new(CountingDeps::default());    let deps: Arc<dyn MediaDrainDeps> = Arc::clone(&counting) as Arc<dyn MediaDrainDeps>;    let pass = drain_pass(&replica, &deps, &clock(), &watch()).await;    assert_eq!(pass.uploaded, 9);    assert_eq!(counting.most.load(std::sync::atomic::Ordering::SeqCst), MEDIA_DRAIN_CONCURRENCY);    assert_eq!(MEDIA_DRAIN_CONCURRENCY, 3);}#[tokio::test]async fn an_empty_ledger_is_a_pass_that_moved_nothing_and_asked_nobody() {    let (_dir, _layout, replica) = open_test_replica();    let replica = Arc::new(Mutex::new(replica));    let deps: Arc<dyn MediaDrainDeps> = Arc::new(FakeDeps::default());    assert_eq!(        drain_pass(&replica, &deps, &clock(), &watch()).await,        DrainPass::default()    );}/// A row written under a build whose uploader never ran (#508 left the/// drain's deps unset, so every `_media` row a phone wrote under it sat/// `pending` with no attempt) is still due: `claim_due_media` asks only for/// `pending` and a retry instant that is null or past, never for an age. The/// first pass of a fixed build takes those rows up, oldest first, with no/// migration and no re-enqueue.#[tokio::test]async fn rows_left_pending_by_a_build_with_no_uploader_go_up_on_the_first_pass() {    let (_dir, layout, replica) = open_test_replica();    // Days before the clock's instant, in the order they were captured.    let written_at = [        "2026-09-07T08:00:00.000Z",        "2026-09-09T21:30:00.000Z",        "2026-09-11T06:15:00.000Z",    ];    for (n, at) in written_at.iter().enumerate() {        let sha256 = format!("{n:064x}");        let path = media_file_path(&layout, WORKSPACE, &sha256, "jpg");        std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");        std::fs::write(&path, [n as u8; 8]).expect("the file");        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg"),                workspace_id: WORKSPACE.to_string(),                sha256,                content_type: "image/jpeg".to_string(),                size_bytes: 8,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: (*at).to_string(),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");    }    // What the broken build left behind: pending, never attempted, no retry    // instant — stated here so a change to `enqueue_media`'s defaults fails    // this test rather than silently changing what it proves.    for row in replica        .driver        .all(            "SELECT attempts, next_attempt_at, state FROM _media ORDER BY created_at",            &[],        )        .expect("the rows")    {        assert_eq!(row.get("attempts"), Some(&SqlValue::Integer(0)));        assert_eq!(row.get("next_attempt_at"), Some(&SqlValue::Null));        assert_eq!(row.get("state"), Some(&SqlValue::Text("pending".to_string())));    }    let replica = Arc::new(Mutex::new(replica));    let deps = Arc::new(FakeDeps::default());    let shared: Arc<dyn MediaDrainDeps> = Arc::clone(&deps) as Arc<dyn MediaDrainDeps>;    let pass = drain_pass(&replica, &shared, &clock(), &watch()).await;    assert_eq!(pass.uploaded, 3);    assert_eq!(pass.failed, 0);    // All three, none twice. Claimed oldest first (`claim_due_media`'s own    // order); the puts run three abreast, so their log is not ordered.    let mut put = deps.keys();    put.sort();    assert_eq!(        put,        (0..3)            .map(|n| message_media_key(crate::test_support::file_id(), THREAD, &format!("{n:064x}"), "jpg"))            .collect::<Vec<_>>()    );    let replica = replica.lock().expect("the replica");    let counts = counts_of(&replica).expect("counts");    assert_eq!(counts.synced, 3);    assert_eq!(counts.pending, 0);}/// Deps whose upload STOPS in the middle: `put_bytes` says it has begun and/// then waits to be let go. The test is what runs while the bytes are "going/// up", which is the only moment the lock question can be asked.struct GatedDeps {    began: Mutex<std::sync::mpsc::Sender<String>>,    release: Mutex<std::sync::mpsc::Receiver<()>>,}impl std::fmt::Debug for GatedDeps {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("GatedDeps")    }}impl MediaDrainDeps for GatedDeps {    fn upload(&self, row: &MediaRowRef, _local_path: &std::path::Path) -> Result<Landed, ServerRefusal> {        cotton_store::held::must_not_wait("the bytes going up");        self.began            .lock()            .expect("the sender")            .send(row.key.clone())            .expect("the test is listening");        // One release per upload; a worker that never got one is the test        // failing on its own timeout, never a hang.        let _ = self            .release            .lock()            .expect("the gate")            .recv_timeout(std::time::Duration::from_secs(10));        Ok(Landed::Stored)    }}/// THE RULE THE COMMENT ALWAYS CLAIMED: the bytes go up OUTSIDE the replica/// lock. Every phone read (`with_file`) and the sync loop's fold take that/// same lock, so a worker holding it across a PUT — seconds per picture, three/// workers, thousands of rows — is a Home that never draws and a Sync screen/// stuck on "Checking…" (build 143). Two rows, so a reader is proved to get/// the lock BETWEEN uploads as well as during one.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn a_reader_gets_the_replica_while_the_bytes_are_going_up() {    let (_dir, layout, replica) = open_test_replica();    for n in 0..2u8 {        let sha256 = format!("{n:064x}");        let path = media_file_path(&layout, WORKSPACE, &sha256, "jpg");        std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");        std::fs::write(&path, [n; 8]).expect("the file");        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg"),                workspace_id: WORKSPACE.to_string(),                sha256,                content_type: "image/jpeg".to_string(),                size_bytes: 8,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: "2026-09-08T10:00:00.000Z".to_string(),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");    }    let replica = Arc::new(Mutex::new(replica));    let (began_tx, began_rx) = std::sync::mpsc::channel::<String>();    let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();    let deps: Arc<dyn MediaDrainDeps> = Arc::new(GatedDeps {        began: Mutex::new(began_tx),        release: Mutex::new(release_rx),    });    let pass = {        let replica = Arc::clone(&replica);        let deps = Arc::clone(&deps);        let clock = clock();        tokio::spawn(async move { drain_pass(&replica, &deps, &clock, &watch()).await })    };    // One upload at a time, each stopped mid-PUT while the reader asks for    // the file. `try_lock` rather than `lock`: a held lock must be a red    // test, never a hung one. Twice, so the lock is proved free BETWEEN two    // uploads as well as during one.    let mut in_the_air = Vec::new();    for _ in 0..2 {        in_the_air.push(            began_rx                .recv_timeout(std::time::Duration::from_secs(10))                .expect("an upload began"),        );        {            // Polled, not `try_lock` once: another worker may hold the lock            // for its own two statements at this instant, and that is the            // millisecond wait a reader is allowed. The PUT is parked on the            // gate for as long as this loop runs, so a lock held ACROSS it            // fails here by the deadline rather than hanging.            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);            let held = loop {                if let Ok(held) = replica.try_lock() {                    break Some(held);                }                if std::time::Instant::now() > deadline {                    break None;                }                std::thread::sleep(std::time::Duration::from_millis(1));            };            assert!(                held.is_some(),                "the replica is held while bytes are going up — a phone read would wait on this PUT"            );            // And the reader can READ: the row in the air is still pending,            // because the mark comes after the bytes. (Both rows may be in the            // air at once — three workers — so only the one in hand is            // asserted, not the other's timing.)            let counts = counts_of(&held.expect("the file")).expect("counts");            assert!(counts.pending >= 1, "{counts:?}");            assert_eq!(counts.pending + counts.synced, 2, "{counts:?}");        }        release_tx.send(()).expect("a worker is waiting");    }    in_the_air.sort();    let pass = pass.await.expect("the pass ran");    assert_eq!(pass.uploaded, 2);    assert_eq!(pass.failed, 0);    let replica = replica.lock().expect("the replica");    let counts = counts_of(&replica).expect("counts");    assert_eq!((counts.pending, counts.synced), (0, 2));    assert_eq!(        in_the_air,        (0..2)            .map(|n| message_media_key(crate::test_support::file_id(), THREAD, &format!("{n:064x}"), "jpg"))            .collect::<Vec<_>>()    );}// ─────────────────────────────────────────────────────────────────────────────// The phone is TOLD when bytes land — once per tick// ─────────────────────────────────────────────────────────────────────────────#[tokio::test]async fn a_tick_that_moved_no_bytes_tells_nobody() {    let (_dir, _layout, replica) = open_test_replica();    let heard: Arc<Mutex<Vec<(String, MediaMoved)>>> = Arc::new(Mutex::new(Vec::new()));    let log = Arc::clone(&heard);    let drain = MediaDrain::new(MediaDrainInput {        replica: Arc::new(Mutex::new(replica)),        deps: Arc::new(FakeDeps::default()),        clock: clock(),        interval_ms: None,        on_status: None,        keep_fetch: None,        evict: None,        others: None,        held_notes: None,        unlink: None,        watch: None,        after_uploads: None,        on_media: Some(Arc::new(move |database: &str, moved| {            log.lock().expect("the log").push((database.to_string(), moved))        })),    });    drain.drain_now().await;    assert!(heard.lock().expect("the log").is_empty());}/// A second database this device holds beside its own — a project's.const A_PROJECT: &str = "66666666-6666-4666-8666-666666666666";/// RULE: The upload drain takes up every database's pending media, not the attached database's alone — each held replica has its own queue.#[tokio::test]async fn upload_queue_drains_every_replica() {    let (dir, layout, replica) = open_test_replica();    let (mine, _path) = queue_one(&replica, &layout, None);    let project = crate::test_support::open_replica_for(&layout, dir.path(), A_PROJECT);    let theirs = queue_one_in_project(&project, &layout);    let project = Arc::new(Mutex::new(project));    let beside = Arc::clone(&project);    let deps = Arc::new(FakeDeps::default());    let drain = MediaDrain::new(MediaDrainInput {        replica: Arc::new(Mutex::new(replica)),        deps: Arc::clone(&deps) as Arc<dyn MediaDrainDeps>,        clock: clock(),        interval_ms: None,        on_status: None,        keep_fetch: None,        evict: None,        others: Some(Arc::new(move || vec![Arc::clone(&beside)])),        held_notes: None,        unlink: None,        watch: None,        after_uploads: None,        on_media: None,    });    drain.drain_now().await;    assert_eq!(        deps.keys(),        vec![mine, theirs.clone()],        "the attached database's first, then the project's"    );    let held = project.lock().expect("the project");    assert_eq!(        media_by_key(&held.driver, &theirs)            .expect("a read")            .expect("a row")            .state,        "synced",        "and the project's row is marked in the project's own file"    );}/// One pending upload in [`A_PROJECT`]'s replica, its bytes on disk; answers/// its key.fn queue_one_in_project(project: &crate::Replica, layout: &crate::Layout) -> String {    let sha256 = "b".repeat(64);    let path = media_file_path(layout, A_PROJECT, &sha256, "jpg");    std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");    std::fs::write(&path, b"synthetic bytes").expect("the file");    let key = format!("{A_PROJECT}/photos/{sha256}.jpg");    enqueue_media(        &project.driver,        &MediaEnqueueInput {            key: key.clone(),            workspace_id: A_PROJECT.to_string(),            sha256,            content_type: "image/jpeg".to_string(),            size_bytes: 15,            local_path: Some(path.to_string_lossy().to_string()),            state: None,            after: None,            after_row_id: None,            now: "2026-09-08T10:00:00.000Z".to_string(),            tier: None,            captured_here: false,        },    )    .expect("a ledger row");    key}/// RULE: The upload status a device reports counts the queued, sent and failed media of every database it holds, not only the one on screen.#[tokio::test]async fn upload_status_counts_every_database() {    let (dir, layout, replica) = open_test_replica();    queue_one(&replica, &layout, None);    let project = crate::test_support::open_replica_for(&layout, dir.path(), A_PROJECT);    queue_one_in_project(&project, &layout);    let beside = Arc::new(Mutex::new(project));    let seen: Arc<Mutex<Vec<MediaDrainStatus>>> = Arc::new(Mutex::new(Vec::new()));    let log = Arc::clone(&seen);    let drain = MediaDrain::new(MediaDrainInput {        replica: Arc::new(Mutex::new(replica)),        deps: Arc::new(FakeDeps::default()),        clock: clock(),        interval_ms: None,        on_status: Some(Arc::new(move |status: &MediaDrainStatus| {            log.lock().expect("the log").push(status.clone())        })),        keep_fetch: None,        evict: None,        others: Some(Arc::new(move || vec![Arc::clone(&beside)])),        held_notes: None,        unlink: None,        watch: None,        after_uploads: None,        on_media: None,    });    drain.drain_now().await;    // The line read while the tick works already counts BOTH queues…    let seen = seen.lock().expect("the log").clone();    let uploading = seen        .iter()        .find(|status| status.state == DrainState::Uploading)        .expect("an uploading status");    assert_eq!(uploading.pending, 2, "both databases' uploads are waiting");    // …and the one left after it counts both as sent.    let after = drain.status();    assert_eq!((after.pending, after.synced, after.failed), (0, 2, 0));}// ─────────────────────────────────────────────────────────────────────────────// MEDIA DRAIN 1, item 3: where each file is, while it goes// ─────────────────────────────────────────────────────────────────────────────/// Deps whose upload says it has sent half, then waits to be let go.struct HalfwayDeps {    began: Mutex<std::sync::mpsc::Sender<String>>,    release: Mutex<std::sync::mpsc::Receiver<()>>,}impl std::fmt::Debug for HalfwayDeps {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("HalfwayDeps")    }}impl MediaDrainDeps for HalfwayDeps {    fn upload(&self, _row: &MediaRowRef, _local_path: &std::path::Path) -> Result<Landed, ServerRefusal> {        unreachable!("the drain asks for the watched upload")    }    fn upload_watched(&self, row: &MediaRowRef, _local_path: &std::path::Path, progress: Progress) -> Result<Landed, ServerRefusal> {        progress(20, 40);        self.began.lock().expect("the sender").send(row.key.clone()).expect("the test is listening");        let _ = self.release.lock().expect("the gate").recv_timeout(std::time::Duration::from_secs(10));        progress(40, 40);        Ok(Landed::Stored)    }}/// RULE: A file going up answers uploading with the bytes sent of the bytes that go, and uploaded only once the object has answered; nothing about it stays in the air after.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn a_file_going_up_says_how_far_and_is_uploaded_only_on_the_objects_answer() {    let (_dir, layout, replica) = open_test_replica();    let (key, _path) = queue_one(&replica, &layout, None);    let replica = Arc::new(Mutex::new(replica));    let (began_tx, began_rx) = std::sync::mpsc::channel::<String>();    let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();    let deps: Arc<dyn MediaDrainDeps> = Arc::new(HalfwayDeps { began: Mutex::new(began_tx), release: Mutex::new(release_rx) });    let watch = watch();    let pass = {        let (replica, deps, clock, watch) = (Arc::clone(&replica), Arc::clone(&deps), clock(), Arc::clone(&watch));        tokio::spawn(async move { drain_pass(&replica, &deps, &clock, &watch).await })    };    began_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("the upload began");    let asked = vec![key.clone()];    let halfway = {        let replica = replica.lock().expect("the replica");        crate::media::uploads_of(&asked, &cotton_store::media_ledger::media_by_keys(&replica.driver, &asked).expect("reads"), &watch)    };    assert_eq!(halfway.files[0].phase, Phase::Uploading);    assert_eq!((halfway.files[0].sent, halfway.files[0].total), (Some(20), 40));    assert_eq!(halfway.counts.uploaded, 0, "half sent is not kept");    release_tx.send(()).expect("the upload is waiting");    assert_eq!(pass.await.expect("the pass ran").uploaded, 1);    let done = {        let replica = replica.lock().expect("the replica");        crate::media::uploads_of(&asked, &cotton_store::media_ledger::media_by_keys(&replica.driver, &asked).expect("reads"), &watch)    };    assert_eq!(done.files[0].phase, Phase::Uploaded);    assert_eq!(watch.in_the_air(), 0);}/// RULE: A file the object refuses for good leaves the queue as failed with the word the person acts on (too_big, cotton_full, refused, file_gone), never as uploaded; a full space waits with its word and stays queued.#[tokio::test]async fn a_refused_file_is_failed_with_its_word_and_a_full_space_waits() {    for (refusal, phase, code) in [        (ServerRefusal::new("a media file is at most 100 MB", 413).with_code("too_big".to_string()), Phase::Failed, "too_big"),        (ServerRefusal::new("this object's media is full", 413).with_code("object_full".to_string()), Phase::Failed, "cotton_full"),        (ServerRefusal::new("not a type this object keeps", 415), Phase::Failed, "refused"),        (ServerRefusal::new("your space is full", 413).with_code(SPACE_FULL.to_string()), Phase::Waiting, "space_full"),    ] {        let (_dir, layout, replica) = open_test_replica();        let (key, _path) = queue_one(&replica, &layout, None);        let replica = Arc::new(Mutex::new(replica));        let fake = FakeDeps::default();        *fake.refusal.lock().expect("the slot") = Some(refusal);        let deps: Arc<dyn MediaDrainDeps> = Arc::new(fake);        let watch = watch();        let pass = drain_pass(&replica, &deps, &clock(), &watch).await;        assert_eq!(pass.uploaded, 0);        let asked = vec![key];        let replica = replica.lock().expect("the replica");        let uploads = crate::media::uploads_of(&asked, &cotton_store::media_ledger::media_by_keys(&replica.driver, &asked).expect("reads"), &watch);        assert_eq!((uploads.files[0].phase, uploads.files[0].code.as_deref()), (phase, Some(code)));    }}/// RULE: A file whose bytes left this device is failed as file_gone before anything is sent.#[tokio::test]async fn a_file_no_longer_here_is_failed_as_gone() {    let (_dir, layout, replica) = open_test_replica();    let (key, path) = queue_one(&replica, &layout, None);    std::fs::remove_file(&path).expect("the file goes");    let replica = Arc::new(Mutex::new(replica));    let fake = Arc::new(FakeDeps::default());    let deps: Arc<dyn MediaDrainDeps> = Arc::clone(&fake) as Arc<dyn MediaDrainDeps>;    drain_pass(&replica, &deps, &clock(), &watch()).await;    assert!(fake.keys().is_empty(), "nothing sent");    let replica = replica.lock().expect("the replica");    let row = media_by_key(&replica.driver, &key).expect("a read").expect("a row");    assert_eq!((row.state.as_str(), row.last_code.as_deref()), ("failed", Some("file_gone")));}/// `count` files queued, oldest first; file `big` (if any) is 9 bytes, the rest 8. Answers their keys.fn queue_files(replica: &crate::Replica, layout: &crate::Layout, count: u8, big: Option<u8>, network: Option<&str>) -> Vec<String> {    let mut keys = Vec::new();    for n in 0..count {        let sha256 = format!("{:064x}", u32::from(n) + 0x1000);        let path = media_file_path(layout, WORKSPACE, &sha256, "jpg");        std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder");        let size = if big == Some(n) { 9 } else { 8 };        std::fs::write(&path, vec![n; size]).expect("the file");        let key = message_media_key(crate::test_support::file_id(), THREAD, &sha256, "jpg");        enqueue_media(            &replica.driver,            &MediaEnqueueInput {                key: key.clone(),                workspace_id: WORKSPACE.to_string(),                sha256,                content_type: "image/jpeg".to_string(),                size_bytes: size as i64,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                now: format!("2026-09-08T10:00:{:02}.{:03}Z", n / 100, n % 100),                tier: None,                captured_here: false,            },        )        .expect("a ledger row");        if let Some(network) = network {            cotton_store::media_ledger::rule_media(&replica.driver, &key, Some(network), Some("albums"), None, true, "2026-09-08T10:00:00.000Z").expect("the rule");        }        keys.push(key);    }    keys}/// Deps where the 9-byte file is slow, and that note the order uploads end in.#[derive(Debug, Default)]struct BigFileDeps {    ended: Mutex<Vec<i64>>,}impl MediaDrainDeps for BigFileDeps {    fn upload(&self, row: &MediaRowRef, _local_path: &std::path::Path) -> Result<Landed, ServerRefusal> {        let wait = if row.size_bytes == 9 { 600 } else { 5 };        std::thread::sleep(std::time::Duration::from_millis(wait));        self.ended.lock().unwrap().push(row.size_bytes);        Ok(Landed::Stored)    }}/// RULE (MEDIA DRAIN 1 item 1): a pass is never stalled behind one big file. The big one holds one slot while the/// small ones flow past it, beyond the pass's first claim, and they are all up before it ends.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn a_pass_is_never_stalled_behind_one_big_file() {    let (_dir, layout, replica) = open_test_replica();    let files = 41u8; // more than two claims' worth, the big one first    queue_files(&replica, &layout, files, Some(0), None);    let replica = Arc::new(Mutex::new(replica));    let big = Arc::new(BigFileDeps::default());    let deps: Arc<dyn MediaDrainDeps> = Arc::clone(&big) as Arc<dyn MediaDrainDeps>;    let pass = drain_pass(&replica, &deps, &clock(), &watch()).await;    assert_eq!(pass.uploaded, usize::from(files), "one pass carried every file, not one claim and a wait");    assert_eq!(big.ended.lock().unwrap().last(), Some(&9), "every small file was up before the big one ended");}/// RULE (MEDIA DRAIN 1 item 2): a file queued for Wi-Fi only waits until the shell has said Wi-Fi (and while it says/// mobile, Low Data Mode or none); one queued for any network goes on every network. One test, since the network is/// one value for the process.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn a_wifi_only_file_waits_off_wifi_and_any_network_goes() {    use crate::media::network::{self, Path};    let (_dir, layout, replica) = open_test_replica();    let wifi = queue_files(&replica, &layout, 3, None, Some("wifi"));    let replica = Arc::new(Mutex::new(replica));    let deps: Arc<dyn MediaDrainDeps> = Arc::new(FakeDeps::default());    let state = |key: &str| media_by_key(&replica.lock().unwrap().driver, key).unwrap().expect("the row").state;    for path in [Path::Unknown, Path::Mobile, Path::Constrained, Path::None] {        network::set(path);        assert_eq!(drain_pass(&replica, &deps, &clock(), &watch()).await.uploaded, 0, "nothing goes on {path:?}");        assert!(wifi.iter().all(|key| state(key) == "pending"), "{path:?}");    }    {        let replica = replica.lock().unwrap();        cotton_store::media_ledger::rule_media(&replica.driver, &wifi[0], Some("any"), None, None, false, "2026-09-08T10:01:00.000Z").expect("opened");    }    assert_eq!(drain_pass(&replica, &deps, &clock(), &watch()).await.uploaded, 1, "a file someone queued for any network goes on mobile");    assert!(network::set(Path::Wifi), "Wi-Fi now opens what waited");    assert!(!network::set(Path::Wifi), "and said twice opens nothing new");    assert_eq!(drain_pass(&replica, &deps, &clock(), &watch()).await.uploaded, 2, "on Wi-Fi the rest go");    network::set(Path::Unknown);}