Skip to main content

zero_client/client/
error.rs

1//! The errors of the client: why a connection ended, an error a mutator or
2//! the API server raised, and a query the server could not run.
3
4use crate::ivm::{PipelineError, ViewValue};
5use crate::json::Value;
6use crate::keys::InvalidPrimaryKeyValue;
7use crate::protocol::{ErrorBody, ErrorKind, ErrorOrigin, ErroredQuery, FailureCause};
8use std::fmt;
9
10crate::ast::string_enum!(
11    /// The kinds of error the client raises itself
12    /// (`packages/zero-client/src/client/client-error-kind-enum.ts`).
13    ClientErrorKind {
14        AbruptClose = "AbruptClose",
15        CleanClose = "CleanClose",
16        ClientClosed = "ClientClosed",
17        ConnectTimeout = "ConnectTimeout",
18        Hidden = "Hidden",
19        Internal = "Internal",
20        InvalidMessage = "InvalidMessage",
21        NoSocketOrigin = "NoSocketOrigin",
22        Offline = "Offline",
23        PingTimeout = "PingTimeout",
24        PullTimeout = "PullTimeout",
25        UnexpectedBaseCookie = "UnexpectedBaseCookie",
26        UserDisconnect = "UserDisconnect",
27    }
28);
29
30/// Why a connection ended or could not be made: an error the client raised
31/// (`ClientError`) or one the server sent (`ProtocolError`), together
32/// `ZeroError` in `packages/zero-client/src/client/error.ts`.
33#[derive(Clone, Debug, PartialEq)]
34pub enum ConnectionError {
35    /// An error the client raised, of a kind, with its message.
36    Client(ClientErrorKind, String),
37    /// An error the server sent.
38    Server(Box<ErrorBody>),
39}
40
41impl ConnectionError {
42    /// An error the client raised.
43    pub fn client(kind: ClientErrorKind, message: impl Into<String>) -> Self {
44        ConnectionError::Client(kind, message.into())
45    }
46
47    /// The error's message.
48    pub fn message(&self) -> &str {
49        match self {
50            ConnectionError::Client(_, m) => m,
51            ConnectionError::Server(body) => body.message(),
52        }
53    }
54
55    /// The kind's name, a `ClientErrorKind` or an `ErrorKind`.
56    pub fn kind_name(&self) -> &'static str {
57        match self {
58            ConnectionError::Client(kind, _) => kind.as_str(),
59            ConnectionError::Server(body) => body.kind().as_str(),
60        }
61    }
62
63    /// The kind of an error the client raised.
64    pub fn client_kind(&self) -> Option<ClientErrorKind> {
65        match self {
66            ConnectionError::Client(kind, _) => Some(*kind),
67            ConnectionError::Server(_) => None,
68        }
69    }
70
71    /// The kind of an error the server sent.
72    pub fn server_kind(&self) -> Option<ErrorKind> {
73        match self {
74            ConnectionError::Server(body) => Some(body.kind()),
75            ConnectionError::Client(..) => None,
76        }
77    }
78
79    /// `isZeroError`: a client error, or a server error that says where it
80    /// came from. Older servers send errors without an origin.
81    pub fn is_zero_error(&self) -> bool {
82        match self {
83            ConnectionError::Client(..) => true,
84            ConnectionError::Server(body) => matches!(
85                body.origin(),
86                Some(ErrorOrigin::Server | ErrorOrigin::ZeroCache)
87            ),
88        }
89    }
90
91    /// `isAuthError`: the server rejected the credentials, or the API server
92    /// answered a push or transform with 401 or 403.
93    pub fn is_auth_error(&self) -> bool {
94        let ConnectionError::Server(body) = self else {
95            return false;
96        };
97        if !self.is_zero_error() {
98            return false;
99        }
100        match &**body {
101            ErrorBody::Basic { kind, .. } => {
102                matches!(kind, ErrorKind::AuthInvalidated | ErrorKind::Unauthorized)
103            }
104            ErrorBody::PushFailed { cause, .. } | ErrorBody::TransformFailed { cause, .. } => {
105                is_http_auth_failure(cause)
106            }
107            ErrorBody::Backoff { .. } => false,
108        }
109    }
110
111    /// `isTransportFailure`: the socket closed or never answered, rather
112    /// than the server replying. These carry no backoff instructions and
113    /// usually clear within seconds, so they are retried on the fast
114    /// schedule.
115    pub fn is_transport_failure(&self) -> bool {
116        matches!(
117            self.client_kind(),
118            Some(
119                ClientErrorKind::AbruptClose
120                    | ClientErrorKind::CleanClose
121                    | ClientErrorKind::ConnectTimeout
122                    | ClientErrorKind::PingTimeout
123            )
124        )
125    }
126
127    /// How a rejected mutation describes the client (`getStateDescription`).
128    pub fn state_description(&self) -> &'static str {
129        match self.client_kind() {
130            Some(ClientErrorKind::Offline) => "offline",
131            Some(ClientErrorKind::ClientClosed) => "closed",
132            _ => "in error state",
133        }
134    }
135
136    /// `getBackoffParams`.
137    pub fn backoff(&self) -> Option<&ErrorBody> {
138        match self {
139            ConnectionError::Server(body)
140                if matches!(**body, ErrorBody::Backoff { .. }) && self.is_zero_error() =>
141            {
142                Some(body)
143            }
144            _ => None,
145        }
146    }
147}
148
149impl fmt::Display for ConnectionError {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        write!(f, "{}: {}", self.kind_name(), self.message())
152    }
153}
154
155impl std::error::Error for ConnectionError {}
156
157fn is_http_auth_failure(cause: &FailureCause) -> bool {
158    matches!(cause, FailureCause::Http { status, .. } if *status == 401.0 || *status == 403.0)
159}
160
161/// What a connection error does to the connection status
162/// (`getErrorConnectionTransition`).
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub(crate) enum ConnectionTransition {
165    /// Keep the status and retry.
166    None,
167    NeedsAuth,
168    Error,
169    Disconnected,
170    Closed,
171}
172
173impl ConnectionTransition {
174    /// The transition and the reason to record. An error without an origin
175    /// is unexpected: it becomes an internal client error.
176    pub(crate) fn of(error: &ConnectionError) -> (ConnectionTransition, ConnectionError) {
177        if !error.is_zero_error() {
178            return (
179                ConnectionTransition::Error,
180                ConnectionError::client(
181                    ClientErrorKind::Internal,
182                    format!("Unexpected internal error: {}", error.message()),
183                ),
184            );
185        }
186        (ConnectionTransition::new(error), error.clone())
187    }
188
189    fn new(error: &ConnectionError) -> ConnectionTransition {
190        use ClientErrorKind as C;
191        use ErrorKind as S;
192        if error.is_auth_error() {
193            return ConnectionTransition::NeedsAuth;
194        }
195        match error {
196            ConnectionError::Client(kind, _) => match kind {
197                C::AbruptClose
198                | C::CleanClose
199                | C::ConnectTimeout
200                | C::PingTimeout
201                | C::PullTimeout
202                | C::UnexpectedBaseCookie => ConnectionTransition::None,
203                C::Internal | C::InvalidMessage | C::UserDisconnect => ConnectionTransition::Error,
204                C::Hidden | C::Offline | C::NoSocketOrigin => ConnectionTransition::Disconnected,
205                C::ClientClosed => ConnectionTransition::Closed,
206            },
207            ConnectionError::Server(body) => match body.kind() {
208                S::ClientNotFound
209                | S::InvalidConnectionRequest
210                | S::InvalidConnectionRequestBaseCookie
211                | S::InvalidConnectionRequestLastMutationID
212                | S::InvalidConnectionRequestClientDeleted
213                | S::InvalidMessage
214                | S::InvalidPush
215                | S::VersionNotSupported
216                | S::SchemaVersionNotSupported
217                | S::Internal
218                | S::PushFailed
219                | S::TransformFailed => ConnectionTransition::Error,
220                S::Rebalance | S::Rehome | S::ServerOverloaded => ConnectionTransition::None,
221                S::AuthInvalidated | S::Unauthorized => ConnectionTransition::NeedsAuth,
222                S::MutationRateLimited | S::MutationFailed => ConnectionTransition::None,
223            },
224        }
225    }
226}
227
228/// An error a mutator raised for the app to handle, or that the API server
229/// reported for a mutation (`ApplicationError` in
230/// `packages/zero-protocol/src/application-error.ts`). Return it from a
231/// mutator to give the caller a message and details.
232#[derive(Clone, Debug, PartialEq)]
233pub struct ApplicationError {
234    /// What the app shows.
235    pub message: String,
236    /// Anything else the app wants to pass along, as JSON.
237    pub details: Option<Value>,
238}
239
240impl ApplicationError {
241    /// An error with `message` and no details.
242    pub fn new(message: impl Into<String>) -> Self {
243        ApplicationError {
244            message: message.into(),
245            details: None,
246        }
247    }
248
249    /// With `details`; a null is no details (`details ?? undefined` in JS).
250    pub fn with_details(message: impl Into<String>, details: Option<Value>) -> Self {
251        ApplicationError {
252            message: message.into(),
253            details: details.filter(|d| !d.is_null()),
254        }
255    }
256
257    /// `wrapWithApplicationError`.
258    pub(crate) fn wrapping(error: &Error) -> ApplicationError {
259        match error {
260            Error::Application(e) => e.clone(),
261            // `getErrorDetails` gives an error of another class its name.
262            Error::InvalidPrimaryKey(e) => ApplicationError::with_details(
263                e.to_string(),
264                Some(Value::Object(
265                    [("name", Value::from("TypeError"))].into_iter().collect(),
266                )),
267            ),
268            e => ApplicationError::new(e.message()),
269        }
270    }
271}
272
273impl fmt::Display for ApplicationError {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.write_str(&self.message)
276    }
277}
278
279impl std::error::Error for ApplicationError {}
280
281/// A query the server could not run.
282#[derive(Clone, Debug)]
283pub struct QueryError {
284    /// Why the server could not run the query, if it said.
285    pub error: Option<ErroredQuery>,
286    /// What the view held when the query failed. JS rejects `run` with it.
287    pub data: Option<ViewValue>,
288}
289
290impl QueryError {
291    /// A query error with no view data.
292    pub fn new(error: Option<ErroredQuery>) -> Self {
293        QueryError { error, data: None }
294    }
295}
296
297impl fmt::Display for QueryError {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        match &self.error {
300            Some(ErroredQuery::App {
301                message: Some(m), ..
302            }) => f.write_str(m),
303            Some(ErroredQuery::Parse { message, .. }) => f.write_str(message),
304            _ => f.write_str("Query failed"),
305        }
306    }
307}
308
309impl std::error::Error for QueryError {}
310
311/// An error of the client's API.
312#[derive(Clone, Debug)]
313pub enum Error {
314    /// A mutator or the API server raised it for the app.
315    Application(ApplicationError),
316    /// The connection failed or the client is closed.
317    Connection(ConnectionError),
318    /// The server could not run a query.
319    Query(Box<QueryError>),
320    /// A query could not be built or failed while it ran.
321    Pipeline(PipelineError),
322    /// A row's primary key is not a string, number, or boolean.
323    InvalidPrimaryKey(InvalidPrimaryKeyValue),
324    /// Anything else, with its message.
325    Message(String),
326}
327
328impl Error {
329    /// The error's message.
330    pub fn message(&self) -> String {
331        match self {
332            Error::Application(e) => e.message.clone(),
333            Error::Connection(e) => e.message().to_owned(),
334            Error::Query(e) => e.to_string(),
335            Error::Pipeline(e) => e.to_string(),
336            Error::InvalidPrimaryKey(e) => e.to_string(),
337            Error::Message(m) => m.clone(),
338        }
339    }
340}
341
342impl fmt::Display for Error {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        match self {
345            Error::Connection(e) => e.fmt(f),
346            e => f.write_str(&e.message()),
347        }
348    }
349}
350
351impl std::error::Error for Error {}
352
353impl From<ApplicationError> for Error {
354    fn from(e: ApplicationError) -> Self {
355        Error::Application(e)
356    }
357}
358
359impl From<ConnectionError> for Error {
360    fn from(e: ConnectionError) -> Self {
361        Error::Connection(e)
362    }
363}
364
365impl From<QueryError> for Error {
366    fn from(e: QueryError) -> Self {
367        Error::Query(Box::new(e))
368    }
369}
370
371impl From<PipelineError> for Error {
372    fn from(e: PipelineError) -> Self {
373        Error::Pipeline(e)
374    }
375}
376
377impl From<InvalidPrimaryKeyValue> for Error {
378    fn from(e: InvalidPrimaryKeyValue) -> Self {
379        Error::InvalidPrimaryKey(e)
380    }
381}
382
383impl From<String> for Error {
384    fn from(m: String) -> Self {
385        Error::Message(m)
386    }
387}
388
389impl From<&str> for Error {
390    fn from(m: &str) -> Self {
391        Error::Message(m.to_owned())
392    }
393}