Skip to main content

zero_client/protocol/
up.rs

1//! Messages from the client to zero-cache (`upstreamSchema` in
2//! `packages/zero-protocol/src/up.ts`).
3
4use super::*;
5
6#[derive(Clone, Debug, PartialEq)]
7pub enum Upstream {
8    InitConnection(InitConnectionBody),
9    Ping,
10    DeleteClients(DeleteClientsBody),
11    ChangeDesiredQueries(ChangeDesiredQueriesBody),
12    Pull(PullRequestBody),
13    UpdateAuth(UpdateAuthBody),
14    Push(PushBody),
15    /// Sent before the client closes the socket. The body is any array.
16    CloseConnection(Vec<Value>),
17    Inspect(InspectUpBody),
18    /// Tells zero-cache the client has seen the mutation results up to the
19    /// given ID, so it can delete them.
20    AckMutationResponses(MutationId),
21    /// A message whose string tag this build doesn't know, kept as sent.
22    /// `upstreamSchema` is an open `taggedTupleUnion`, so a newer client's
23    /// messages parse.
24    Unrecognized(Vec<Value>),
25}
26
27impl Upstream {
28    pub fn tag(&self) -> &str {
29        match self {
30            Upstream::InitConnection(_) => "initConnection",
31            Upstream::Ping => "ping",
32            Upstream::DeleteClients(_) => "deleteClients",
33            Upstream::ChangeDesiredQueries(_) => "changeDesiredQueries",
34            Upstream::Pull(_) => "pull",
35            Upstream::UpdateAuth(_) => "updateAuth",
36            Upstream::Push(_) => "push",
37            Upstream::CloseConnection(_) => "closeConnection",
38            Upstream::Inspect(_) => "inspect",
39            Upstream::AckMutationResponses(_) => "ackMutationResponses",
40            Upstream::Unrecognized(a) => a.first().and_then(Value::as_str).unwrap_or(""),
41        }
42    }
43
44    /// Parses message text, as zero-cache receives it.
45    pub fn from_text(text: &str) -> Result<Self> {
46        Self::from_json(&parse_message(text)?)
47    }
48
49    /// The message text to send.
50    pub fn to_text(&self) -> String {
51        json::stringify(&self.to_json())
52    }
53}
54
55impl JsonCodable for Upstream {
56    fn from_json(v: &Value) -> Result<Self> {
57        let Value::Array(a) = v else {
58            return Err(DecodeError::new("Expected array"));
59        };
60        let Some(Value::String(tag)) = a.first() else {
61            return Err(DecodeError::new("Expected string").at("0"));
62        };
63        // A known tag picks its tuple, which must have exactly two elements.
64        fn body<'a, T>(
65            v: &'a Value,
66            tag: &str,
67            decode: impl FnOnce(&'a Value) -> Result<T>,
68        ) -> Result<T> {
69            decode(body_of(v, tag)?).map_err(|e| e.at("1"))
70        }
71        Ok(match tag.as_str() {
72            "initConnection" => {
73                Upstream::InitConnection(body(v, tag, InitConnectionBody::from_json)?)
74            }
75            "ping" => {
76                body(v, tag, decode::object)?;
77                Upstream::Ping
78            }
79            "deleteClients" => Upstream::DeleteClients(body(v, tag, DeleteClientsBody::from_json)?),
80            "changeDesiredQueries" => {
81                Upstream::ChangeDesiredQueries(body(v, tag, ChangeDesiredQueriesBody::from_json)?)
82            }
83            "pull" => Upstream::Pull(body(v, tag, PullRequestBody::from_json)?),
84            "updateAuth" => Upstream::UpdateAuth(body(v, tag, UpdateAuthBody::from_json)?),
85            "push" => Upstream::Push(body(v, tag, PushBody::from_json)?),
86            "closeConnection" => {
87                Upstream::CloseConnection(body(v, tag, |b| Ok(decode::array_value(b)?.clone()))?)
88            }
89            "inspect" => Upstream::Inspect(body(v, tag, InspectUpBody::from_json)?),
90            "ackMutationResponses" => {
91                Upstream::AckMutationResponses(body(v, tag, MutationId::from_json)?)
92            }
93            _ => Upstream::Unrecognized(a.clone()),
94        })
95    }
96
97    fn to_json(&self) -> Value {
98        let body = match self {
99            Upstream::InitConnection(b) => b.to_json(),
100            Upstream::Ping => Value::Object(Object::new()),
101            Upstream::DeleteClients(b) => b.to_json(),
102            Upstream::ChangeDesiredQueries(b) => b.to_json(),
103            Upstream::Pull(b) => b.to_json(),
104            Upstream::UpdateAuth(b) => b.to_json(),
105            Upstream::Push(b) => b.to_json(),
106            Upstream::CloseConnection(b) => Value::Array(b.clone()),
107            Upstream::Inspect(b) => b.to_json(),
108            Upstream::AckMutationResponses(id) => id.to_json(),
109            Upstream::Unrecognized(a) => return Value::Array(a.clone()),
110        };
111        message(self.tag(), body)
112    }
113}