Skip to main content

zero_client/protocol/
error.rs

1//! The body of an `error` message (`errorBodySchema` in
2//! `packages/zero-protocol/src/error.ts`) and its enums.
3
4use super::*;
5use crate::ast::string_enum;
6
7string_enum!(
8    /// The kind of a protocol error (`error-kind-enum.ts`), in the order of
9    /// `errorKindSchema`, which valita's messages list.
10    ErrorKind {
11        AuthInvalidated = "AuthInvalidated",
12        ClientNotFound = "ClientNotFound",
13        InvalidConnectionRequest = "InvalidConnectionRequest",
14        InvalidConnectionRequestBaseCookie = "InvalidConnectionRequestBaseCookie",
15        InvalidConnectionRequestLastMutationID = "InvalidConnectionRequestLastMutationID",
16        InvalidConnectionRequestClientDeleted = "InvalidConnectionRequestClientDeleted",
17        InvalidMessage = "InvalidMessage",
18        InvalidPush = "InvalidPush",
19        MutationRateLimited = "MutationRateLimited",
20        MutationFailed = "MutationFailed",
21        Unauthorized = "Unauthorized",
22        VersionNotSupported = "VersionNotSupported",
23        SchemaVersionNotSupported = "SchemaVersionNotSupported",
24        Internal = "Internal",
25        Rebalance = "Rebalance",
26        Rehome = "Rehome",
27        ServerOverloaded = "ServerOverloaded",
28        PushFailed = "PushFailed",
29        TransformFailed = "TransformFailed",
30    }
31);
32
33impl ErrorKind {
34    /// The kinds whose body carries backoff parameters
35    /// (`backoffErrorKindSchema`).
36    pub fn is_backoff(self) -> bool {
37        matches!(
38            self,
39            ErrorKind::Rebalance | ErrorKind::Rehome | ErrorKind::ServerOverloaded
40        )
41    }
42
43    /// The kinds of a basic error body (`basicErrorKindSchema`).
44    pub fn is_basic(self) -> bool {
45        !self.is_backoff() && !matches!(self, ErrorKind::PushFailed | ErrorKind::TransformFailed)
46    }
47}
48
49string_enum!(
50    /// Where an error came from (`error-origin-enum.ts`).
51    ErrorOrigin { Client = "client", Server = "server", ZeroCache = "zeroCache" }
52);
53
54string_enum!(
55    /// Why a push or transform failed (`error-reason-enum.ts`).
56    ErrorReason {
57        Database = "database",
58        Parse = "parse",
59        OutOfOrderMutation = "oooMutation",
60        UnsupportedPushVersion = "unsupportedPushVersion",
61        Internal = "internal",
62        Http = "http",
63        Timeout = "timeout",
64    }
65);
66
67string_enum!(
68    /// `mutation-type-enum.ts`.
69    MutationType { Crud = "crud", Custom = "custom" }
70);
71
72/// Decodes one of a [`string_enum!`]'s values with valita's message.
73macro_rules! enum_value {
74    ($ty:ident, $v:expr) => {{
75        let names: Vec<&str> = $ty::ALL.iter().map(|k| k.as_str()).collect();
76        literal_union($v, &names).map(|n| $ty::parse(n).expect("listed"))
77    }};
78}
79pub(crate) use enum_value;
80
81/// An origin other than `client`.
82fn remote_origin(v: &Value) -> Result<ErrorOrigin> {
83    match enum_value!(ErrorOrigin, v)? {
84        ErrorOrigin::Client => Err(DecodeError::new("Unexpected origin \"client\"")),
85        o => Ok(o),
86    }
87}
88
89/// Why a push or transform failed: the `origin` and `reason` of
90/// `pushFailedBodySchema` and `transformFailedBodySchema`, whose three
91/// variants each allow different combinations.
92#[derive(Clone, Debug, PartialEq)]
93pub enum FailureCause {
94    /// `origin: 'server'`: the API server reported the failure.
95    Server { reason: ErrorReason },
96    /// `origin: 'zeroCache', reason: 'http'`: the API server answered with a
97    /// non-OK status.
98    Http {
99        status: f64,
100        body_preview: Option<String>,
101    },
102    /// `origin: 'zeroCache'` with reason `timeout`, `parse`, or `internal`.
103    ZeroCache { reason: ErrorReason },
104}
105
106impl FailureCause {
107    pub fn origin(&self) -> ErrorOrigin {
108        match self {
109            FailureCause::Server { .. } => ErrorOrigin::Server,
110            _ => ErrorOrigin::ZeroCache,
111        }
112    }
113
114    pub fn reason(&self) -> ErrorReason {
115        match self {
116            FailureCause::Server { reason } | FailureCause::ZeroCache { reason } => *reason,
117            FailureCause::Http { .. } => ErrorReason::Http,
118        }
119    }
120
121    fn decode(r: &Reader<'_>, server_reasons: &[ErrorReason]) -> Result<Self> {
122        let one_of = |allowed: &[ErrorReason]| {
123            r.required("reason", |v| {
124                let reason = enum_value!(ErrorReason, v)?;
125                if allowed.contains(&reason) {
126                    Ok(reason)
127                } else {
128                    Err(DecodeError::new(format!("Unexpected value {v}")))
129                }
130            })
131        };
132        // valita tries the variants in order; at most one accepts.
133        if r.required("origin", remote_origin)? == ErrorOrigin::Server {
134            return Ok(FailureCause::Server {
135                reason: one_of(server_reasons)?,
136            });
137        }
138        if r.required("reason", |v| enum_value!(ErrorReason, v))? == ErrorReason::Http {
139            return Ok(FailureCause::Http {
140                status: r.number("status")?,
141                body_preview: r.optional_string("bodyPreview")?,
142            });
143        }
144        Ok(FailureCause::ZeroCache {
145            reason: one_of(&[
146                ErrorReason::Timeout,
147                ErrorReason::Parse,
148                ErrorReason::Internal,
149            ])?,
150        })
151    }
152
153    fn write(&self, b: Builder) -> Builder {
154        let b = b
155            .set("origin", self.origin().as_str())
156            .set("reason", self.reason().as_str());
157        match self {
158            FailureCause::Http {
159                status,
160                body_preview,
161            } => b
162                .set("status", *status)
163                .opt("bodyPreview", body_preview.clone()),
164            _ => b,
165        }
166    }
167}
168
169#[derive(Clone, Debug, PartialEq)]
170pub enum ErrorBody {
171    /// `basicErrorBodySchema`. `origin` is `server` or `zeroCache` when set.
172    Basic {
173        kind: ErrorKind,
174        message: String,
175        origin: Option<ErrorOrigin>,
176    },
177    /// `backoffBodySchema`: zero-cache asks the client to reconnect later.
178    Backoff {
179        kind: ErrorKind,
180        message: String,
181        min_backoff_ms: Option<f64>,
182        max_backoff_ms: Option<f64>,
183        /// Query parameters to send in the next reconnect only.
184        reconnect_params: Option<Vec<(String, String)>>,
185        origin: Option<ErrorOrigin>,
186    },
187    /// `pushFailedBodySchema`: `mutation_ids` may be a subset of the pushed
188    /// mutations.
189    PushFailed {
190        message: String,
191        mutation_ids: Vec<MutationId>,
192        details: Option<Value>,
193        cause: FailureCause,
194    },
195    /// `transformFailedBodySchema`.
196    TransformFailed {
197        message: String,
198        query_ids: Vec<String>,
199        details: Option<Value>,
200        cause: FailureCause,
201    },
202}
203
204const PUSH_SERVER_REASONS: &[ErrorReason] = &[
205    ErrorReason::Database,
206    ErrorReason::Parse,
207    ErrorReason::OutOfOrderMutation,
208    ErrorReason::UnsupportedPushVersion,
209    ErrorReason::Internal,
210];
211
212const TRANSFORM_SERVER_REASONS: &[ErrorReason] = &[
213    ErrorReason::Database,
214    ErrorReason::Parse,
215    ErrorReason::Internal,
216];
217
218impl ErrorBody {
219    pub fn kind(&self) -> ErrorKind {
220        match self {
221            ErrorBody::Basic { kind, .. } | ErrorBody::Backoff { kind, .. } => *kind,
222            ErrorBody::PushFailed { .. } => ErrorKind::PushFailed,
223            ErrorBody::TransformFailed { .. } => ErrorKind::TransformFailed,
224        }
225    }
226
227    pub fn message(&self) -> &str {
228        match self {
229            ErrorBody::Basic { message, .. }
230            | ErrorBody::Backoff { message, .. }
231            | ErrorBody::PushFailed { message, .. }
232            | ErrorBody::TransformFailed { message, .. } => message,
233        }
234    }
235
236    /// Where the error came from; `None` from servers too old to say.
237    pub fn origin(&self) -> Option<ErrorOrigin> {
238        match self {
239            ErrorBody::Basic { origin, .. } | ErrorBody::Backoff { origin, .. } => *origin,
240            ErrorBody::PushFailed { cause, .. } | ErrorBody::TransformFailed { cause, .. } => {
241                Some(cause.origin())
242            }
243        }
244    }
245}
246
247impl JsonCodable for ErrorBody {
248    fn from_json(v: &Value) -> Result<Self> {
249        let r = Reader::new(v, "error body")?;
250        let kind = r.required("kind", |v| enum_value!(ErrorKind, v))?;
251        if kind.is_basic() {
252            return Ok(ErrorBody::Basic {
253                kind,
254                message: r.string("message")?,
255                origin: r.optional("origin", remote_origin)?,
256            });
257        }
258        if kind.is_backoff() {
259            return Ok(ErrorBody::Backoff {
260                kind,
261                message: r.string("message")?,
262                min_backoff_ms: r.optional_number("minBackoffMs")?,
263                max_backoff_ms: r.optional_number("maxBackoffMs")?,
264                reconnect_params: r.optional("reconnectParams", string_record)?,
265                origin: r.optional("origin", |v| {
266                    literal(v, ErrorOrigin::ZeroCache.as_str()).map(|()| ErrorOrigin::ZeroCache)
267                })?,
268            });
269        }
270        if kind == ErrorKind::PushFailed {
271            return Ok(ErrorBody::PushFailed {
272                message: r.string("message")?,
273                mutation_ids: r
274                    .required("mutationIDs", |v| decode::array(v, MutationId::from_json))?,
275                details: r.get("details").cloned(),
276                cause: FailureCause::decode(&r, PUSH_SERVER_REASONS)?,
277            });
278        }
279        Ok(ErrorBody::TransformFailed {
280            message: r.string("message")?,
281            query_ids: r.required("queryIDs", decode::strings)?,
282            details: r.get("details").cloned(),
283            cause: FailureCause::decode(&r, TRANSFORM_SERVER_REASONS)?,
284        })
285    }
286
287    fn to_json(&self) -> Value {
288        let b = Builder::new()
289            .set("kind", self.kind().as_str())
290            .set("message", self.message());
291        match self {
292            ErrorBody::Basic { origin, .. } => b.opt("origin", origin.map(ErrorOrigin::as_str)),
293            ErrorBody::Backoff {
294                min_backoff_ms,
295                max_backoff_ms,
296                reconnect_params,
297                origin,
298                ..
299            } => b
300                .opt("minBackoffMs", *min_backoff_ms)
301                .opt("maxBackoffMs", *max_backoff_ms)
302                .opt(
303                    "reconnectParams",
304                    reconnect_params.as_deref().map(string_record_json),
305                )
306                .opt("origin", origin.map(ErrorOrigin::as_str)),
307            ErrorBody::PushFailed {
308                mutation_ids,
309                details,
310                cause,
311                ..
312            } => cause.write(
313                b.set("mutationIDs", array_json(mutation_ids))
314                    .opt("details", details.clone()),
315            ),
316            ErrorBody::TransformFailed {
317                query_ids,
318                details,
319                cause,
320                ..
321            } => cause.write(
322                b.set("queryIDs", decode::strings_json(query_ids))
323                    .opt("details", details.clone()),
324            ),
325        }
326        .build()
327    }
328}