Skip to main content

zero_client/protocol/
mod.rs

1//! The zero-protocol wire messages (`packages/zero-protocol/src`), decoded
2//! as valita does in `passthrough` mode: unknown keys are accepted and
3//! dropped, and optional fields may be absent but not `null` unless they
4//! are nullable.
5
6mod client_schema;
7mod connect;
8mod down;
9mod error;
10mod inspect;
11mod mutation;
12mod poke;
13mod queries;
14mod up;
15pub mod valita;
16
17pub use client_schema::*;
18pub use connect::*;
19pub use down::*;
20pub use error::*;
21pub use inspect::*;
22pub use mutation::*;
23pub use poke::*;
24pub use queries::*;
25pub use up::*;
26
27use crate::decode::{self, Builder, DecodeError, JsonCodable, Reader, Result};
28use crate::json::{self, Object, Value};
29
30/// The sync protocol version this client speaks
31/// (`PROTOCOL_VERSION` in `packages/zero-protocol/src/protocol-version.ts`).
32pub const PROTOCOL_VERSION: u32 = 57;
33
34/// A cookie: the version of the client view a client has. Where the
35/// protocol allows a `NullableVersion`, `None` is the state before the first
36/// pull.
37pub type Version = String;
38
39/// The values of a row's primary key columns, by column. Each is a string,
40/// number, or boolean.
41pub type PrimaryKeyValueRecord = Object;
42
43/// A row as the protocol carries it (`rowSchema`): a record of JSON values.
44pub type RowRecord = Object;
45
46/// `packages/zero-protocol/src/mutation-id.ts`.
47#[derive(Clone, Debug, PartialEq)]
48pub struct MutationId {
49    pub id: f64,
50    pub client_id: String,
51}
52
53impl JsonCodable for MutationId {
54    fn from_json(v: &Value) -> Result<Self> {
55        let r = Reader::new(v, "mutation ID")?;
56        Ok(MutationId {
57            id: r.number("id")?,
58            client_id: r.string("clientID")?,
59        })
60    }
61
62    fn to_json(&self) -> Value {
63        Builder::new()
64            .set("id", self.id)
65            .set("clientID", self.client_id.clone())
66            .build()
67    }
68}
69
70/// `nullableVersionSchema`: a string or `null`.
71pub(crate) fn nullable_version(v: &Value) -> Result<Option<Version>> {
72    match v {
73        Value::Null => Ok(None),
74        Value::String(s) => Ok(Some(s.clone())),
75        v => Err(DecodeError::new(format!(
76            "Expected string or null, got {}",
77            v.type_name()
78        ))),
79    }
80}
81
82pub(crate) fn nullable_version_json(v: &Option<Version>) -> Value {
83    v.clone().map_or(Value::Null, Value::String)
84}
85
86/// `v.literal(expected)` for a string.
87pub(crate) fn literal(v: &Value, expected: &str) -> Result<()> {
88    match v {
89        Value::String(s) if s == expected => Ok(()),
90        v => Err(DecodeError::new(format!(
91            "Expected literal \"{expected}\", got {v}"
92        ))),
93    }
94}
95
96/// `v.literalUnion(...)`: one of `names`, with valita's message.
97pub(crate) fn literal_union<'a>(v: &Value, names: &[&'a str]) -> Result<&'a str> {
98    if let Value::String(s) = v
99        && let Some(name) = names.iter().find(|n| **n == s.as_str())
100    {
101        return Ok(name);
102    }
103    let quoted: Vec<String> = names
104        .iter()
105        .map(|n| json::stringify(&Value::from(*n)))
106        .collect();
107    let list = match quoted.split_last() {
108        Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
109        _ => quoted.concat(),
110    };
111    let mut e = DecodeError::new(format!("Expected literal value {list}"));
112    e.got = format!(" Got {}", crate::keys::valita_display(Some(v)));
113    Err(e)
114}
115
116/// `v.record(v.string())`, in the object's order.
117pub(crate) fn string_record(v: &Value) -> Result<Vec<(String, String)>> {
118    decode::record(v, decode::string)
119}
120
121/// `v.record(v.number())`, in the object's order.
122pub(crate) fn number_record(v: &Value) -> Result<Vec<(String, f64)>> {
123    decode::record(v, decode::number)
124}
125
126pub(crate) fn string_record_json(r: &[(String, String)]) -> Value {
127    Value::Object(
128        r.iter()
129            .map(|(k, v)| (k.clone(), Value::String(v.clone())))
130            .collect(),
131    )
132}
133
134pub(crate) fn number_record_json(r: &[(String, f64)]) -> Value {
135    Value::Object(
136        r.iter()
137            .map(|(k, v)| (k.clone(), Value::Number(*v)))
138            .collect(),
139    )
140}
141
142/// `primaryKeyValueRecordSchema`.
143pub(crate) fn primary_key_value_record(v: &Value) -> Result<Object> {
144    Ok(decode::record(v, decode::primary_key_value)?
145        .into_iter()
146        .collect())
147}
148
149/// `jsonObjectSchema` (`packages/shared/src/json-schema.ts`). It checks
150/// `typeof v === 'object'`, so it accepts arrays as well as objects.
151pub(crate) fn json_object(v: &Value) -> Result<Value> {
152    match v {
153        Value::Object(_) | Value::Array(_) => Ok(v.clone()),
154        _ => Err(DecodeError::new("Not a JSON object")),
155    }
156}
157
158/// The body of a `[tag, body]` tuple: exactly two elements, the first the
159/// literal `tag`.
160pub(crate) fn body_of<'a>(v: &'a Value, tag: &str) -> Result<&'a Value> {
161    let a = decode::array_value(v)?;
162    if a.len() != 2 {
163        return Err(DecodeError::new(format!(
164            "Expected array of length 2, got {}",
165            a.len()
166        )));
167    }
168    literal(&a[0], tag).map_err(|e| e.at("0"))?;
169    Ok(&a[1])
170}
171
172/// A `[tag, body]` message.
173pub(crate) fn message(tag: &str, body: Value) -> Value {
174    Value::Array(vec![Value::from(tag), body])
175}
176
177/// Parses the text of a WebSocket message.
178pub fn parse_message(text: &str) -> Result<Value> {
179    json::parse(text).map_err(|e| DecodeError::new(e.to_string()))
180}
181
182pub(crate) fn array_json<T: JsonCodable>(items: &[T]) -> Value {
183    Value::Array(items.iter().map(JsonCodable::to_json).collect())
184}