Cotton code
157 lines · 7.5 KB · RustRaw
//! The transport seam: refusals and the exchange's deadlines.use super::*;#[test]fn a_terminal_device_refusal_is_recognised_by_its_code_and_nothing_else_is() {    assert!(ServerRefusal::new("no", 403)        .with_code("device_revoked")        .is_terminal_device_refusal());    assert!(!ServerRefusal::new("later", 429)        .with_code("rate_limited")        .retry_after(30)        .is_terminal_device_refusal());    assert!(!ServerRefusal::offline("offline").is_terminal_device_refusal());}// ── The socket exchange: one deadline for the whole call ──────────────────/// One `GET /` over the real socket exchange, with `ceiling` as its deadline.fn exchange_at(port: u16, ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> {    let origin = Origin::parse(&format!("http://127.0.0.1:{port}")).expect("an origin");    let authority = origin.authority();    SocketExchange.send(        &origin,        &http1::Http1Request {            method: "GET",            path: "/",            authority: &authority,            headers: Vec::new(),            body: None,        },        ceiling,    )}#[test]fn a_head_that_trickles_is_given_up_on_at_the_exchanges_deadline() {    // A byte every 200 ms of a head: every read returns something, so a    // per-read timeout never trips. One second is the whole exchange.    let port = scripted::trickling(b"", b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");    let refused = scripted::finishes(std::time::Duration::from_secs(4), move || {        exchange_at(port, std::time::Duration::from_secs(1)).map(|_| ())    })    .expect_err("a head that took nine seconds was waited for");    assert!(refused.contains(wire::DEADLINE_PASSED), "{refused}");}#[test]fn a_body_that_trickles_is_given_up_on_at_the_same_deadline_as_the_head() {    use std::io::Read as _;    // The head at once; the body never ends. The deadline armed at the dial    // is still the one the body reads under — not a fresh one after the head.    let port = scripted::trickling(b"HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\n", b"");    let refused = scripted::finishes(std::time::Duration::from_secs(4), move || {        let mut answer = exchange_at(port, std::time::Duration::from_secs(1))?;        let mut body = Vec::new();        answer            .read_to_end(&mut body)            .map(|_| ())            .map_err(|error| error.to_string())    })    .expect_err("a body that never ends was read to its end");    assert!(refused.contains(wire::DEADLINE_PASSED), "{refused}");}#[test]fn a_request_body_buys_time_at_the_slowest_upload_this_client_waits_for() {    assert_eq!(body_allowance(0), std::time::Duration::ZERO);    assert_eq!(body_allowance(1), std::time::Duration::from_secs(1));    // Sixteen mebibytes — a photo — at 32 KiB/s is eight and a half minutes.    assert_eq!(        body_allowance(16 * 1024 * 1024),        std::time::Duration::from_secs(512)    );}/// The refusal a serving Mac answers with until its release pass commits.struct Releasing;impl RefusalAware for Releasing {    fn last_refusal(&self) -> Option<ServerRefusal> {        Some(            ServerRefusal::new("the serving Mac has not heard the relay's time yet", 503)                .with_code("releasing"),        )    }}/// RULE: A 503 releasing — a serving Mac dating its held writes — is a retry-later: the sync pass backs off.#[test]fn a_serving_mac_still_releasing_is_retried_later_never_a_stop() {    let failure = crate::sync::cycle::classify(        cotton_store::exchange::SyncError::Transport("503".to_string()),        &Releasing,    );    assert!(failure.answered(), "a typed 503 proves contact: {failure:?}");    assert!(!failure.is_terminal());}/// RULE: ONE transport on the phone for every byte — a socket is opened, and a signed client is built, only inside the transport module (`cotton-client/src/transport/`, where every household request goes through the one `SignedHttp` and its records-first gate, and a joined Mac's line is that transport re-addressed), in the media byte path that dials beside that one fetch and under its gate, and in the exceptions below, each of which names why it is not a household fetch. A second transport is how a fetch outside the gate filled the downlink an exchange read was waiting on (architect, 13 Oct 2026 14:20 IST); add an exception only with its reason.#[test]fn no_second_transport_opens_a_socket() {    const OPENS: [&str; 7] =        ["dial_by(", "wire::dial(", "= dial(&", "SignedHttp::new(", "TcpStream::connect", "reqwest::", "ureq::"];    let allowed: std::collections::BTreeMap<&str, &str> = [        ("cotton-client/src/transport/", "the one transport"),        ("cotton-client/src/media/transport.rs", "media bytes, dialled beside the one fetch and gated by it"),        ("cotton-client/src/live/socket.rs", "the live channel's long-lived socket: a few bytes of news, never a fetch"),        ("cotton-ffi/src/phone/net.rs", "builds the one household transport"),        ("cotton-ffi/src/phone/city.rs", "a third party's place-name lookup, not the household"),        ("cotton-ffi/src/phone/serve_from.rs", "an order handed to the relay's directory, not to a Mac"),        ("cotton-client/src/ci/", "a Mac's CI runner (a Mac only)"),        ("cotton-client/src/session_host/", "a session's terminal stream: bytes for a view, never a fetch"),        ("cotton-client/src/media/loopback.rs", "the phone's own player door on 127.0.0.1: it knocks on itself to see the door still answers, never a fetch"),        ("cotton-ffi/src/phone/mail_imap.rs", "This phone fetches (Post CONTRACT row 12): the person's own mail server over IMAP, on the core's own socket, read-only, never the household"),        ("cotton-client/src/media/lan.rs", "the Wi-Fi door the owner asked for (AirPlay to his projector, 17 Nov 2026): one film offered to the TV on the Wi-Fi address while it plays there; it knocks on its own listener to wake it as it shuts, never a fetch"),    ]    .into_iter()    .collect();    let crates = cotton_store::manifest_dir().parent().expect("the crates folder").to_path_buf();    let mut strays = Vec::new();    for root in ["cotton-client/src", "cotton-ffi/src"] {        let mut stack = vec![crates.join(root)];        while let Some(dir) = stack.pop() {            for entry in std::fs::read_dir(&dir).expect("a folder") {                let path = entry.expect("an entry").path();                let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("");                if path.is_dir() {                    stack.push(path);                    continue;                }                if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {                    continue;                }                let at = path.strip_prefix(&crates).unwrap_or(&path).to_string_lossy().replace('\\', "/");                if allowed.keys().any(|allowed| at.starts_with(allowed)) {                    continue;                }                let text = std::fs::read_to_string(&path).expect("a source file");                for line in text.lines() {                    let code = line.trim_start();                    if code.starts_with("//") {                        continue;                    }                    if OPENS.iter().any(|opens| code.contains(opens)) {                        strays.push(format!("{at}: {code}"));                    }                }            }        }    }    assert!(strays.is_empty(), "a socket opened outside the one transport: {strays:#?}");}