//! A peer's bytes, read into ops — ONE of the three places a [`CottonOp`] is //! built (`mint` writes this file's own; `stored` reads one back out of this //! file's tables). //! //! It answers a REASON per op rather than failing the batch: one malformed op //! in a page costs its neighbours nothing, and the reason goes back to the //! peer as that op's rejection. The checks are the ones every reader of the //! wire has always made (`cotton-tools/src/sync/apply.rs`'s `parse_op`, which //! slice 2c points here): non-empty strings, a kind this build folds, a //! numeric schema version, and a patch exactly when the kind needs one. use serde_json::{Map, Value}; use crate::actor::Actor; use crate::canonical::{self, Kind, Receipt}; use crate::protocol::types::{CottonOp, OpKind}; /// One op off the wire: its id and its receipt. Everything else the op /// carries is read out of the receipt, so a peer cannot say one thing beside /// the bytes and another inside them. pub fn op(raw: &Value) -> std::result::Result { let Some(object) = raw.as_object() else { return Err("op is not an object".to_string()); }; let string = |key: &str| -> std::result::Result { match object.get(key).and_then(Value::as_str) { Some(value) if !value.is_empty() => Ok(value.to_string()), _ => Err(format!("{key} must be a non-empty string")), } }; let op_id = string("opId")?; let receipt = string("receipt")?; let mut op = from_bytes(op_id, receipt.as_bytes())?; // The signature rides beside the bytes, as the sender stored it. What it // is worth is the signature screen's question, not the reader's. op.sig = match object.get("sig") { None | Some(Value::Null) => None, Some(Value::String(sig)) if !sig.is_empty() => Some(sig.clone()), Some(_) => return Err("sig must be a non-empty string".to_string()), }; Ok(op) } /// An op from a receipt's stored or carried bytes, verbatim. pub fn from_bytes(op_id: String, bytes: &[u8]) -> std::result::Result { let receipt = canonical::decode(bytes).map_err(|e| e.to_string())?; let text = String::from_utf8(bytes.to_vec()).map_err(|_| "receipt bytes are not UTF-8".to_string())?; Ok(reading(op_id, &receipt, text)) } /// An op from a receipt this file just minted: the one place bytes are made. pub fn from_receipt(op_id: String, receipt: &Receipt) -> crate::error::Result { let bytes = canonical::encode(receipt)?; let text = String::from_utf8(bytes) .map_err(|_| crate::error::StoreError::encode("the canonical form is UTF-8 by construction"))?; Ok(reading(op_id, receipt, text)) } /// An op built from a change OUTSIDE `mint` — for fixtures and tests, which /// want a write at a stamp and an author of their choosing. The receipt is /// the one `mint` would make (`mint::receipt_of`), under `actor`. pub fn op_of_change( db: &crate::driver::Driver, change: &crate::mint::Change, hlc: &str, author: &str, actor: &Actor, op_id: String, ) -> crate::error::Result { let receipt = crate::mint::receipt_of(db, "test", change, hlc, author, &actor.to_wire())?; from_receipt(op_id, &receipt) } fn reading(op_id: String, receipt: &Receipt, text: String) -> CottonOp { CottonOp { op_id, device_id: receipt.author.clone(), kind: match receipt.kind { Kind::Create | Kind::Change => OpKind::Upsert, Kind::Retract => OpKind::Delete, }, table: receipt.table.clone(), row_id: receipt.row_id.clone(), patch: match receipt.kind { Kind::Retract => None, Kind::Create | Kind::Change => { let mut map = Map::with_capacity(receipt.fields.len()); for (name, value) in &receipt.fields { map.insert(name.clone(), value.clone()); } Some(map) } }, hlc: receipt.stamp.clone(), schema_version: receipt.schema, actor: receipt.actor.clone(), receipt: text, restamps: receipt.restamps.clone(), sig: None, } } /// An actor off the wire — the one reader of an actor's text outside this /// file's own rows. Slice 3a's receipts carry one per op; a parked or stored /// actor is read by [`crate::stored::actor`]. pub fn actor(raw: &Value) -> std::result::Result { let Some(text) = raw.as_str() else { return Err("actor must be a string".to_string()); }; Actor::from_wire(text) } /// A page off the wire: each op's own verdict, in the page's order. pub fn ops(raw: &[Value]) -> Vec> { raw.iter().map(op).collect() } #[cfg(test)] #[path = "wire_tests.rs"] mod tests;