//! A row a rule owes its file: an upsert of a patch onto `(table, row_id)`, or //! a retract of the row. A rule plans; its host writes. The phone's store turns //! one into its `LocalChange` (`cotton-store`'s `From`, the same four //! fields), the Worker applies it to its object as JSON: `{table, id, patch}` //! or `{table, id, retract: true}`. use serde::ser::{Serialize, SerializeMap, Serializer}; use serde::Deserialize; use serde_json::{Map, Value}; /// What one op does to one row (re-exported as `cotton_store::protocol::types::OpKind`). #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum OpKind { Upsert, Delete, } impl OpKind { /// The word the `kind` column and the wire both use. pub fn as_str(self) -> &'static str { match self { OpKind::Upsert => "upsert", OpKind::Delete => "delete", } } } /// One planned row. A `Delete` is a Retract, the only delete a rule plans: /// the row leaves while no create is above it, and a later create makes it /// live again. #[derive(Debug, Clone, PartialEq)] pub struct Change { pub kind: OpKind, pub table: String, pub row_id: String, /// `Some` exactly on an upsert, a `serde_json::Map` in the order its keys /// were written: a patch is stored as JSON and its key order is observable. pub patch: Option>, } impl Change { pub fn upsert(table: &str, row_id: &str, patch: Map) -> Change { Change { kind: OpKind::Upsert, table: table.to_string(), row_id: row_id.to_string(), patch: Some(patch) } } pub fn retract(table: &str, row_id: &str) -> Change { Change { kind: OpKind::Delete, table: table.to_string(), row_id: row_id.to_string(), patch: None } } } impl Serialize for Change { fn serialize(&self, serializer: S) -> Result { let mut map = serializer.serialize_map(Some(3))?; map.serialize_entry("table", &self.table)?; map.serialize_entry("id", &self.row_id)?; match self.kind { OpKind::Upsert => map.serialize_entry("patch", &self.patch.clone().unwrap_or_default())?, OpKind::Delete => map.serialize_entry("retract", &true)?, } map.end() } } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn a_change_reads_as_the_worker_applies_it() { let mut patch = Map::new(); patch.insert("body".into(), json!("hi")); assert_eq!(serde_json::to_value(Change::upsert("message", "m1", patch)).unwrap(), json!({"table": "message", "id": "m1", "patch": {"body": "hi"}})); assert_eq!(serde_json::to_value(Change::retract("message_reaction", "r1")).unwrap(), json!({"table": "message_reaction", "id": "r1", "retract": true})); } }