Cotton code
587 lines · 24.1 KB · RustRaw
//! How this device reaches a server, behind one seam.//!//! `remote` is HTTP — the wire FORMAT of the ONE sync call, and nothing else://! the credential and the base address live in `connection.rs`, because two//! implementations of "what a push is" is the bug//! this whole seam exists to prevent//! ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]).//!//! **These seams are BLOCKING, and that is deliberate.** Everything a sync//! cycle does around them is blocking already: the store's driver is SQLite,//! the fold is SQLite, the outbox is SQLite. So the cycle is one blocking piece//! of work the loop hands to `spawn_blocking` (see `sync::task`), and a//! transport that were async would only mean the cycle awaiting inside a//! blocking thread. An async HTTP client implements [`ServerFetch`] by blocking//! on its own future there, which is exactly what that thread is for.pub mod address;pub mod http1;pub mod object;pub mod records_first;pub mod refusal;pub mod signed_http;pub mod device_removals;pub mod signer;pub mod wire;/// The scripted server every suite in this crate drives. Never compiled into a/// shipped build.#[cfg(any(test, feature = "test-fixtures"))]pub mod scripted;pub use address::{    attach_socket_url, is_pairing_route, live_socket_url, normalize_server_url,};pub use refusal::{DeviceRefusal, NoteKey, RefusalKind, RefusalMemory, Refuser};pub use signed_http::{ServerAddress, SignedHttp};pub use signer::RequestSigner;pub use wire::Origin;/// A refusal from a server, with the status and code the caller branches on.////// The four TERMINAL device codes are `connection::TERMINAL_DEVICE_CODES`;/// everything else is transient by definition and goes back on the ladder.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]#[error("{message}")]pub struct ServerRefusal {    pub message: String,    /// The HTTP status, or `0` for a failure that never reached one — no    /// network, a socket that hung past the ceiling.    pub status: u16,    /// The refusal envelope's `code`, when the server sent one.    pub code: Option<String>,    /// The saved row named by a `409 connection_exists`. Only that refusal    /// carries this handle, so Connect can resume its Sign in again.    pub existing_connection_id: Option<String>,    /// What `Retry-After` said, in seconds.    ///    /// Carried rather than swallowed because the sync loop must WAIT that long:    /// the server's own answer to "how busy am I" beats this client's backoff    /// ladder, and an import of 32k messages is exactly the workload that meets    /// the hourly bucket.    pub retry_after_seconds: Option<u32>,    /// WHICH MACHINE refused: the answer's `x-cotton-server` tag    /// (`cotton_core::device::server_id`), when it carried one. A Mac keeps    /// the household's refusal of it against this, so the refusal of a Mac the    /// owner has since removed can lapse.    pub server: Option<String>,    /// WHO REMOVED this device, by name, when a `device_revoked` said so    /// (`removedBy`). The removed phone's receipt names them.    pub removed_by: Option<String>,}impl ServerRefusal {    pub fn new(message: impl Into<String>, status: u16) -> ServerRefusal {        ServerRefusal {            message: message.into(),            status,            code: None,            existing_connection_id: None,            retry_after_seconds: None,            server: None,            removed_by: None,        }    }    /// The machine that answered, by its `x-cotton-server` tag. A blank tag    /// named nobody.    #[must_use]    pub fn answered_by(mut self, tag: Option<&str>) -> ServerRefusal {        self.server = tag            .map(str::trim)            .filter(|tag| !tag.is_empty())            .map(str::to_string);        self    }    #[must_use]    pub fn with_code(mut self, code: impl Into<String>) -> ServerRefusal {        self.code = Some(code.into());        self    }    #[must_use]    pub fn retry_after(mut self, seconds: u32) -> ServerRefusal {        self.retry_after_seconds = Some(seconds);        self    }    /// A failure that never reached a server at all.    pub fn offline(message: impl Into<String>) -> ServerRefusal {        ServerRefusal::new(message, 0)    }    pub fn is_terminal_device_refusal(&self) -> bool {        self.code            .as_deref()            .is_some_and(crate::connection::is_terminal_device_refusal)    }    /// A `426`: this build's schema is older than the file's. Nothing about    /// this device, and nothing a retry changes until the app is updated.    pub fn is_upgrade_required(&self) -> bool {        self.status == 426 || self.code.as_deref() == Some(UPGRADE_REQUIRED)    }    /// The mirror of [`Self::is_upgrade_required`]: this build's schema is    /// NEWER than the serving Mac's file, so the Mac takes nothing from it    /// until the Mac is updated. A Mac says so with [`MAC_BEHIND`]; a Mac cut    /// before that code said only `400 schemaVersion must be N`, and N below    /// this build's schema is the same answer — the owner's phone 254 met it    /// from Macs at 132 (12 Oct 2026) and drew the sentence raw.    pub fn is_mac_behind(&self) -> bool {        self.code.as_deref() == Some(MAC_BEHIND)            || (self.status == 400                && schema_the_mac_asks(&self.message)                    .is_some_and(|mac| mac < cotton_store::migrate::SCHEMA_VERSION))    }}/// The schema N of a `schemaVersion must be N` answer.fn schema_the_mac_asks(message: &str) -> Option<u32> {    let (_, after) = message.split_once("schemaVersion must be ")?;    let digits: String = after.chars().take_while(char::is_ascii_digit).collect();    digits.parse().ok()}/// The server's code for "this build folds a schema older than the file's".pub const UPGRADE_REQUIRED: &str = "upgrade_required";/// The server's code for "the file is on a schema OLDER than this build's":/// the Mac is the one to update, and nothing this device does changes it.pub const MAC_BEHIND: &str = "mac_behind";/// How long ONE request may take before it is abandoned.////// Sixty seconds, the phone's own ceiling and for the phone's own reason: a/// socket that hangs instead of erroring is not a slow request, it is one that/// never settles, and a sync loop holding one cycle at a time is a loop that/// never runs again. On 2026-09-07 exactly one did and a phone stopped syncing/// for thirty-three minutes with no error, no failed cycle and no event/// anywhere. It is a CEILING, not a target — everything real finishes in well/// under a second — and the cost of being wrong is one retried request.////// Declared here and honoured by whoever implements [`ServerFetch`], because/// the timeout belongs to the thing that holds the socket.pub const REQUEST_CEILING_MS: u64 = 60_000;/// The slowest upload a ceiling waits for: every byte of a request BODY buys/// the call this much more time on top of its ceiling ([`body_allowance`]).////// A ceiling is a deadline for the WHOLE call, and a whole call includes/// sending the body: sixty seconds is fifteen megabytes on a two-megabit/// uplink, and a photo the Mac mirrors to a bucket can be ten times that./// Thirty-two kibibytes a second is an eighth of that uplink — a real upload/// always fits, and a stuck one still ends.pub const BODY_FLOOR_BYTES_PER_SECOND: u64 = 32 * 1024;/// The time a request body of `bytes` buys on top of a call's ceiling.pub fn body_allowance(bytes: usize) -> std::time::Duration {    std::time::Duration::from_secs((bytes as u64).div_ceil(BODY_FLOOR_BYTES_PER_SECOND))}/// One request against the server this Mac is connected to.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ClientRequest {    pub method: &'static str,    /// Path and query, never an origin: the connection owns the address, and a    /// caller that spelled one would be a second opinion about which server    /// this is.    pub path: String,    pub body: Option<Vec<u8>>,    pub content_type: Option<&'static str>,    /// What this caller can read back COMPRESSED, when it can read anything    /// compressed at all.    ///    /// ONE route sets it — the snapshot — and that is the point. The transport    /// here inflates nothing on its own, so a header sent on a request whose    /// reader is `serde_json::from_slice` would be a gzip parsed as JSON the    /// first time a server grew a compression layer. A caller that asks is a    /// caller that has arranged to inflate.    pub accept_encoding: Option<&'static str>,    /// A SHORTER ceiling than [`REQUEST_CEILING_MS`], for a call whose answer    /// is optional.    ///    /// **THE 37-SECOND LAUNCH.** `REQUEST_CEILING_MS` is sixty seconds because    /// a socket that never settles must not hold a sync loop for ever; it is a    /// backstop, not a budget. A Mac's launch pass asks `GET    /// /v1/code/credentials` before it trusts the credential it already holds    /// (`git::keychain::still_live`), and on a serving Mac that request goes    /// out over the relay and back down its own tunnel — so a launch that    /// arrives before the tunnel line is active is HELD by the relay for up to    /// fifty seconds, and 37 s of that was measured. The probe's own answer is    /// documented as optional: *"a server that cannot be reached answers `None`    /// and changes nothing"*. So it asks for a ceiling it can afford to hit.    ///    /// `None` means [`REQUEST_CEILING_MS`], which is every other call.    pub ceiling_ms: Option<u64>,    /// Resume a body from this byte: `Range: bytes=N-`.    ///    /// ONE route sets it — the snapshot, whose prepared copy is kept on the    /// server so a download cut short asks for the rest of it rather than all    /// of it again. The copy id in the signed query is what makes the bytes    /// the same bytes; the header is unsigned, like `Accept-Encoding`. `None`    /// is every other call.    pub range: Option<u64>,}impl ClientRequest {    pub fn get(path: impl Into<String>) -> ClientRequest {        ClientRequest {            method: "GET",            path: path.into(),            body: None,            content_type: None,            accept_encoding: None,            ceiling_ms: None,            range: None,        }    }    pub fn post_json(path: impl Into<String>, body: Vec<u8>) -> ClientRequest {        ClientRequest {            method: "POST",            path: path.into(),            body: Some(body),            content_type: Some("application/json"),            accept_encoding: None,            ceiling_ms: None,            range: None,        }    }    /// A DELETE with no body — a revoke, which names what it revokes in the    /// path and has nothing else to say.    pub fn delete(path: impl Into<String>) -> ClientRequest {        ClientRequest {            method: "DELETE",            path: path.into(),            body: None,            content_type: None,            accept_encoding: None,            ceiling_ms: None,            range: None,        }    }    /// Say this caller will inflate a gzipped answer.    #[must_use]    pub fn accepting_gzip(mut self) -> ClientRequest {        self.accept_encoding = Some("gzip");        self    }    /// Name the database this request is about, as `database=<id>` in the    /// query.    ///    /// In the PATH rather than a field beside it, because the signature covers    /// path and query: the database a request names is inside what the device    /// signed, and a clock-corrected retry (a clone of this request) names the    /// same one. The id is a workspace id — a UUID — so it needs no escaping.    #[must_use]    pub fn for_database(mut self, id: &str) -> ClientRequest {        let joiner = if self.path.contains('?') { '&' } else { '?' };        self.path = format!(            "{}{joiner}{}={id}",            self.path,            crate::connection::list::DATABASE_QUERY        );        self    }    /// The database this request names, when it names one.    pub fn database(&self) -> Option<&str> {        let (_, query) = self.path.split_once('?')?;        query.split('&').find_map(|pair| {            pair.strip_prefix(crate::connection::list::DATABASE_QUERY)?                .strip_prefix('=')                .filter(|id| !id.is_empty())        })    }    /// Give up on this one after `ms` rather than after the whole ceiling.    ///    /// **ONLY FOR A CALL WHOSE ANSWER IS OPTIONAL.** A shorter ceiling turns a    /// slow server into a failed request, so it belongs to a caller that treats    /// "I could not ask" as a state and not as an error. See    /// [`ClientRequest::ceiling_ms`] for the launch this exists for.    #[must_use]    pub fn within_ms(mut self, ms: u64) -> ClientRequest {        self.ceiling_ms = Some(ms);        self    }    /// Ask for the body from byte `start` on ([`ClientRequest::range`]).    #[must_use]    pub fn from_byte(mut self, start: u64) -> ClientRequest {        self.range = Some(start);        self    }}/// What one came back with. A 2xx only — anything else is a [`ServerRefusal`].#[derive(Debug, Clone, PartialEq, Eq)]pub struct ClientAnswer {    pub status: u16,    pub body: Vec<u8>,}impl ClientAnswer {    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, ServerRefusal> {        serde_json::from_slice(&self.body).map_err(|error| {            // A 2xx whose body is not what the route documents is the server            // being wrong, not the network — but it is still transient from            // here, so it climbs the ladder rather than stopping the loop.            ServerRefusal::new(                format!("the server's answer could not be read: {error}"),                self.status,            )        })    }}/// An answer whose BODY has not been read yet.////// Two things beyond `Read`, and each is why this is a trait rather than a/// struct: the status and headers a caller branches on before it decides to/// read at all, and the read timeout — which is/// [`REQUEST_CEILING_MS`] for an ordinary answer and/// a stall timeout for one that is a whole file.pub trait Answer: std::io::Read + Send {    fn status(&self) -> u16;    /// One header, matched case-insensitively.    fn header(&self, name: &str) -> Option<String>;    /// What `Content-Length` promised, when the server said.    fn content_length(&self) -> Option<u64>;    /// How long ONE read of the body may block from here on.    fn set_read_timeout(&mut self, timeout: std::time::Duration) -> std::io::Result<()>;    /// What closes this answer's socket from another thread — a sync read    /// cancelling a media fetch ([`records_first::RecordsFirst::streaming`]).    /// `None` for an answer with no socket of its own.    fn closer(&self) -> Option<records_first::Closer> {        None    }}/// How a request actually goes out.////// A seam so the whole ladder above it — the moved follow, the clock/// correction, the terminal notes — is tested against a SCRIPT rather than/// against a socket, and so the same code is proved against a real/// `cotton-server` on an ephemeral port by swapping this one value.pub trait Exchange: Send + Sync + std::fmt::Debug {    fn send(        &self,        origin: &Origin,        request: &http1::Http1Request<'_>,        ceiling: std::time::Duration,    ) -> Result<Box<dyn Answer>, String>;    /// The same request with its body STREAMED off `body`, `length` bytes,    /// rather than held: a file going up (`media::transport`). `request.body`    /// is `None`; the deadline is `ceiling` plus what `length` buys.    fn send_stream(        &self,        origin: &Origin,        request: &http1::Http1Request<'_>,        body: &mut dyn std::io::Read,        length: u64,        ceiling: std::time::Duration,    ) -> Result<Box<dyn Answer>, String>;    /// Whether two requests may be in the air at once, each answered as asked (FIRST SYNC FAST: the next sync page    /// is asked while this one folds). The real socket dials each request on its own; a scripted exchange answers    /// in the order it was written, so asking ahead would hand a later reply to an earlier request.    fn concurrent(&self) -> bool {        false    }}/// The real one: dial, write, read the head, hand back the socket.////// **`ceiling` IS A DEADLINE FOR THE WHOLE EXCHANGE** — the lookup, the/// connect, the handshake, the request, the head and the body — plus what the/// request's body buys ([`body_allowance`]). It is computed once, here, and/// stays armed on the socket the answer reads from, so a body that trickles/// ends where the head would have. A caller whose answer is a whole database/// asks for the stall window instead ([`Answer::set_read_timeout`]).#[derive(Debug, Default, Clone, Copy)]pub struct SocketExchange;impl Exchange for SocketExchange {    fn concurrent(&self) -> bool {        true    }    fn send(        &self,        origin: &Origin,        request: &http1::Http1Request<'_>,        ceiling: std::time::Duration,    ) -> Result<Box<dyn Answer>, String> {        let deadline = std::time::Instant::now()            + ceiling            + body_allowance(request.body.map_or(0, <[u8]>::len));        let wire = wire::dial_by(origin, deadline)?;        let answer = http1::send(wire, request)            .map_err(|error| format!("{} did not answer ({error})", origin.text))?;        Ok(Box::new(answer))    }    fn send_stream(        &self,        origin: &Origin,        request: &http1::Http1Request<'_>,        body: &mut dyn std::io::Read,        length: u64,        ceiling: std::time::Duration,    ) -> Result<Box<dyn Answer>, String> {        let deadline = std::time::Instant::now()            + ceiling            + body_allowance(usize::try_from(length).unwrap_or(usize::MAX));        let wire = wire::dial_by(origin, deadline)?;        let answer = http1::send_stream(wire, request, body, length)            .map_err(|error| format!("{} did not answer ({error})", origin.text))?;        Ok(Box::new(answer))    }}/// THE seam a remote connection offers: one signed request.////// `connection.rs` is the implementation — the device signature, the base/// address and the `device_clock` re-sign are all its, and none of them is/// visible here.pub trait ServerFetch: Send + Sync + std::fmt::Debug {    fn call(&self, request: ClientRequest) -> Result<ClientAnswer, ServerRefusal>;    /// Remove through the serving Mac. Durable transports retain an unanswered    /// request for their next contact; an approval is never deleted locally.    fn remove_device(&self, device: &str, erase: bool, database: Option<&str>) -> Result<ClientAnswer, ServerRefusal> {        self.call(device_removals::Removal { origin: String::new(), database: database.unwrap_or_default().into(), device: device.into(), erase }.request())    }    /// The way the last request the Mac answered went, as a person reads it    /// ("home network", "Tailscale", "over the relay") — for the Debug    /// group's exchange lines. `None` before any answer, and for a fetch that    /// does not know.    fn answered_way(&self) -> Option<&'static str> {        None    }    /// The records-first gate this fetch's requests meet at    /// ([`records_first::RecordsFirst`]); `None` for a fetch with none, whose    /// media never yields.    fn records_first(&self) -> Option<std::sync::Arc<records_first::RecordsFirst>> {        None    }}/// What was behind the last transport failure, when the transport knew.////// The store's `SyncTransport` answers a plain `String` on the way out — one/// message, no status, no code — which is right for the store (a transport/// failure is not a store failure) and not enough for the loop: the four/// TERMINAL device refusals are told apart from a transient one by their CODE,/// and a `Retry-After` is a number the server sent. So a transport remembers/// its last refusal and the cycle asks./// Bytes a transport carried, and the way it last went/// ([`RefusalAware::moved`]).#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct Moved {    pub sent: u64,    pub received: u64,    pub way: Option<&'static str>,}pub trait RefusalAware {    /// The last exchange asked this holder to push missing originals.    fn readthrough_pending(&self) -> bool { false }    /// What this transport has carried since it was made, and the way it    /// last went — one pass's bytes, since a pass makes its own transport.    fn moved(&self) -> Moved {        Moved::default()    }    fn last_refusal(&self) -> Option<ServerRefusal>;    /// Whether the page just folded asks the pass to end there, still behind:    /// what it folded is drawn (a pass tells the screens once it ends) and    /// the next pass comes straight back for the rest. Asked once a page, and    /// answered once. The default never does.    fn rests(&self) -> bool {        false    }    /// The page just asked folded into the copy and stands: told once a    /// page, after its fold committed, never after one that failed. The    /// object's transport lets the parks of the rows it opened go here    /// ([`crate::seal::Note::Unparked`]). The default does nothing.    fn folded(&self) {}    /// Would this device take the WHOLE FILE of `database` instead of its    /// pages, if the serving Mac finds it far behind    /// (`cotton_store::protocol::types::ExchangeRequest::takes_copy`)? Only a    /// phone's own database, while its [`CopyGate`] allows. The    /// default is `false`: a Mac, a peer pass, a joined line and a test fake    /// page as they always did.    fn takes_copy(&self, _database: &str) -> bool {        false    }    /// The gate this transport's requests go through, so a pass the loop    /// stopped waiting for can have its read cut from another thread. The    /// default has none.    fn gate(&self) -> Option<std::sync::Arc<records_first::RecordsFirst>> {        None    }    /// Is the database this transport is bound to listed for this device right    /// now? A pass asks this BEFORE it reads its file, and an unlisted    /// database sends nothing.    ///    /// Here rather than on [`SyncingTransport`], which every type gets by a    /// blanket impl and so could never override. The default is `true`: an    /// unbound transport, a peer pass and a test fake are bound to no list,    /// and nothing changes for them. An `Err` is a probe that could not be    /// answered; the refusal behind it is [`Self::last_refusal`].    fn listed(&mut self) -> Result<bool, String> {        Ok(true)    }    /// [`Self::listed`] for ANY database this device holds — what the pass    /// over every held database asks per section, of the one transport that    /// carries them all. One probe answers for every database of the pass.    fn listed_database(&mut self, _database: &str) -> Result<bool, String> {        Ok(true)    }    /// The file this transport's pass is over, lent to it for the one write    /// it makes itself, before its pull folds: the object transport adds to    /// the copy the columns the object's definitions name that this build's    /// tables lack (`object::ObjectTransport::hold_served`). Handed by    /// whoever made the transport for the pass, before it is asked, so the    /// write goes through the pass's own handle and never a second open of    /// the copy. The default takes nothing: a transport that writes nothing    /// of its own needs no file.    fn lend_file(&mut self, _file: std::sync::Arc<dyn crate::sync::cycle::LendsFile + Send + Sync>) {}}/// What the sync loop drives: the store's ONE call, plus the refusal behind a/// failure. Both transports are `Send` and own what they need, so a cycle can/// run on a blocking thread./// Asked as each page is built: would this device take a copy of the whole/// file right now? The phone's answer is `cotton-ffi`'s/// (`phone::net::copy_gate`) — yes unless a failed copy's pause stands, and/// never by the kind of network; nothing else sets one.pub type CopyGate = std::sync::Arc<dyn Fn() -> bool + Send + Sync>;pub trait SyncingTransport: cotton_store::exchange::SyncTransport + RefusalAware + Send {}impl<T: cotton_store::exchange::SyncTransport + RefusalAware + Send> SyncingTransport for T {}#[cfg(test)]#[path = "mod_tests.rs"]mod tests;