//! 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<Change>`, 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")]pubenumOpKind {Upsert,Delete,}implOpKind {/// The word the `kind` column and the wire both use.pubfn as_str(self) -> &'static str {matchself {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)]pubstructChange {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<Map<String, Value>>,}implChange {pubfn upsert(table: &str, row_id: &str, patch: Map<String, Value>) -> Change {Change { kind: OpKind::Upsert, table: table.to_string(), row_id: row_id.to_string(), patch: Some(patch) } }pubfn retract(table: &str, row_id: &str) -> Change {Change { kind: OpKind::Delete, table: table.to_string(), row_id: row_id.to_string(), patch: None } }}implSerializeforChange {fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {letmut map = serializer.serialize_map(Some(3))?; map.serialize_entry("table", &self.table)?; map.serialize_entry("id", &self.row_id)?;matchself.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 {usesuper::*;use serde_json::json; #[test]fn a_change_reads_as_the_worker_applies_it() {letmut 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})); }}