//! The wire protocol. One op is one row-level change; a batch of them is what //! crosses between two files in either direction — and since version 8 there is //! ONE verb that carries them, [`ExchangeRequest`], because the two sides of a //! sync are the same side. //! //! The serde names ARE the wire names — the Rust store has to be able to read //! a body the TypeScript server wrote and vice versa, so every rename here is //! load-bearing. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; /// Values as they sit in SQLite — storage-encoded, never domain objects. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum StorageValue { Null, Number(f64), Text(String), } pub use cotton_rules::change::OpKind; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct CottonOp { /// ULID, client-generated. The idempotency key on both sides. #[serde(rename = "opId")] pub op_id: String, /// `device:` for a user's device, `server:` for server writes. #[serde(rename = "deviceId")] pub device_id: String, pub kind: OpKind, /// Physical table name, e.g. `cotton_todos`. pub table: String, #[serde(rename = "rowId")] pub row_id: String, /// Only the columns that changed. Null iff `kind == Delete`. pub patch: Option>, pub hlc: String, #[serde(rename = "schemaVersion")] pub schema_version: u32, /// The actor the receipt names (`crate::actor`), as its wire text. pub actor: String, /// THE WRITE: the receipt's canonical bytes (`crate::canonical`), as /// minted — UTF-8 JSON carried verbatim, stored verbatim, and the bytes /// keys will sign. Every other field here is a reading of it. pub receipt: String, /// The op id of the receipt this one re-dates (slice 1), read out of the /// receipt like every field beside it. Absent from the wire when it /// replaces nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub restamps: Option, /// The Ed25519 signature of the device that minted the receipt, over its /// bytes and the database id (`crate::signed`), base64url unpadded. Beside /// the bytes, never inside them. Absent on a receipt minted by a handle /// with no device key. #[serde(default, skip_serializing_if = "Option::is_none")] pub sig: Option, } /// Why one op did not land, and whether asking again could ever change that. /// /// `retryable` is ADDITIVE and ABSENT MEANS FINAL — which keeps a peer that /// never sends the field behaving exactly as it does today. So `None` must /// serialize to nothing at all: a `"retryable": false` on the wire is a /// different message from no field, and the other side reads the difference. /// /// Almost every rejection is final: a CHECK, a UNIQUE, a NOT NULL, a bad /// reference. The exception is a peer that is simply BEHIND, which resolves /// itself the moment that peer is updated. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PushRejection { #[serde(rename = "opId")] pub op_id: String, pub reason: String, /// Transient — the caller keeps the op queued and tries again later. #[serde(skip_serializing_if = "Option::is_none", default)] pub retryable: Option, /// WHY it is transient, as a word a screen can key on rather than a /// sentence it would have to parse: [`REJECTION_SERVER_BEHIND`] when the /// peer's build is older than the writer's, [`REJECTION_PHONE_BEHIND`] /// when the write is older than the peer's schema. Absent on every final /// rejection, and absent from a peer one build behind this field — which /// reads exactly as it did before: held, with no word about why. #[serde(skip_serializing_if = "Option::is_none", default)] pub code: Option, /// The judge's time when it refused a receipt as [`REJECTION_FUTURE`] /// (slice 1): ISO-8601, the form the relay's `HELLO.server_time` takes, so /// a replica takes it as a reading the same way. Absent on every other /// rejection. #[serde(rename = "serverTime", skip_serializing_if = "Option::is_none", default)] pub server_time: Option, } /// A rejection's reason word: the receipt is stamped more than ten minutes /// ahead of the judge's time (slice 1's arrival bound). Held, not final: the /// pusher re-dates it to when it was minted and sends it again, and /// `serverTime` is the judge time it reads that by. pub const REJECTION_FUTURE: &str = "future"; /// A retryable rejection's reason word: the PEER is behind the writer's /// schema, and the op lands verbatim once the peer is updated. pub const REJECTION_SERVER_BEHIND: &str = "server_behind"; /// A retryable rejection's reason word (slice 12): the serving Mac is at an /// epoch this request carried neither as its `handedOverEpoch` nor as its /// `handingOverTo`, so nothing in it was folded. The device hands over to that /// epoch first, and its queue goes after. pub const REJECTION_HAND_OVER: &str = "hand_over"; /// A retryable rejection's reason word: the WRITE is behind the peer's /// schema — it names a column the peer has since dropped — and it lands once /// the writer is updated and re-offers it. pub const REJECTION_PHONE_BEHIND: &str = "phone_behind"; /// A held rejection's reason word: the Mac parked this receipt — `waiting` /// for its author's fact, or `newer-shape` above its schema — and folds it /// itself once that fact arrives or it moves. Told only to /// a caller that asked ([`ExchangeRequest::parks_waiting`]); the caller parks /// it push-side, so it stops travelling on every pass, and ends the park once /// the Mac's `seen` passes its stamp. pub const REJECTION_AUTHOR_WAITING: &str = "author_waiting"; /// A rejection's reason word for an op the PEER DID NOT REACH in this /// exchange (film-progress-flood, 17 Nov 2026): a transport that posts each /// write in its own request (the personal object) sends at most so many rows /// a pass so the pass's pull lands every pass, and the rest wait their turn. /// Neither delivered nor held: the op stays queued as it is, no attempt is /// counted, and the drain goes on with the next exchange. pub const REJECTION_DEFERRED: &str = "deferred"; impl PushRejection { /// A final rejection — `retryable` absent, which is what "final" is /// spelled as on the wire. pub fn final_reason(op_id: impl Into, reason: impl Into) -> Self { PushRejection { op_id: op_id.into(), reason: reason.into(), retryable: None, code: None, server_time: None, } } /// A rejection that will clear itself once one side is updated: held, /// never parked, and named by `code` so a screen can say which side. pub fn held(op_id: impl Into, reason: impl Into, code: &'static str) -> Self { PushRejection { op_id: op_id.into(), reason: reason.into(), retryable: Some(true), code: Some(code.to_string()), server_time: None, } } /// An op the peer did not reach this exchange ([`REJECTION_DEFERRED`]): /// still queued, sent with the next. pub fn deferred(op_id: impl Into) -> Self { PushRejection::held(op_id, "not reached this exchange; sent with the next", REJECTION_DEFERRED) } /// The arrival bound's refusal ([`REJECTION_FUTURE`]), carrying the judge /// time it was judged against. pub fn future(op_id: impl Into, reason: impl Into, server_time: String) -> Self { PushRejection { server_time: Some(server_time), ..PushRejection::held(op_id, reason, REJECTION_FUTURE) } } } /// How many ROWS one exchange page carries when the caller names no limit. /// /// ROWS, never ops: a row whose columns came from two writes is two ops and one /// row, and a page that counted ops could end inside a row. Five hundred is the /// old pull page, kept deliberately — the body is the same size it always was, /// and the number that changed is what it counts. pub const EXCHANGE_PAGE_ROWS: u32 = 500; /// The largest page a caller may ask for. pub const MAX_EXCHANGE_PAGE_ROWS: u32 = 2_000; /// ONE SYMMETRIC VERB. What a caller sends `POST /v1/sync/exchange`. /// /// There is no push and no pull: a device hands over what it wrote and says how /// far it has seen each AUTHOR, and the answer is what it has not seen plus /// what the peer made of the writes. Both sides run the same fold /// ([`crate::fold::fold_ops`]), so "who wins" has one implementation and the /// two halves cannot disagree. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ExchangeRequest { #[serde(rename = "workspaceId")] pub workspace_id: String, /// `{author: hlc_seen}` — one entry per WRITER this file has folded, never /// per peer. An author missing from the map has never been seen, which is /// what `""` means too. [`crate::changes::ORIGIN_AUTHOR`] spells its cursor /// as a `(table, row)` token rather than a stamp. pub cursors: BTreeMap, /// This caller's own outbox, drained by the same call. pub ops: Vec, /// How many ROWS the answer may carry. Defaults to /// [`EXCHANGE_PAGE_ROWS`], capped at [`MAX_EXCHANGE_PAGE_ROWS`]. #[serde(skip_serializing_if = "Option::is_none", default)] pub limit: Option, /// The schema this caller can fold, required on every wire request. #[serde(rename = "schemaVersion", deserialize_with = "present")] pub schema_version: Option, /// The lowest file stamp this caller's build folds without a rebuild /// (`schema::move_intents::floor`). Read by a Mac whose file is BELOW /// [`Self::schema_version`]: the newer side's floor must reach the older /// side's stamp (`exchange::admission`). Absent from a build before it, /// which a file below it then refuses as before. #[serde(rename = "schemaFloor", default, skip_serializing_if = "Option::is_none")] pub schema_floor: Option, /// THE LAST SERVING EPOCH THIS FILE HANDED OVER TO (slice 12): its /// `_meta.handed_over_epoch`, `null` on a file that has never handed over. /// Required on the wire, null or not: a server at epoch E folds a request /// only when this or [`Self::handing_over_to`] is E, so a missing mark is /// never read as "handed over". #[serde(rename = "handedOverEpoch", deserialize_with = "nullable")] pub handed_over_epoch: Option, /// THE EPOCH A HAND-OVER PASS IS HANDING OVER TO: from the second request /// of the pass, the epoch its first answer named. Absent outside a pass. #[serde(rename = "handingOverTo", default, skip_serializing_if = "Option::is_none")] pub handing_over_to: Option, /// THE NIGHT THIS REPLICA IS A COPY OF: the author of its latest serving /// fact. A Dev server serving the owner's copy, restored afresh every /// night, answers a replica of another night with that copy's end /// ([`ExchangeResponse::copy_night`]) and folds nothing of it. Every other /// server reads nothing here. #[serde(rename = "servingAuthor", default, skip_serializing_if = "Option::is_none")] pub serving_author: Option, /// THIS CALLER WOULD TAKE THE WHOLE FILE INSTEAD OF THE PAGES, if the /// serving Mac finds it far behind ([`ExchangeResponse::copy`]). Said by a /// phone for its own database on any network — Wi-Fi and cellular alike /// (owner, 12 Oct 2026) — and not while a failed copy's pause stands; a /// Mac never says it. Absent is `false`. #[serde(rename = "takesCopy", default, skip_serializing_if = "std::ops::Not::not")] pub takes_copy: bool, /// THIS CALLER PARKS A RECEIPT THE MAC PARKED `waiting`: told so as a held /// [`REJECTION_AUTHOR_WAITING`], it parks that receipt on its side and /// stops offering it on every pass. A caller that does not say it is told /// nothing, as before — a held refusal it cannot read would stop its /// queue. Absent is `false`. #[serde(rename = "parksWaiting", default, skip_serializing_if = "std::ops::Not::not")] pub parks_waiting: bool, } /// How far behind a caller must be, in changes (receipts), before a copy of /// the whole file is faster than the pages ([`ExchangeResponse::copy`]). /// Forty default pages; past this the pages cost the phone more than the /// download of a file cut for it. pub const COPY_FASTER_PAST: u64 = 20_000; /// THE WHOLE FILE IS FASTER: the serving Mac's offer to a caller that said it /// [`ExchangeRequest::takes_copy`] and is more than [`COPY_FASTER_PAST`] /// changes behind. The caller stops paging and fetches the copy cut for it /// over the first-copy path (`GET /v1/sync/snapshot`), replacing its file /// once its own outbox has landed. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopyOffer { /// About how big the file is, in bytes, on the serving Mac — before the /// device's keep rules cut it and before the gzip. An upper bound for the /// sentence; the download says the real size. pub bytes: u64, } /// The Mac behind an exchange answer, as it names itself: the name a person /// gave it and its app's version label. Facts about the running binary and /// the machine, never about a credential or a route. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnsweredBy { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option, } /// An original this serving Mac needs from this holder's replica store. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct WantedUpload { pub key: String, pub url: String, pub method: String, pub headers: BTreeMap, } /// What the other side answers. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ExchangeResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub wanted: Vec, /// The file this answer came from — the responder's own open file, never /// an echo of the request. A device holding several databases refuses a /// page that names another one rather than folding it into the wrong file. #[serde(rename = "workspaceId")] pub workspace_id: String, /// The writes this caller has not seen, in stamp order per author, whole /// rows only. pub ops: Vec, /// The caller's cursor map, advanced by exactly what `ops` carries. When /// `hasMore` is false this is the responder's whole ceiling; while it is /// true it is where the next page resumes, which is the only value that /// cannot skip a write. pub cursors: BTreeMap, /// Whether asking again from `cursors` would answer anything. #[serde(rename = "hasMore")] pub has_more: bool, /// The responder's schema, required on every wire answer. #[serde(rename = "schemaVersion", deserialize_with = "present")] pub schema_version: Option, /// What the RESPONDER's fold made of the ops the caller sent: `{table: /// rows}`, counted off its own `FoldResult::applied_rows`. /// /// ROWS, never ops, and never an accepted COUNT — one row arrives as /// several ops, so counting ops over-reports, and two devices that /// converged on the same derived id move the row count by zero while a row /// really did move. A rejected op is simply absent from it. #[serde(rename = "appliedRows")] pub applied_rows: BTreeMap, /// The ops that did not land, with the reason. pub rejected: Vec, /// How far the RESPONDER has seen each AUTHOR — the mirror of the /// request's `cursors`, and what a caller hands over FROM. /// /// `cursors` above is the CALLER's map, advanced; this one is the /// responder's own. Without it an exchange is caller-driven and a device /// hands over only its `_outbox`, so a device that had already synced its /// rows elsewhere — outbox empty — hands over nothing at all on a join. /// With it, a caller can see exactly which authors the peer is behind on /// and send those rows as the `ops` of the next call. /// pub seen: BTreeMap, /// The epoch of the responder's latest `cotton_serving_machine` fact — /// which Mac's term this answer was given in. Absent when the responder's /// file holds no fact. A caller holding a NEWER fact refuses the whole /// answer (`exchange::fold_answer`): an old Mac is answering. #[serde(rename = "servingEpoch", default, skip_serializing_if = "Option::is_none")] pub serving_epoch: Option, /// THE JUDGE'S TIME when it answered (slice 1): ISO-8601, as the relay's /// `HELLO.server_time`, from which a replica takes a reading. Absent from /// a responder with no judge, and from a judge with no judge time yet — /// which serves no page at all. #[serde(rename = "serverTime", default, skip_serializing_if = "Option::is_none")] pub server_time: Option, /// THE RESTORE POINT (slice 12): `{author: stamp}`, the per-author ceiling /// the take-over act froze into this epoch's serving fact /// (`start_positions.positions`), carried on every answer of that epoch. /// A device handing over to it starts each author at `min(restored, /// seen)`, and an author absent from it from nothing — `seen` rises with /// every receipt the server folds, so it is never where a hand-over /// starts. Absent when the responder's latest fact froze none: an epoch /// that began without a take-over has no restore point. #[serde(default, skip_serializing_if = "Option::is_none")] pub restored: Option>, /// THE OWNER'S DEV COPY HAS MOVED ON: the night (its serving fact's /// author) a Dev server serving the owner's copy now holds, answered — /// with nothing else — to a replica of another night. That replica is a /// copy of a file that no longer exists: a Dev phone deletes it and /// fetches tonight's (`exchange::fold_answer`'s `CopyReplaced`). Absent /// from every other answer. #[serde(rename = "copyNight", default, skip_serializing_if = "Option::is_none")] pub copy_night: Option, /// HOW FAR BEHIND THIS ANSWER LEAVES THE CALLER, in changes (receipts), /// counted by the serving Mac up to 10,000 and no further (the count is /// inside its write hold): `0` when it says nothing more. What the device /// row's Sync section says remains. Absent from a responder that does not /// count. #[serde(rename = "behindBy", default, skip_serializing_if = "Option::is_none")] pub behind_by: Option, /// WHAT THE CALLER OWED WHEN THIS CATCH-UP BEGAN, in changes (receipts), /// counted IN FULL, once, by the serving Mac outside its write hold and /// kept on the device's sync record there: what the home's catch-up /// percent is a share of. Absent while the device is level, and on the /// answers of a catch-up before the count has finished. #[serde(rename = "owedAtStart", default, skip_serializing_if = "Option::is_none")] pub owed_at_start: Option, /// THE SAME WHOLE, BY TABLE: how many of the changes the caller owed when /// this catch-up began were of each table (`_writes.tbl`), counted once /// by the serving Mac in the same place as `owedAtStart` — outside its /// write hold — and summing to it. What "Email · 41,000 of 58,900" on the /// device's own page is a share of. Absent while the device is level, /// until that count has finished, and from a Mac that does not make it. #[serde(rename = "owedAtStartByTable", default, skip_serializing_if = "Option::is_none")] pub owed_by_table: Option>, /// HOW MANY CHANGES (receipts) THIS ANSWER MOVED THE CALLER PAST, by table /// (`_writes.tbl`): every receipt its page was dealt, counted BEFORE /// anything was left out of `ops` — what the caller's keep rules do not /// keep, its own writes echoed back, a table its build does not know. /// The same unit as `owedAtStart` and `owedAtStartByTable`, so a /// catch-up's percent is these summed over that whole, and it reaches the /// end whatever was left out. Absent from a responder that does not /// count, whose caller counts the receipts `ops` carried instead. #[serde(default, skip_serializing_if = "Option::is_none")] pub passed: Option>, /// WHY THE SERVING MAC COULD NOT WAKE THIS DEVICE the last time it tried /// (the catch-up wake): a fixed sentence such as the vault holding no /// Apple push key — never any part of a key. Absent when the last wake /// went, or none was needed. #[serde(rename = "wakeRefusal", default, skip_serializing_if = "Option::is_none")] pub wake_refusal: Option, /// THE WHOLE FILE IS FASTER ([`CopyOffer`]): present only to a caller /// that [`ExchangeRequest::takes_copy`] and is far behind. #[serde(default, skip_serializing_if = "Option::is_none")] pub copy: Option, /// WHICH MAC ANSWERED, in its own words ([`AnsweredBy`]): its name and /// its app's version, so a device can say what it last heard from /// (phone diagnostics, 12 Oct 2026 — the build line). `None` from a /// server that does not know itself (a test, a headless run). #[serde(rename = "answeredBy", default, skip_serializing_if = "Option::is_none")] pub answered_by: Option, } /// The path a device OPENS a record through: a row outside its keep rules, /// answered whole by the serving Mac (`crate::keep::open`). pub const OPEN_PATH: &str = "/v1/sync/open"; /// "Send me this record": the row a device opened and does not hold. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct OpenRequest { /// The database the row is in; the request's own `?database=` names the /// file, and a body naming another is refused. #[serde(rename = "workspaceId", default)] pub workspace_id: String, /// Physical table name, e.g. `cotton_email_threads`. pub table: String, #[serde(rename = "rowId")] pub row_id: String, /// Where this answer starts, from the last answer's `next`. Absent is the /// beginning. #[serde(default, skip_serializing_if = "Option::is_none")] pub after: Option, /// "Send me this TABLE": set by a device whose keep rule for `table` was /// widened, with the key its fetch has reached (empty at the beginning). /// `row_id` is then empty and unread. The answer says it understood /// ([`OpenResponse::table`]) — a serving Mac built before this reads the /// request as an open of no row and answers nothing, which must never be /// taken for "the table is complete". #[serde(rename = "tableAfter", default, skip_serializing_if = "Option::is_none")] pub table_after: Option, } /// Where an answer to a table selector ([`OpenRequest::table_after`]) stopped. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TableReached { /// The key the answer read up to: the next request's `tableAfter`. pub reached: String, /// There are keys beyond it. pub more: bool, } /// One row an [`OpenResponse`] restated. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct OpenedRow { pub table: String, #[serde(rename = "rowId")] pub row_id: String, } /// The record a device opened: the receipts of the row, of the owning parents /// it could not land without and of the rows it owns, parents first. Folded as /// a pulled arrival. No ops and no rows is a record the Mac does not hold. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct OpenResponse { pub ops: Vec, pub rows: Vec, /// Set when the record is more rows than one answer holds: ask again with /// `after` at this. #[serde(default, skip_serializing_if = "Option::is_none")] pub next: Option, /// Present on every answer to a table selector, and only there: the /// serving Mac's word that it read the request as one. #[serde(default, skip_serializing_if = "Option::is_none")] pub table: Option, } /// The path of the exchange that carries every held database in one call. pub const EXCHANGE_SECTIONS_PATH: &str = "/v1/sync/exchange/all"; /// The most sections one call may carry. pub const MAX_EXCHANGE_SECTIONS: usize = 64; /// ONE EXCHANGE PER CYCLE, OVER EVERY DATABASE A DEVICE HOLDS. What a caller /// sends [`EXCHANGE_SECTIONS_PATH`]: one [`ExchangeRequest`] per database, each /// exactly what it would have sent alone. /// /// An idle database's section carries its cursors and no ops; the caller /// builds it from a note without opening the file, and an answer with nothing /// in it is not folded — which is what makes an idle database cost nothing. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ExchangeSectionsRequest { pub sections: Vec, } /// One answer per section asked, in the order asked. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ExchangeSectionsResponse { pub sections: Vec, } /// What one database's section came back as: the whole [`ExchangeResponse`] it /// would have had alone, or a refusal that names the database and stops there. /// /// A refused section never fails the call — the other databases still fold. /// `Refused` is tried first: it is the only shape that carries `refused`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum SectionAnswer { Refused(SectionRefused), Answered(ExchangeResponse), } impl SectionAnswer { /// The database this section is about, answered or refused. #[must_use] pub fn workspace_id(&self) -> &str { match self { SectionAnswer::Refused(refused) => &refused.workspace_id, SectionAnswer::Answered(answer) => &answer.workspace_id, } } } /// A section the responder would not exchange, and why. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SectionRefused { #[serde(rename = "workspaceId")] pub workspace_id: String, pub refused: SectionRefusal, } /// The refusal a single-database exchange would have answered as its error /// envelope: the same `code` and sentence, and the same machine-readable /// fields (`erase` on a revoked device) under `extra`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SectionRefusal { pub code: String, pub message: String, #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] pub extra: serde_json::Map, } // Optional internally until an exchange has answered, mandatory and non-null on // the wire. Deserialize T directly so absent/null cannot become a silent None. fn present<'de, D, T>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, T: Deserialize<'de>, { T::deserialize(deserializer).map(Some) } // Mandatory on the wire, and `null` is a value: a field that must be SAID // even when what it says is "none". Through `deserialize_with`, so serde reads // an absent key as missing rather than as `None`. fn nullable<'de, D, T>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, T: Deserialize<'de>, { Option::::deserialize(deserializer) } #[cfg(test)] mod tests { use super::*; fn op() -> CottonOp { CottonOp { op_id: "01J0000000000000000000000A".to_string(), device_id: "device:aaaa".to_string(), kind: OpKind::Upsert, table: "cotton_todos".to_string(), row_id: "todo-1".to_string(), patch: Some( serde_json::from_str(r#"{"title":"Ship it","priority":2}"#).expect("valid JSON"), ), hlc: "1700000000000:0000:device:aaaa".to_string(), schema_version: 45, actor: "device-job:test".to_string(), receipt: "{}".to_string(), restamps: None, sig: None, } } #[test] fn an_op_serializes_under_the_wire_names() { let json = serde_json::to_string(&op()).expect("serializes"); assert_eq!( json, r#"{"opId":"01J0000000000000000000000A","deviceId":"device:aaaa","kind":"upsert","table":"cotton_todos","rowId":"todo-1","patch":{"title":"Ship it","priority":2},"hlc":"1700000000000:0000:device:aaaa","schemaVersion":45,"actor":"device-job:test","receipt":"{}"}"# ); assert_eq!( serde_json::from_str::(&json).expect("round-trips"), op() ); } #[test] fn a_delete_carries_a_null_patch() { let mut delete = op(); delete.kind = OpKind::Delete; delete.patch = None; let json = serde_json::to_string(&delete).expect("serializes"); assert!(json.contains(r#""kind":"delete""#), "{json}"); assert!(json.contains(r#""patch":null"#), "{json}"); } #[test] fn an_absent_retryable_is_absent_on_the_wire_not_false() { // ABSENT ≠ false. An older server never sends the field, and the // client's reading of "no field" is "final" — writing `false` would // say the same thing today and a different thing the moment the // client learns to distinguish them. let final_one = PushRejection::final_reason("op-1", "CHECK constraint failed"); let json = serde_json::to_string(&final_one).expect("serializes"); assert_eq!( json, r#"{"opId":"op-1","reason":"CHECK constraint failed"}"# ); assert!(!json.contains("retryable"), "{json}"); } #[test] fn a_retryable_rejection_says_so_explicitly() { let rejection = PushRejection { op_id: "op-2".to_string(), reason: "server schema is older than this client".to_string(), retryable: Some(true), code: None, server_time: None, }; assert_eq!( serde_json::to_string(&rejection).expect("serializes"), r#"{"opId":"op-2","reason":"server schema is older than this client","retryable":true}"# ); } #[test] fn a_held_rejection_carries_its_word_and_a_peer_without_one_reads_it_as_held() { let held = PushRejection::held( "op-3", "server schema is older than this client", REJECTION_SERVER_BEHIND, ); let json = serde_json::to_string(&held).expect("serializes"); assert_eq!( json, r#"{"opId":"op-3","reason":"server schema is older than this client","retryable":true,"code":"server_behind"}"# ); // The field is additive: a body without it still reads as a hold. let older: PushRejection = serde_json::from_str(r#"{"opId":"op-3","reason":"x","retryable":true}"#) .expect("parses"); assert_eq!(older.retryable, Some(true)); assert_eq!(older.code, None); } #[test] fn a_rejection_from_an_older_server_reads_as_final() { let parsed: PushRejection = serde_json::from_str(r#"{"opId":"op-1","reason":"UNIQUE"}"#).expect("parses"); assert_eq!(parsed.retryable, None); } #[test] fn a_section_answer_is_a_whole_answer_or_a_named_refusal() { let wire = serde_json::json!({ "sections": [ { "workspaceId": "ws-1", "ops": [], "cursors": {}, "hasMore": false, "schemaVersion": 1, "appliedRows": {}, "rejected": [], "seen": {} }, { "workspaceId": "ws-2", "refused": { "code": "device_revoked", "message": "this device was revoked" } }, ]}); let parsed: ExchangeSectionsResponse = serde_json::from_value(wire.clone()).expect("parses"); assert!(matches!(&parsed.sections[0], SectionAnswer::Answered(answer) if answer.workspace_id == "ws-1")); assert!(matches!(&parsed.sections[1], SectionAnswer::Refused(refused) if refused.refused.code == "device_revoked")); assert_eq!(parsed.sections[1].workspace_id(), "ws-2"); assert_eq!(serde_json::to_value(&parsed).expect("serializes"), wire); } #[test] fn an_exchange_request_serializes_under_the_wire_names() { let request = ExchangeRequest { takes_copy: false, parks_waiting: false, workspace_id: "ws-1".to_string(), cursors: BTreeMap::from([ ( "device:aaaa".to_string(), "1700000000000:0000:device:aaaa".to_string(), ), ( "origin".to_string(), "origin:cotton_todos:todo-1".to_string(), ), ]), ops: vec![op()], limit: None, schema_version: Some(48), schema_floor: None, handed_over_epoch: None, handing_over_to: None, serving_author: None, }; let json = serde_json::to_string(&request).expect("serializes"); assert!( json.starts_with(r#"{"workspaceId":"ws-1","cursors":{"#), "{json}" ); // The optional page limit is omitted; the schema is always declared. assert!(!json.contains(r#""limit""#), "{json}"); // The mark is said even when it is null; the pass's target only in a pass. assert!(json.ends_with("\"schemaVersion\":48,\"handedOverEpoch\":null}"), "{json}"); assert_eq!( serde_json::from_str::(&json).expect("round-trips"), request ); } #[test] fn an_exchange_response_reports_rows_per_table_and_never_a_count() { let response = ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: "ws-1".to_string(), ops: vec![], cursors: BTreeMap::from([( "device:bbbb".to_string(), "1700000000001:0000:device:bbbb".to_string(), )]), has_more: true, schema_version: Some(36), applied_rows: BTreeMap::from([("cotton_todos".to_string(), 2)]), rejected: vec![], seen: BTreeMap::from([( "device:bbbb".to_string(), "1700000000001:0000:device:bbbb".to_string(), )]), serving_epoch: Some(3), server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }; let json = serde_json::to_string(&response).expect("serializes"); assert_eq!( json, r#"{"workspaceId":"ws-1","ops":[],"cursors":{"device:bbbb":"1700000000001:0000:device:bbbb"},"hasMore":true,"schemaVersion":36,"appliedRows":{"cotton_todos":2},"rejected":[],"seen":{"device:bbbb":"1700000000001:0000:device:bbbb"},"servingEpoch":3}"# ); assert_eq!( serde_json::from_str::(&json).expect("round-trips"), response ); } // RULE: synthetic development peers speak the complete current wire format. // A missing cursor, schema or result must fail instead of masking an old peer. #[test] fn exchange_readers_refuse_missing_or_null_required_fields() { let request = serde_json::json!({ "workspaceId": "ws-1", "ops": [], "cursors": {}, "schemaVersion": 48, "handedOverEpoch": null }); let response = serde_json::json!({ "workspaceId": "ws-1", "ops": [], "cursors": {}, "hasMore": false, "schemaVersion": 48, "appliedRows": {}, "rejected": [], "seen": {} }); for field in ["cursors", "schemaVersion"] { for null in [false, true] { let mut invalid = request.clone(); if null { invalid[field] = Value::Null; } else { invalid.as_object_mut().unwrap().remove(field); } assert!( serde_json::from_value::(invalid).is_err(), "request must require {field} (null={null})" ); } } for field in [ "workspaceId", "cursors", "schemaVersion", "appliedRows", "rejected", "seen", ] { for null in [false, true] { let mut invalid = response.clone(); if null { invalid[field] = Value::Null; } else { invalid.as_object_mut().unwrap().remove(field); } assert!( serde_json::from_value::(invalid).is_err(), "response must require {field} (null={null})" ); } } let request_back = serde_json::from_value::(request.clone()).expect("current request"); let response_back = serde_json::from_value::(response.clone()).expect("current response"); assert_eq!(serde_json::to_value(request_back).expect("serialize"), request); assert_eq!(serde_json::to_value(response_back).expect("serialize"), response); } // RULE: a request always says its hand-over mark (`handedOverEpoch`, null when none) — a missing mark is refused, never read as handed over; `handingOverTo` and `restored` appear only when they say something. #[test] fn a_request_says_its_hand_over_mark_and_an_answer_its_restore_point() { let mut request = serde_json::json!({ "workspaceId": "ws-1", "ops": [], "cursors": {}, "schemaVersion": 48, "handedOverEpoch": 2 }); let parsed = serde_json::from_value::(request.clone()).expect("a mark"); assert_eq!((parsed.handed_over_epoch, parsed.handing_over_to), (Some(2), None)); request["handingOverTo"] = serde_json::json!(3); let parsed = serde_json::from_value::(request.clone()).expect("a pass"); assert_eq!(parsed.handing_over_to, Some(3)); assert_eq!(serde_json::to_value(&parsed).expect("serializes"), request); request.as_object_mut().unwrap().remove("handedOverEpoch"); assert!( serde_json::from_value::(request).is_err(), "a request with no mark is refused, not read as null" ); let response = serde_json::json!({ "workspaceId": "ws-1", "ops": [], "cursors": {}, "hasMore": false, "schemaVersion": 48, "appliedRows": {}, "rejected": [], "seen": {"a": "s9"}, "servingEpoch": 3, "restored": {"a": "s4"} }); let parsed = serde_json::from_value::(response.clone()).expect("an answer"); assert_eq!(parsed.restored, Some(BTreeMap::from([("a".to_string(), "s4".to_string())]))); assert_eq!(serde_json::to_value(&parsed).expect("serializes"), response); } #[test] fn the_page_is_counted_in_rows_and_the_number_is_the_declaration() { assert_eq!(EXCHANGE_PAGE_ROWS, 500); assert_eq!(MAX_EXCHANGE_PAGE_ROWS, 2_000); const { assert!(EXCHANGE_PAGE_ROWS <= MAX_EXCHANGE_PAGE_ROWS) }; } }