Skip to main content

zero_client/protocol/
poke.rs

1//! Pokes (`packages/zero-protocol/src/poke.ts`), row patches
2//! (`row-patch.ts`), and binary poke chunks.
3
4use super::*;
5
6/// The range of schema versions the server supports.
7#[derive(Clone, Debug, PartialEq)]
8pub struct SchemaVersions {
9    pub min_supported_version: f64,
10    pub max_supported_version: f64,
11}
12
13/// Starts a poke (`pokeStartBodySchema`).
14#[derive(Clone, Debug, PartialEq)]
15pub struct PokeStartBody {
16    pub poke_id: String,
17    /// The cookie the poke applies to; `None` for a client that has never
18    /// pulled.
19    pub base_cookie: Option<Version>,
20    /// Always set when the poke has a `rowsPatch`.
21    pub schema_versions: Option<SchemaVersions>,
22    pub timestamp: Option<f64>,
23}
24
25impl JsonCodable for PokeStartBody {
26    fn from_json(v: &Value) -> Result<Self> {
27        let r = Reader::new(v, "pokeStart body")?;
28        Ok(PokeStartBody {
29            poke_id: r.string("pokeID")?,
30            base_cookie: r.required("baseCookie", nullable_version)?,
31            schema_versions: r.optional("schemaVersions", |v| {
32                let s = Reader::new(v, "schema versions")?;
33                Ok(SchemaVersions {
34                    min_supported_version: s.number("minSupportedVersion")?,
35                    max_supported_version: s.number("maxSupportedVersion")?,
36                })
37            })?,
38            timestamp: r.optional_number("timestamp")?,
39        })
40    }
41
42    fn to_json(&self) -> Value {
43        Builder::new()
44            .set("pokeID", self.poke_id.clone())
45            .set("baseCookie", nullable_version_json(&self.base_cookie))
46            .opt(
47                "schemaVersions",
48                self.schema_versions.as_ref().map(|s| {
49                    Builder::new()
50                        .set("minSupportedVersion", s.min_supported_version)
51                        .set("maxSupportedVersion", s.max_supported_version)
52                        .build()
53                }),
54            )
55            .opt("timestamp", self.timestamp)
56            .build()
57    }
58}
59
60/// A change to the synced rows (`rowPatchOpSchema`).
61#[derive(Clone, Debug, PartialEq)]
62pub enum RowPatchOp {
63    /// Inserts or replaces the row.
64    Put {
65        table_name: String,
66        value: RowRecord,
67    },
68    /// Merges `merge` into the row with primary key `id`. `merge` is a
69    /// `jsonObjectSchema`, which admits an array as well as an object; it is
70    /// kept as sent. `constrain` limits the columns the row keeps.
71    Update {
72        table_name: String,
73        id: PrimaryKeyValueRecord,
74        merge: Option<Value>,
75        constrain: Option<Vec<String>>,
76    },
77    /// Deletes the row with primary key `id`.
78    Del {
79        table_name: String,
80        id: PrimaryKeyValueRecord,
81    },
82    /// Deletes every row.
83    Clear,
84}
85
86impl JsonCodable for RowPatchOp {
87    fn from_json(v: &Value) -> Result<Self> {
88        let r = Reader::new(v, "row patch op")?;
89        match r.string("op")?.as_str() {
90            "put" => Ok(RowPatchOp::Put {
91                table_name: r.string("tableName")?,
92                value: r.required("value", decode::object)?,
93            }),
94            "update" => Ok(RowPatchOp::Update {
95                table_name: r.string("tableName")?,
96                id: r.required("id", primary_key_value_record)?,
97                merge: r.optional("merge", json_object)?,
98                constrain: r.optional("constrain", decode::strings)?,
99            }),
100            "del" => Ok(RowPatchOp::Del {
101                table_name: r.string("tableName")?,
102                id: r.required("id", primary_key_value_record)?,
103            }),
104            "clear" => Ok(RowPatchOp::Clear),
105            op => Err(DecodeError::new(format!("Invalid row patch op \"{op}\"")).at("op")),
106        }
107    }
108
109    fn to_json(&self) -> Value {
110        match self {
111            RowPatchOp::Put { table_name, value } => Builder::new()
112                .set("op", "put")
113                .set("tableName", table_name.clone())
114                .set("value", value.clone()),
115            RowPatchOp::Update {
116                table_name,
117                id,
118                merge,
119                constrain,
120            } => Builder::new()
121                .set("op", "update")
122                .set("tableName", table_name.clone())
123                .set("id", id.clone())
124                .opt("merge", merge.clone())
125                .opt("constrain", constrain.as_deref().map(decode::strings_json)),
126            RowPatchOp::Del { table_name, id } => Builder::new()
127                .set("op", "del")
128                .set("tableName", table_name.clone())
129                .set("id", id.clone()),
130            RowPatchOp::Clear => Builder::new().set("op", "clear"),
131        }
132        .build()
133    }
134}
135
136/// One part of a poke (`pokePartBodySchema`).
137#[derive(Clone, Debug, PartialEq)]
138pub struct PokePartBody {
139    pub poke_id: String,
140    /// The new last mutation ID of each client that changed.
141    pub last_mutation_id_changes: Option<Vec<(String, f64)>>,
142    /// Changes to each client's desired queries, in the order the server
143    /// sent the clients: a `clear` for one client and a `put` for another
144    /// must apply in that order.
145    pub desired_queries_patches: Option<Vec<(String, QueriesPatch)>>,
146    /// Changes to the queries whose rows `rows_patch` syncs.
147    pub got_queries_patch: Option<QueriesPatch>,
148    pub rows_patch: Option<Vec<RowPatchOp>>,
149    pub mutations_patch: Option<Vec<MutationPatchOp>>,
150}
151
152impl JsonCodable for PokePartBody {
153    fn from_json(v: &Value) -> Result<Self> {
154        let r = Reader::new(v, "pokePart body")?;
155        Ok(PokePartBody {
156            last_mutation_id_changes: r.optional("lastMutationIDChanges", number_record)?,
157            desired_queries_patches: r.optional("desiredQueriesPatches", |v| {
158                decode::record(v, queries_patch)
159            })?,
160            got_queries_patch: r.optional("gotQueriesPatch", queries_patch)?,
161            rows_patch: r.optional("rowsPatch", |v| decode::array(v, RowPatchOp::from_json))?,
162            mutations_patch: r.optional("mutationsPatch", |v| {
163                decode::array(v, MutationPatchOp::from_json)
164            })?,
165            poke_id: r.string("pokeID")?,
166        })
167    }
168
169    fn to_json(&self) -> Value {
170        Builder::new()
171            .opt(
172                "lastMutationIDChanges",
173                self.last_mutation_id_changes
174                    .as_deref()
175                    .map(number_record_json),
176            )
177            .opt(
178                "desiredQueriesPatches",
179                self.desired_queries_patches.as_ref().map(|p| {
180                    Value::Object(p.iter().map(|(k, q)| (k.clone(), array_json(q))).collect())
181                }),
182            )
183            .opt(
184                "gotQueriesPatch",
185                self.got_queries_patch.as_deref().map(array_json),
186            )
187            .opt("rowsPatch", self.rows_patch.as_deref().map(array_json))
188            .opt(
189                "mutationsPatch",
190                self.mutations_patch.as_deref().map(array_json),
191            )
192            .set("pokeID", self.poke_id.clone())
193            .build()
194    }
195}
196
197/// Ends a poke (`pokeEndBodySchema`).
198#[derive(Clone, Debug, PartialEq)]
199pub struct PokeEndBody {
200    pub poke_id: String,
201    /// The cookie after the poke. Ignore it, and it may be empty, if
202    /// `cancel` is set.
203    pub cookie: Version,
204    /// Discard the poke without applying it.
205    pub cancel: Option<bool>,
206}
207
208impl JsonCodable for PokeEndBody {
209    fn from_json(v: &Value) -> Result<Self> {
210        let r = Reader::new(v, "pokeEnd body")?;
211        Ok(PokeEndBody {
212            poke_id: r.string("pokeID")?,
213            cookie: r.string("cookie")?,
214            cancel: r.optional_bool("cancel")?,
215        })
216    }
217
218    fn to_json(&self) -> Value {
219        Builder::new()
220            .set("pokeID", self.poke_id.clone())
221            .set("cookie", self.cookie.clone())
222            .opt("cancel", self.cancel)
223            .build()
224    }
225}
226
227/// The binary poke chunks of protocol 52 and later. Between `pokeStart` and
228/// `pokeEnd` zero-cache may send a poke's parts as binary messages instead of
229/// `pokePart` messages: each is a [`MESSAGE_TYPE`](poke_chunk::MESSAGE_TYPE)
230/// byte and then the next bytes of the UTF-8 JSON of a `PokePartBody[]`. A
231/// chunk can end inside a UTF-8 sequence.
232pub mod poke_chunk {
233    use super::*;
234
235    /// `POKE_CHUNK_MESSAGE_TYPE`.
236    pub const MESSAGE_TYPE: u8 = 0x00;
237    /// `POKE_CHUNK_PROTOCOL_VERSION`.
238    pub const PROTOCOL_VERSION: u32 = 52;
239
240    /// The payload of a binary message. Fails for a message of another
241    /// type, which the client treats as an invalid message.
242    pub fn payload(message: &[u8]) -> Result<&[u8]> {
243        match message.split_first() {
244            None => Err(DecodeError::new("Unknown binary message type: undefined")),
245            Some((&MESSAGE_TYPE, rest)) => Ok(rest),
246            Some((t, _)) => Err(DecodeError::new(format!(
247                "Unknown binary message type: {t}"
248            ))),
249        }
250    }
251
252    /// Decodes the payloads of a poke's chunks, in order, into its parts
253    /// (`decodePokeChunks`): strict UTF-8, a leading BOM dropped as
254    /// `TextDecoder` does, then `pokePartsSchema`.
255    pub fn decode<'a>(chunks: impl IntoIterator<Item = &'a [u8]>) -> Result<Vec<PokePartBody>> {
256        let bytes: Vec<u8> = chunks.into_iter().flatten().copied().collect();
257        let payload = bytes
258            .strip_prefix(&[0xEF, 0xBB, 0xBF][..])
259            .unwrap_or(&bytes);
260        let text = std::str::from_utf8(payload)
261            .map_err(|_| DecodeError::new("The encoded data was not valid for encoding utf-8"))?;
262        decode::array(&parse_message(text)?, PokePartBody::from_json)
263    }
264}