Cotton code
407 lines · 14.3 KB · RustRaw
//! Bytes for a batch: what is stored, what is skipped, and the rule that a//! message never waits on either.use cotton_core::import::envelope::{Direction, EnvelopeMessage, ImportBatch};use cotton_store::media_ledger::media_by_key;use super::*;use crate::seams::FixedClock;use crate::test_support::{open_test_replica, WORKSPACE};const THREAD: &str = "77777777-7777-4777-8777-777777777777";fn leg<'a>(layout: &'a Layout, clock: &'a FixedClock) -> MediaLeg<'a> {    MediaLeg {        layout,        file: crate::test_support::file_id(),        thread_id: THREAD,        clock,    }}fn a_file(dir: &std::path::Path, name: &str, size: usize) -> std::path::PathBuf {    let path = dir.join(name);    std::fs::create_dir_all(path.parent().expect("a folder")).expect("the folder");    std::fs::write(&path, vec![5u8; size]).expect("the bytes");    path}fn file_ref(path: &std::path::Path, name: &str) -> MediaFile {    MediaFile {        external_id: "S1".to_string(),        path: path.to_path_buf(),        name: Some(name.to_string()),        content_type: None,    }}fn one_message_batch() -> ImportBatch {    ImportBatch {        workspace_id: WORKSPACE.to_string(),        channel: "imessage".to_string(),        thread: None,        dm: None,        messages: vec![EnvelopeMessage {            phone: None,            email: None,            sender_label: None,            display_name: None,            direction: Direction::In,            body: "at the lake".to_string(),            media: None,            sent_at: "2026-09-01T10:00:00.000Z".to_string(),            external_id: "S1".to_string(),            reply_to_external_id: None,            reactions: None,            meta: None,        }],        new_thread_id: Some(THREAD.to_string()),    }}#[test]fn it_stores_a_file_keys_it_to_the_thread_and_ledgers_it_pending() {    let (dir, layout, replica) = open_test_replica();    let path = a_file(dir.path(), "incoming/photo.jpg", 48);    let clock = FixedClock::default_start();    let outcome = store_one_file(        &leg(&layout, &clock),        &replica.driver,        &file_ref(&path, "photo.jpg"),    );    let MediaOutcome::Stored {        key,        content_type,        size_bytes,        name,    } = outcome    else {        panic!("expected the file to be stored, got {outcome:?}");    };    assert_eq!(content_type, "image/jpeg");    assert_eq!(size_bytes, 48);    assert_eq!(name, "photo.jpg");    // The key carries the thread, which is why the caller had to resolve it    // before a byte moved.    assert!(        key.starts_with(&format!("{WORKSPACE}/messages/{THREAD}/")),        "{key}"    );    let row = media_by_key(&replica.driver, &key)        .expect("a read")        .expect("a ledger row");    assert_eq!(row.state, "pending");    // No trigger: the relay ignores an imported row, so there is nothing on the    // server to wake.    assert_eq!(row.after, None);}#[test]fn a_file_this_mac_does_not_hold_is_a_counted_skip_and_never_an_error() {    let (dir, layout, replica) = open_test_replica();    let clock = FixedClock::default_start();    let missing = dir.path().join("gone.jpg");    assert_eq!(        store_one_file(            &leg(&layout, &clock),            &replica.driver,            &file_ref(&missing, "gone.jpg")        ),        MediaOutcome::Missing    );}#[test]fn a_type_the_server_would_never_sign_for_is_refused_before_a_byte_is_copied() {    let (dir, layout, replica) = open_test_replica();    let path = a_file(dir.path(), "thing.xyz", 12);    let clock = FixedClock::default_start();    assert_eq!(        store_one_file(            &leg(&layout, &clock),            &replica.driver,            &file_ref(&path, "thing.xyz")        ),        MediaOutcome::UnsupportedType    );    // Judged HERE, so nothing was copied into this Mac's store.    assert!(!layout.client_media_dir().join(WORKSPACE).exists());}#[test]fn a_file_past_the_servers_own_ceiling_is_refused_rather_than_copied_and_then_rejected() {    let (dir, layout, replica) = open_test_replica();    let limits = media_limits(MediaKind::Message);    let path = a_file(dir.path(), "huge.jpg", (limits.max_bytes + 1) as usize);    let clock = FixedClock::default_start();    assert_eq!(        store_one_file(            &leg(&layout, &clock),            &replica.driver,            &file_ref(&path, "huge.jpg")        ),        MediaOutcome::Oversize    );}#[test]fn a_type_the_source_recorded_beats_the_one_the_extension_suggests() {    let (dir, layout, replica) = open_test_replica();    // iMessage is the rare source that actually RECORDS the type.    let path = a_file(dir.path(), "clip.bin", 20);    let clock = FixedClock::default_start();    let file = MediaFile {        external_id: "S1".to_string(),        path,        name: Some("clip.mov".to_string()),        content_type: Some("video/quicktime".to_string()),    };    let outcome = store_one_file(&leg(&layout, &clock), &replica.driver, &file);    let MediaOutcome::Stored { content_type, .. } = outcome else {        panic!("expected the file to be stored, got {outcome:?}");    };    assert_eq!(content_type, "video/quicktime");}#[test]fn every_outcome_has_its_own_counted_reason_so_a_panel_can_say_which() {    let reasons: Vec<&str> = [        MediaOutcome::Stored {            key: "k".to_string(),            content_type: "image/jpeg".to_string(),            size_bytes: 1,            name: "a.jpg".to_string(),        },        MediaOutcome::Missing,        MediaOutcome::Oversize,        MediaOutcome::UnsupportedType,        MediaOutcome::Failed {            detail: "the disk".to_string(),        },    ]    .iter()    .map(MediaOutcome::note_key)    .collect();    assert_eq!(        reasons,        vec![            "media:stored",            "media:missing",            "media:oversize",            "media:unsupportedType",            "media:failed"        ]    );    // Every one of them begins `media:`, which is what keeps a lost picture out    // of the DROPPED-rows count.    assert!(reasons.iter().all(|key| key.starts_with("media:")));}#[test]fn it_hangs_a_stored_file_on_the_message_that_referenced_it() {    let (dir, layout, replica) = open_test_replica();    let path = a_file(dir.path(), "photo.jpg", 48);    let clock = FixedClock::default_start();    let (next, notes) = attach_media(        &leg(&layout, &clock),        &replica.driver,        &one_message_batch(),        &[file_ref(&path, "photo.jpg")],    );    assert_eq!(notes.get("media:stored"), Some(&1));    let media = next.messages[0].media.as_ref().expect("an attachment");    assert_eq!(media.len(), 1);    assert_eq!(media[0].content_type, "image/jpeg");    assert_eq!(media[0].name.as_deref(), Some("photo.jpg"));    assert_eq!(media[0].size_bytes, Some(48.0));    assert!(media[0].key.starts_with(&format!("{WORKSPACE}/messages/{THREAD}/")));}#[test]fn it_answers_a_new_batch_and_never_edits_the_one_the_source_built() {    let (dir, layout, replica) = open_test_replica();    let path = a_file(dir.path(), "photo.jpg", 48);    let clock = FixedClock::default_start();    let original = one_message_batch();    let (next, _) = attach_media(        &leg(&layout, &clock),        &replica.driver,        &original,        &[file_ref(&path, "photo.jpg")],    );    // A reader that mutates its caller's data is how a retry ends up writing    // something different from what it read.    assert!(original.messages[0].media.is_none());    assert!(next.messages[0].media.is_some());}#[test]fn a_message_whose_file_could_not_be_stored_still_lands_with_its_words() {    let (dir, layout, replica) = open_test_replica();    let clock = FixedClock::default_start();    let missing = dir.path().join("nope.jpg");    let (next, notes) = attach_media(        &leg(&layout, &clock),        &replica.driver,        &one_message_batch(),        &[file_ref(&missing, "nope.jpg")],    );    assert_eq!(notes.get("media:missing"), Some(&1));    assert_eq!(next.messages[0].body, "at the lake");    assert!(next.messages[0].media.is_none());    // The host collector counts dropped rows; client builds do not link it.    // A lost picture is about a FILE, never a row.    #[cfg(feature = "ingest")]    assert_eq!(crate::ingest::dropped_from(&notes), 0);}#[test]fn a_batch_with_no_files_is_handed_straight_back() {    let (_dir, layout, replica) = open_test_replica();    let clock = FixedClock::default_start();    let batch = one_message_batch();    let (next, notes) = attach_media(&leg(&layout, &clock), &replica.driver, &batch, &[]);    assert_eq!(next, batch);    assert!(notes.is_empty());}#[test]fn two_files_on_one_message_both_ride_it() {    let (dir, layout, replica) = open_test_replica();    let one = a_file(dir.path(), "one.jpg", 12);    let two = a_file(dir.path(), "two.png", 20);    let clock = FixedClock::default_start();    let (next, notes) = attach_media(        &leg(&layout, &clock),        &replica.driver,        &one_message_batch(),        &[file_ref(&one, "one.jpg"), file_ref(&two, "two.png")],    );    assert_eq!(notes.get("media:stored"), Some(&2));    let media = next.messages[0].media.as_ref().expect("attachments");    assert_eq!(media.len(), 2);}/// A synthetic Ogg/Opus voice note: one page each for the header and tags,/// then `count` 20 ms silence packets on one page.fn ogg_voice_note(count: usize) -> Vec<u8> {    fn page(out: &mut Vec<u8>, sequence: u32, granule: i64, packets: &[Vec<u8>]) {        out.extend_from_slice(b"OggS\0\0");        out.extend_from_slice(&granule.to_le_bytes());        out.extend_from_slice(&9u32.to_le_bytes());        out.extend_from_slice(&sequence.to_le_bytes());        out.extend_from_slice(&[0; 4]);        out.push(packets.len() as u8);        out.extend(packets.iter().map(|packet| packet.len() as u8));        packets.iter().for_each(|packet| out.extend_from_slice(packet));    }    let mut head = b"OpusHead\x01\x01".to_vec();    head.extend_from_slice(&0u16.to_le_bytes());    head.extend_from_slice(&48_000u32.to_le_bytes());    head.extend_from_slice(&[0, 0, 0]);    let mut ogg = Vec::new();    page(&mut ogg, 0, 0, &[head]);    page(&mut ogg, 1, 0, &[b"OpusTags".to_vec()]);    page(&mut ogg, 2, 960 * count as i64, &vec![vec![0xF8, 0xFF, 0xFE]; count]);    ogg}#[derive(Default)]struct HeldObjects(std::sync::Mutex<Vec<(String, String, Vec<u8>)>>);impl PutObject for HeldObjects {    fn put(&self, key: &str, source: &std::path::Path, content_type: &str) -> Result<(), String> {        let bytes = std::fs::read(source).map_err(|error| error.to_string())?;        self.0.lock().unwrap().push((key.to_string(), content_type.to_string(), bytes));        Ok(())    }}/// RULE: voice intake stores AAC playback beside the untouched Ogg original, so every phone can play it without losing the source.#[test]fn a_voice_note_keeps_its_ogg_and_gains_a_rendition_the_phone_plays() {    let dir = tempfile::tempdir().expect("a folder");    let path = dir.path().join("3EB0AA.ogg");    let ogg = ogg_voice_note(100);    std::fs::write(&path, &ogg).expect("the bytes");    // A rendition must never overwrite or delete a file beside the import.    let neighbor = dir.path().join("3EB0AA.playback.m4a");    std::fs::write(&neighbor, b"another original attachment").unwrap();    let store = HeldObjects::default();    let mut file = file_ref(&path, "3EB0AA.ogg");    file.content_type = Some("audio/ogg".to_string());    // The Linux fixture exercises the serving job's contract; ffmpeg runs only on a Mac.    let mut ran = false;    let (next, notes) = attach_with_transcoder(        &one_message_batch(),        &[file],        |file| put_one_file(crate::test_support::file_id(), THREAD, &store, file),        &mut |job| {            assert_eq!(job.input, path);            assert_ne!(job.output, path);            let args = job.arguments();            assert!(args.windows(2).any(|pair| pair == ["-c:a", "aac"]));            assert_eq!(args.last().unwrap(), job.output.as_os_str());            std::fs::write(&job.output, b"synthetic AAC m4a output").unwrap();            ran = true;            Ok(())        },    );    assert!(ran);    assert_eq!(notes.get("voice:rendered"), Some(&1));    let media = &next.messages[0].media.as_ref().expect("an attachment")[0];    assert_eq!(media.content_type, "audio/ogg", "the original stays the attachment");    assert_eq!(media.duration_ms, Some(2000.0));    assert_eq!(media.playback_content_type.as_deref(), Some("audio/mp4"));    let playback = media.playback_key.as_deref().expect("a rendition key");    assert!(playback.starts_with(&format!("{WORKSPACE}/messages/{THREAD}/")) && playback.ends_with(".m4a"));    let held = store.0.lock().unwrap();    assert_eq!(held.len(), 2, "the original and its rendition");    assert_eq!((held[0].0.as_str(), held[0].2.as_slice()), (media.key.as_str(), ogg.as_slice()));    assert_eq!((held[1].0.as_str(), held[1].1.as_str()), (playback, "audio/mp4"));    assert_eq!(&held[1].2, b"synthetic AAC m4a output");    assert_eq!(std::fs::read(&neighbor).unwrap(), b"another original attachment");    assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2, "no rendition left behind on disk");}/// RULE: a failed voice job must keep the original object, because playback failure never erases a message.#[test]fn a_recording_that_cannot_be_transcoded_still_lands_as_its_original() {    let dir = tempfile::tempdir().expect("a folder");    let path = dir.path().join("3EB0AB.ogg");    std::fs::write(&path, ogg_voice_note(10)).unwrap();    let store = HeldObjects::default();    let mut file = file_ref(&path, "3EB0AB.ogg");    file.content_type = Some("audio/ogg".to_string());    let (next, notes) = attach_with_transcoder(        &one_message_batch(),        &[file],        |file| put_one_file(crate::test_support::file_id(), THREAD, &store, file),        &mut |_| Err("fixture_encoder_failure".into()),    );    assert_eq!(notes.get("voice:notRendered"), Some(&1));    let media = &next.messages[0].media.as_ref().expect("an attachment")[0];    // Its length is still read from the Ogg (a phone has no transcoder): the voice player and the list say it.    assert_eq!((media.playback_key.as_deref(), media.duration_ms), (None, Some(200.0)));    assert_eq!(store.0.lock().unwrap().len(), 1);}