Cotton code
155 lines · 7.1 KB · RustRaw
//! Reads that land while the phone swaps the database it stands on — Sign//! out, Sign in again, Delete account — on other threads, as Android asks the//! core on four: none is answered that this phone has no database//! (`shell::swap`; launch walk of Words, 22 Nov 2026, where Sign out drew//! "This phone has not started or joined a database yet" for a moment).use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::transport::Exchange;use serde_json::json;use crate::handle::CottonHandle;use crate::phone::personal_object::call_with;const DATABASE: &str = "22222222-2222-4222-8222-222222222222";/// An invented personal object: its definitions, an empty page, its owner.#[derive(Debug, Default)]struct Object;impl Exchange for Object {    fn send(        &self,        origin: &cotton_client::transport::Origin,        request: &cotton_client::transport::http1::Http1Request<'_>,        ceiling: std::time::Duration,    ) -> Result<Box<dyn cotton_client::transport::Answer>, String> {        let reply = if request.path.starts_with("/v1/definitions") {            Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "flavour": {}, "boards": [], "etag": "e1"}).to_string())        } else if request.path.starts_with("/v1/sync") {            Reply::ok(&json!({"version": 3, "rows": [], "server_time": "2026-11-22T09:00:00.000Z", "device": null}).to_string())        } else if request.path.starts_with("/v1/me") {            Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+15550190417", "role": "owner"}, "version": 3}).to_string())        } else {            Reply::ok("{}")        };        ScriptedExchange::new([reply]).send(origin, request, ceiling)    }    fn send_stream(        &self,        origin: &cotton_client::transport::Origin,        request: &cotton_client::transport::http1::Http1Request<'_>,        body: &mut dyn std::io::Read,        length: u64,        ceiling: std::time::Duration,    ) -> Result<Box<dyn cotton_client::transport::Answer>, String> {        let mut bytes = Vec::new();        std::io::Read::read_to_end(&mut std::io::Read::take(body, length), &mut bytes).map_err(|error| error.to_string())?;        let whole = cotton_client::transport::http1::Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request };        self.send(origin, &whole, ceiling)    }}fn phone() -> (tempfile::TempDir, Arc<CottonHandle>) {    let dir = tempfile::tempdir().expect("a temp container");    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/notes/flavour.json")).expect("Words' manifest")),    })    .expect("an open core");    (dir, Arc::new(handle))}/// Nothing stays open but the database the connection names: never the/// copy set aside or deleted, opened again by a read during the swap.fn standing(handle: &CottonHandle) {    let named = cotton_client::connection::ConnectionFile::at(handle.client().layout().connection_json()).read().and_then(|held| held.workspace_id);    if let Some(open) = handle.client().attached_database() {        assert_eq!(Some(open), named, "only what the connection names is open");    }}fn connect(handle: &CottonHandle) {    let ask = json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "deviceName": "An invented phone"});    call_with(handle, "personal.connect", &ask, Arc::new(Object) as Arc<dyn Exchange>).expect("connected");}/// Four threads read, as Words' list and home do, while `swap` runs again/// and again on this one; every answer said that there is no database.fn read_across(handle: &Arc<CottonHandle>, rounds: usize, swap: impl Fn(&CottonHandle)) -> Vec<String> {    let nothing = crate::shell::client::not_connected_sentence();    let stop = Arc::new(AtomicBool::new(false));    let said = Arc::new(Mutex::new(Vec::new()));    let readers: Vec<_> = (0..4)        .map(|_| {            let (handle, stop, said, nothing) = (Arc::clone(handle), Arc::clone(&stop), Arc::clone(&said), nothing.clone());            std::thread::spawn(move || {                while !stop.load(Ordering::SeqCst) {                    for method in ["notes.list", "read.you"] {                        if let Err(refused) = crate::methods::dispatch_across_swaps(&handle, method, &json!({})) {                            if refused.code == "not_connected" || refused.message.contains(&nothing) {                                said.lock().unwrap().push(format!("{method}: {} {}", refused.code, refused.message));                            }                        }                    }                }            })        })        .collect();    for _ in 0..rounds {        swap(handle);    }    stop.store(true, Ordering::SeqCst);    for reader in readers {        reader.join().expect("a reader ends");    }    let said = said.lock().unwrap().clone();    said}#[test]fn no_read_across_sign_out_and_sign_in_answers_that_there_is_no_database() {    let (_dir, handle) = phone();    connect(&handle);    let said = read_across(&handle, 3, |handle| {        call_with(handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("signed out");        standing(handle);        connect(handle);        standing(handle);    });    assert!(said.is_empty(), "{} reads answered that there is no database, first: {:?}", said.len(), said.first());}#[test]fn no_read_across_forgetting_a_deleted_account_answers_that_there_is_no_database() {    let (_dir, handle) = phone();    connect(&handle);    let said = read_across(&handle, 3, |handle| {        crate::phone::account_delete::call(handle, "account.forget", &json!({})).expect("forgot");        standing(handle);        connect(handle);        standing(handle);    });    assert!(said.is_empty(), "{} reads answered that there is no database, first: {:?}", said.len(), said.first());}#[test]fn the_swapping_thread_itself_is_never_held_and_gives_the_turn_back() {    // Sign out stands on a fresh database it opens on its own thread, inside    // its own turn (`start_local` attaches it): nothing waits on itself, and    // the turn is given back when it ends.    let (_dir, handle) = phone();    connect(&handle);    call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("signed out");    assert!(!handle.client().swapping_now(), "the turn is given back");    assert!(handle.client().attached_database().is_some(), "the fresh database stands open");}