Cotton code
196 lines · 6.8 KB · RustRaw
use super::*;use cotton_client::sync::{HeldFiles, SyncLoop, SyncLoopInput};use cotton_store::protocol::types::{    ExchangeRequest, ExchangeResponse, ExchangeSectionsRequest, ExchangeSectionsResponse,    SectionAnswer, SectionRefusal, SectionRefused,};const A: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";const B: &str = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";fn open_replica_for(    layout: &Layout,    scratch: &std::path::Path,    database: &str,) -> cotton_client::Replica {    let snapshot = scratch.join(format!("snapshot-{database}.db"));    let db = cotton_store::test_template::create_workspace_for_test(        &snapshot,        &cotton_store::meta::Meta {            workspace_id: database.into(),            owner_id: "synthetic-owner".into(),            device_id: "synthetic-snapshot".into(),            last_server_seq: 0,            last_hlc: None,        },    )    .unwrap();    db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Synthetic', 'synthetic-owner', '2026-09-08T09:00:00Z')", &[rusqlite::types::Value::Text(database.to_string())]).unwrap();    drop(db);    cotton_client::open_replica(        layout,        database,        &cotton_client::seams::FixedClock::default_start(),        &cotton_client::seams::SeededRandom::default(),        &mut |destination| {            std::fs::copy(&snapshot, destination)                .map(|_| ())                .map_err(|error| error.to_string())        },    )    .unwrap()}fn accepted(request: &ExchangeRequest) -> ExchangeResponse {    let mut seen = request.cursors.clone();    for op in &request.ops {        let top = seen.entry(op.device_id.clone()).or_default();        if op.hlc > *top {            *top = op.hlc.clone();        }    }    serde_json::from_value(json!({        "workspaceId": request.workspace_id, "ops": [], "cursors": request.cursors,        "hasMore": false, "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION,        "appliedRows": {}, "rejected": [], "seen": seen,    }))    .unwrap()}struct Server(Arc<Mutex<Vec<Vec<String>>>>);impl cotton_client::transport::RefusalAware for Server {    fn last_refusal(&self) -> Option<cotton_client::transport::ServerRefusal> {        None    }}impl cotton_store::exchange::SyncTransport for Server {    fn exchange(&mut self, _: &ExchangeRequest) -> Result<ExchangeResponse, String> {        panic!("the household uses sections");    }    fn exchange_many(        &mut self,        request: &ExchangeSectionsRequest,    ) -> Result<ExchangeSectionsResponse, String> {        self.0.lock().unwrap().push(            request                .sections                .iter()                .map(|section| section.workspace_id.clone())                .collect(),        );        Ok(ExchangeSectionsResponse {            sections: request                .sections                .iter()                .map(|section| {                    if section.workspace_id == A {                        SectionAnswer::Refused(SectionRefused {                            workspace_id: A.into(),                            refused: SectionRefusal {                                code: "device_reader_only".into(),                                message: "This device reads only.".into(),                                extra: Default::default(),                            },                        })                    } else {                        SectionAnswer::Answered(accepted(section))                    }                })                .collect(),        })    }}/// RULE: A typed refusal preserves Mac contact and the pass continues to the next database and the next pass; walker296's 17 Oct 2026 rows for 299 mistook an answered refusal for silence.#[tokio::test]async fn a_typed_refusal_keeps_the_mac_reachable_and_other_databases_syncing() {    let dir = tempfile::tempdir().unwrap();    let layout = Layout::new(dir.path());    let a = Arc::new(Mutex::new(open_replica_for(&layout, dir.path(), A)));    let b = Arc::new(Mutex::new(open_replica_for(&layout, dir.path(), B)));    let lines = HomeLines::kept_at(dir.path().join("lines.json"));    lines.heard(        A,        Some(cotton_client::sync::Reported {            pushed: 0,            pulled: 0,            behind: true,            remaining: Some(7),            owed_at_start: Some(9),            unsent: 0,            handed: 0,            passed: 2,        }),        None,        None,        false,        90_000,    );    let heard = lines.clone();    let reports = Arc::new(Mutex::new(Vec::new()));    let told = reports.clone();    let calls = Arc::new(Mutex::new(Vec::new()));    let requests = calls.clone();    let running = SyncLoop::new(SyncLoopInput {        replica: a,        workspace_id: A.into(),        transport: Arc::new(move || Ok(Box::new(Server(requests.clone())))),        clock: Arc::new(cotton_client::seams::FixedClock::default_start()),        random: Arc::new(cotton_client::seams::SeededRandom::default()),        interval_ms: None,        on_status: None,        on_tables: None,        on_sent: None,        held: Some(HeldFiles {            ids: Arc::new(|| vec![B.into()]),            open: Arc::new(move |_| Ok(b.clone())),            open_now: Arc::new(|_| true),            notes: HeldNotes::beside(&layout.connection_json()),            after_pass: None,            on_tables: None,            on_sent: None,            on_report: Some(Arc::new(move |report| {                heard.heard(                    report.database,                    report.reported,                    report.schema,                    report.moved,                    report.answered,                    100_000,                );                told.lock().unwrap().push((                    report.database.to_string(),                    report.answered,                    report.reported.is_some(),                ));            })),        }),        time_box: Default::default(),        on_copy: None,    });    for _ in 0..2 {        let failure = running.pull_now().await.unwrap_err();        assert!(!failure.is_terminal());        assert!(failure.answered());        let held = lines.lines.lock().unwrap();        assert_eq!(held[A].facts().mac_silent_since, None);        assert_eq!(held[A].facts().mac_answered_at, Some(100_000));        assert_eq!(            held[A].facts().remaining,            Some(7),            "a refusal does not claim the backlog was folded"        );    }    assert_eq!(        *calls.lock().unwrap(),        vec![vec![A.to_string(), B.to_string()]; 2]    );    let reports = reports.lock().unwrap();    assert_eq!(        reports            .iter()            .filter(|(database, answered, moved)| database == B && *answered && *moved)            .count(),        2    );}