Skip to main content

zero_client/protocol/
mutation.rs

1//! Mutations, pushes, and their results (`packages/zero-protocol/src/mutation.ts`,
2//! `push.ts`, and `mutations-patch.ts`).
3
4use super::error::enum_value;
5use super::*;
6use crate::ast::string_enum;
7
8/// The name of every CRUD mutation (`CRUD_MUTATION_NAME`).
9pub const CRUD_MUTATION_NAME: &str = "_zero_crud";
10
11string_enum!(CrudOpKind { Insert = "insert", Upsert = "upsert", Update = "update", Delete = "delete" });
12
13/// One operation of a CRUD mutation (`crudOpSchema`). An update's `value` is
14/// a partial row with at least the primary key columns; a delete's holds the
15/// primary key columns, each a string, number, or boolean.
16#[derive(Clone, Debug, PartialEq)]
17pub struct CrudOp {
18    pub op: CrudOpKind,
19    pub table_name: String,
20    pub primary_key: Vec<String>,
21    pub value: RowRecord,
22}
23
24impl JsonCodable for CrudOp {
25    fn from_json(v: &Value) -> Result<Self> {
26        let r = Reader::new(v, "CRUD op")?;
27        let name = r.string("op")?;
28        let op = CrudOpKind::parse(&name)
29            .ok_or_else(|| DecodeError::new(format!("Invalid CRUD op \"{name}\"")).at("op"))?;
30        Ok(CrudOp {
31            op,
32            table_name: r.string("tableName")?,
33            primary_key: r.required("primaryKey", decode::compound_key)?,
34            value: if op == CrudOpKind::Delete {
35                r.required("value", primary_key_value_record)?
36            } else {
37                r.required("value", decode::object)?
38            },
39        })
40    }
41
42    fn to_json(&self) -> Value {
43        Builder::new()
44            .set("op", self.op.as_str())
45            .set("tableName", self.table_name.clone())
46            .set("primaryKey", decode::strings_json(&self.primary_key))
47            .set("value", self.value.clone())
48            .build()
49    }
50}
51
52/// A mutation as pushed to zero-cache (`mutationSchema`).
53#[derive(Clone, Debug, PartialEq)]
54pub enum Mutation {
55    /// The legacy CRUD mutators (`crudMutationSchema`). Its name is always
56    /// [`CRUD_MUTATION_NAME`] and its args are `[{ops}]`.
57    Crud {
58        id: f64,
59        client_id: String,
60        ops: Vec<CrudOp>,
61        timestamp: f64,
62    },
63    /// A custom mutator (`customMutationSchema`).
64    Custom {
65        id: f64,
66        client_id: String,
67        name: String,
68        args: Vec<Value>,
69        timestamp: f64,
70    },
71}
72
73impl JsonCodable for Mutation {
74    fn from_json(v: &Value) -> Result<Self> {
75        let r = Reader::new(v, "mutation")?;
76        match r.required("type", |v| enum_value!(MutationType, v))? {
77            MutationType::Crud => {
78                r.literal("name", CRUD_MUTATION_NAME)?;
79                let ops = r.required("args", |v| {
80                    let args = decode::array_value(v)?;
81                    if args.len() != 1 {
82                        return Err(DecodeError::new(format!(
83                            "Expected array of length 1, got {}",
84                            args.len()
85                        )));
86                    }
87                    Reader::new(&args[0], "CRUD arg")
88                        .and_then(|arg| {
89                            arg.required("ops", |v| decode::array(v, CrudOp::from_json))
90                        })
91                        .map_err(|e| e.at("0"))
92                })?;
93                Ok(Mutation::Crud {
94                    id: r.number("id")?,
95                    client_id: r.string("clientID")?,
96                    ops,
97                    timestamp: r.number("timestamp")?,
98                })
99            }
100            MutationType::Custom => Ok(Mutation::Custom {
101                id: r.number("id")?,
102                client_id: r.string("clientID")?,
103                name: r.string("name")?,
104                args: r.required("args", |v| Ok(decode::array_value(v)?.clone()))?,
105                timestamp: r.number("timestamp")?,
106            }),
107        }
108    }
109
110    fn to_json(&self) -> Value {
111        match self {
112            Mutation::Crud {
113                id,
114                client_id,
115                ops,
116                timestamp,
117            } => Builder::new()
118                .set("type", "crud")
119                .set("id", *id)
120                .set("clientID", client_id.clone())
121                .set("name", CRUD_MUTATION_NAME)
122                .set(
123                    "args",
124                    Value::Array(vec![Builder::new().set("ops", array_json(ops)).build()]),
125                )
126                .set("timestamp", *timestamp),
127            Mutation::Custom {
128                id,
129                client_id,
130                name,
131                args,
132                timestamp,
133            } => Builder::new()
134                .set("type", "custom")
135                .set("id", *id)
136                .set("clientID", client_id.clone())
137                .set("name", name.clone())
138                .set("args", args.clone())
139                .set("timestamp", *timestamp),
140        }
141        .build()
142    }
143}
144
145/// A failed mutation's result (`mutationErrorSchema`), kept as sent: see
146/// [`MutationResult`] for which results are errors.
147#[derive(Clone, Debug, PartialEq)]
148pub struct MutationError {
149    /// `"app"` for an error the mutator threw; `"oooMutation"` or
150    /// `"alreadyProcessed"` for one from zero.
151    pub error: Value,
152    pub message: Option<Value>,
153    pub details: Option<Value>,
154}
155
156/// The result of running a mutation on the API server
157/// (`mutationResultSchema`), read as the JS client reads it: in
158/// `passthrough` mode, telling errors apart with `'error' in result`. The
159/// union's OK branch, `{data?}`, accepts every object, so a result with
160/// `data` is OK even if it has an `error`, and any other result with an
161/// `error`, whatever its value, is an error.
162#[derive(Clone, Debug, PartialEq)]
163pub enum MutationResult {
164    Ok { data: Option<Value> },
165    Error(MutationError),
166}
167
168impl JsonCodable for MutationResult {
169    fn from_json(v: &Value) -> Result<Self> {
170        let r = Reader::new(v, "mutation result")?;
171        Ok(if let Some(data) = r.get("data") {
172            MutationResult::Ok {
173                data: Some(data.clone()),
174            }
175        } else if let Some(error) = r.get("error") {
176            MutationResult::Error(MutationError {
177                error: error.clone(),
178                message: r.get("message").cloned(),
179                details: r.get("details").cloned(),
180            })
181        } else {
182            MutationResult::Ok { data: None }
183        })
184    }
185
186    fn to_json(&self) -> Value {
187        match self {
188            MutationResult::Ok { data } => Builder::new().opt("data", data.clone()),
189            MutationResult::Error(e) => Builder::new()
190                .set("error", e.error.clone())
191                .opt("message", e.message.clone())
192                .opt("details", e.details.clone()),
193        }
194        .build()
195    }
196}
197
198/// `mutationResponseSchema`.
199#[derive(Clone, Debug, PartialEq)]
200pub struct MutationResponse {
201    pub id: MutationId,
202    pub result: MutationResult,
203}
204
205impl JsonCodable for MutationResponse {
206    fn from_json(v: &Value) -> Result<Self> {
207        let r = Reader::new(v, "mutation response")?;
208        Ok(MutationResponse {
209            id: r.required("id", MutationId::from_json)?,
210            result: r.required("result", MutationResult::from_json)?,
211        })
212    }
213
214    fn to_json(&self) -> Value {
215        Builder::new()
216            .set("id", self.id.to_json())
217            .set("result", self.result.to_json())
218            .build()
219    }
220}
221
222/// A change to the mutation results zero-cache tracks for a client
223/// (`mutations-patch.ts`).
224#[derive(Clone, Debug, PartialEq)]
225pub enum MutationPatchOp {
226    Put(Box<MutationResponse>),
227    Del(MutationId),
228}
229
230impl JsonCodable for MutationPatchOp {
231    fn from_json(v: &Value) -> Result<Self> {
232        let r = Reader::new(v, "mutations patch op")?;
233        match r.string("op")?.as_str() {
234            "put" => Ok(MutationPatchOp::Put(Box::new(
235                r.required("mutation", MutationResponse::from_json)?,
236            ))),
237            "del" => Ok(MutationPatchOp::Del(
238                r.required("id", MutationId::from_json)?,
239            )),
240            op => Err(DecodeError::new(format!("Invalid mutations patch op \"{op}\"")).at("op")),
241        }
242    }
243
244    fn to_json(&self) -> Value {
245        match self {
246            MutationPatchOp::Put(m) => Builder::new().set("op", "put").set("mutation", m.to_json()),
247            MutationPatchOp::Del(id) => Builder::new().set("op", "del").set("id", id.to_json()),
248        }
249        .build()
250    }
251}
252
253/// The body of a `push` message (`pushBodySchema`).
254#[derive(Clone, Debug, PartialEq)]
255pub struct PushBody {
256    pub client_group_id: String,
257    pub mutations: Vec<Mutation>,
258    pub push_version: f64,
259    /// The schema version of CRUD mutations.
260    pub schema_version: Option<f64>,
261    pub timestamp: f64,
262    pub request_id: String,
263    /// Deprecated: auth is set by `initConnection` and `updateAuth`.
264    pub auth: Option<String>,
265    pub traceparent: Option<String>,
266}
267
268impl JsonCodable for PushBody {
269    fn from_json(v: &Value) -> Result<Self> {
270        let r = Reader::new(v, "push body")?;
271        Ok(PushBody {
272            client_group_id: r.string("clientGroupID")?,
273            mutations: r.required("mutations", |v| decode::array(v, Mutation::from_json))?,
274            push_version: r.number("pushVersion")?,
275            schema_version: r.optional_number("schemaVersion")?,
276            timestamp: r.number("timestamp")?,
277            request_id: r.string("requestID")?,
278            auth: r.optional_string("auth")?,
279            traceparent: r.optional_string("traceparent")?,
280        })
281    }
282
283    fn to_json(&self) -> Value {
284        Builder::new()
285            .set("clientGroupID", self.client_group_id.clone())
286            .set("mutations", array_json(&self.mutations))
287            .set("pushVersion", self.push_version)
288            .opt("schemaVersion", self.schema_version)
289            .set("timestamp", self.timestamp)
290            .set("requestID", self.request_id.clone())
291            .opt("auth", self.auth.clone())
292            .opt("traceparent", self.traceparent.clone())
293            .build()
294    }
295}
296
297/// The deprecated error responses to a push (`pushErrorSchema`). zero-cache
298/// now reports push failures with `error` messages.
299#[derive(Clone, Debug, PartialEq)]
300pub enum PushError {
301    UnsupportedPushVersion {
302        mutation_ids: Option<Vec<MutationId>>,
303    },
304    UnsupportedSchemaVersion {
305        mutation_ids: Option<Vec<MutationId>>,
306    },
307    Http {
308        status: f64,
309        details: String,
310        mutation_ids: Option<Vec<MutationId>>,
311    },
312    ZeroPusher {
313        details: String,
314        mutation_ids: Option<Vec<MutationId>>,
315    },
316}
317
318impl PushError {
319    pub fn mutation_ids(&self) -> Option<&[MutationId]> {
320        match self {
321            PushError::UnsupportedPushVersion { mutation_ids }
322            | PushError::UnsupportedSchemaVersion { mutation_ids }
323            | PushError::Http { mutation_ids, .. }
324            | PushError::ZeroPusher { mutation_ids, .. } => mutation_ids.as_deref(),
325        }
326    }
327}
328
329impl JsonCodable for PushError {
330    fn from_json(v: &Value) -> Result<Self> {
331        let r = Reader::new(v, "push error")?;
332        let error = r.string("error")?;
333        let ids = || r.optional("mutationIDs", |v| decode::array(v, MutationId::from_json));
334        match error.as_str() {
335            "unsupportedPushVersion" => Ok(PushError::UnsupportedPushVersion {
336                mutation_ids: ids()?,
337            }),
338            "unsupportedSchemaVersion" => Ok(PushError::UnsupportedSchemaVersion {
339                mutation_ids: ids()?,
340            }),
341            "http" => Ok(PushError::Http {
342                status: r.number("status")?,
343                details: r.string("details")?,
344                mutation_ids: ids()?,
345            }),
346            "zeroPusher" => Ok(PushError::ZeroPusher {
347                details: r.string("details")?,
348                mutation_ids: ids()?,
349            }),
350            _ => Err(DecodeError::new(format!("Invalid push error \"{error}\"")).at("error")),
351        }
352    }
353
354    fn to_json(&self) -> Value {
355        let b = match self {
356            PushError::UnsupportedPushVersion { .. } => {
357                Builder::new().set("error", "unsupportedPushVersion")
358            }
359            PushError::UnsupportedSchemaVersion { .. } => {
360                Builder::new().set("error", "unsupportedSchemaVersion")
361            }
362            PushError::Http {
363                status, details, ..
364            } => Builder::new()
365                .set("error", "http")
366                .set("status", *status)
367                .set("details", details.clone()),
368            PushError::ZeroPusher { details, .. } => Builder::new()
369                .set("error", "zeroPusher")
370                .set("details", details.clone()),
371        };
372        b.opt("mutationIDs", self.mutation_ids().map(array_json))
373            .build()
374    }
375}
376
377/// The body of a `pushResponse` message (`pushResponseBodySchema`). valita
378/// tries the OK variant first, and it has no discriminator: a body with a
379/// valid `mutations` array is OK even if it also has an `error` key.
380#[derive(Clone, Debug, PartialEq)]
381pub enum PushResponseBody {
382    Ok { mutations: Vec<MutationResponse> },
383    Error(PushError),
384}
385
386impl JsonCodable for PushResponseBody {
387    fn from_json(v: &Value) -> Result<Self> {
388        let r = Reader::new(v, "pushResponse body")?;
389        match r.required("mutations", |v| {
390            decode::array(v, MutationResponse::from_json)
391        }) {
392            Ok(mutations) => Ok(PushResponseBody::Ok { mutations }),
393            Err(_) => Ok(PushResponseBody::Error(PushError::from_json(v)?)),
394        }
395    }
396
397    fn to_json(&self) -> Value {
398        match self {
399            PushResponseBody::Ok { mutations } => Builder::new()
400                .set("mutations", array_json(mutations))
401                .build(),
402            PushResponseBody::Error(e) => e.to_json(),
403        }
404    }
405}