1use 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 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#[derive(Clone, Debug, PartialEq)]
34pub enum ConnectionError {
35 Client(ClientErrorKind, String),
37 Server(Box<ErrorBody>),
39}
40
41impl ConnectionError {
42 pub fn client(kind: ClientErrorKind, message: impl Into<String>) -> Self {
44 ConnectionError::Client(kind, message.into())
45 }
46
47 pub fn message(&self) -> &str {
49 match self {
50 ConnectionError::Client(_, m) => m,
51 ConnectionError::Server(body) => body.message(),
52 }
53 }
54
55 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 pub fn client_kind(&self) -> Option<ClientErrorKind> {
65 match self {
66 ConnectionError::Client(kind, _) => Some(*kind),
67 ConnectionError::Server(_) => None,
68 }
69 }
70
71 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 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 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub(crate) enum ConnectionTransition {
165 None,
167 NeedsAuth,
168 Error,
169 Disconnected,
170 Closed,
171}
172
173impl ConnectionTransition {
174 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#[derive(Clone, Debug, PartialEq)]
233pub struct ApplicationError {
234 pub message: String,
236 pub details: Option<Value>,
238}
239
240impl ApplicationError {
241 pub fn new(message: impl Into<String>) -> Self {
243 ApplicationError {
244 message: message.into(),
245 details: None,
246 }
247 }
248
249 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 pub(crate) fn wrapping(error: &Error) -> ApplicationError {
259 match error {
260 Error::Application(e) => e.clone(),
261 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#[derive(Clone, Debug)]
283pub struct QueryError {
284 pub error: Option<ErroredQuery>,
286 pub data: Option<ViewValue>,
288}
289
290impl QueryError {
291 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#[derive(Clone, Debug)]
313pub enum Error {
314 Application(ApplicationError),
316 Connection(ConnectionError),
318 Query(Box<QueryError>),
320 Pipeline(PipelineError),
322 InvalidPrimaryKey(InvalidPrimaryKeyValue),
324 Message(String),
326}
327
328impl Error {
329 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}