1use super::*;
5
6#[derive(Clone, Debug, PartialEq)]
8pub struct SchemaVersions {
9 pub min_supported_version: f64,
10 pub max_supported_version: f64,
11}
12
13#[derive(Clone, Debug, PartialEq)]
15pub struct PokeStartBody {
16 pub poke_id: String,
17 pub base_cookie: Option<Version>,
20 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#[derive(Clone, Debug, PartialEq)]
62pub enum RowPatchOp {
63 Put {
65 table_name: String,
66 value: RowRecord,
67 },
68 Update {
72 table_name: String,
73 id: PrimaryKeyValueRecord,
74 merge: Option<Value>,
75 constrain: Option<Vec<String>>,
76 },
77 Del {
79 table_name: String,
80 id: PrimaryKeyValueRecord,
81 },
82 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#[derive(Clone, Debug, PartialEq)]
138pub struct PokePartBody {
139 pub poke_id: String,
140 pub last_mutation_id_changes: Option<Vec<(String, f64)>>,
142 pub desired_queries_patches: Option<Vec<(String, QueriesPatch)>>,
146 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#[derive(Clone, Debug, PartialEq)]
199pub struct PokeEndBody {
200 pub poke_id: String,
201 pub cookie: Version,
204 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
227pub mod poke_chunk {
233 use super::*;
234
235 pub const MESSAGE_TYPE: u8 = 0x00;
237 pub const PROTOCOL_VERSION: u32 = 52;
239
240 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 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}