1use std::{collections::HashSet, error::Error as StdError, fmt};
21
22use itertools::Itertools;
23use tonic::{Code, Status};
24use tonic_types::StatusExt;
25
26use super::{address::Address, RequestID};
27
28macro_rules! error_messages {
29 {
30 $name:ident code: $code_pfx:literal, type: $message_pfx:literal,
31 $($error_name:ident $({ $($field:ident : $inner:ty),+ $(,)? })? = $code:literal: $body:literal),+ $(,)?
32 } => {
33 #[derive(Clone, Eq, PartialEq)]
34 pub enum $name {$(
35 $error_name$( { $($field: $inner),+ })?,
36 )*}
37
38 impl $name {
39 pub const PREFIX: &'static str = $code_pfx;
40
41 pub const fn code(&self) -> usize {
42 match self {$(
43 Self::$error_name $({ $($field: _),+ })? => $code,
44 )*}
45 }
46
47 pub fn format_code(&self) -> String {
48 format!(concat!("[", $code_pfx, "{}{}]"), self.padding(), self.code())
49 }
50
51 pub fn message(&self) -> String {
52 match self {$(
53 Self::$error_name $({$($field),+})? => format!($body $($(, $field = $field)+)?),
54 )*}
55 }
56
57 const fn max_code() -> usize {
58 let mut max = usize::MIN;
59 $(max = if $code > max { $code } else { max };)*
60 max
61 }
62
63 const fn num_digits(x: usize) -> usize {
64 if (x < 10) { 1 } else { 1 + Self::num_digits(x/10) }
65 }
66
67 const fn padding(&self) -> &'static str {
68 match Self::num_digits(Self::max_code()) - Self::num_digits(self.code()) {
69 0 => "",
70 1 => "0",
71 2 => "00",
72 3 => "000",
73 _ => unreachable!(),
74 }
75 }
76
77 const fn name(&self) -> &'static str {
78 match self {$(
79 Self::$error_name $({ $($field: _),+ })? => concat!(stringify!($name), "::", stringify!($error_name)),
80 )*}
81 }
82 }
83
84 impl std::fmt::Display for $name {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 write!(
87 f,
88 concat!("[", $code_pfx, "{}{}] ", $message_pfx, ": {}"),
89 self.padding(),
90 self.code(),
91 self.message()
92 )
93 }
94 }
95
96 impl std::fmt::Debug for $name {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let mut debug_struct = f.debug_struct(self.name());
99 debug_struct.field("message", &format!("{}", self));
100 $(
101 $(
102 if let Self::$error_name { $($field),+ } = &self {
103 $(debug_struct.field(stringify!($field), &$field);)+
104 }
105 )?
106 )*
107 debug_struct.finish()
108 }
109 }
110
111 impl std::error::Error for $name {
112 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
113 None
114 }
115 }
116 };
117}
118
119error_messages! { ConnectionError
120 code: "CXN", type: "Connection Error",
121 RPCMethodUnavailable { message: String } =
122 1: "The server does not support this method, please check the driver-server compatibility:\n'{message}'.",
123 ServerConnectionFailed { addresses: Vec<Address> } =
124 2: "Unable to connect to TypeDB server(s) at: \n{addresses:?}",
125 ServerConnectionFailedWithError { error: String } =
126 3: "Unable to connect to TypeDB server(s), received errors: \n{error}",
127 ServerConnectionFailedStatusError { error: String } =
128 4: "Unable to connect to TypeDB server(s), received network or protocol error: \n{error}",
129 ServerConnectionIsClosed =
130 5: "The connection has been closed and no further operation is allowed.",
131 TransactionIsClosed =
132 6: "The transaction is closed and no further operation is allowed.",
133 TransactionIsClosedWithErrors { errors: String } =
134 7: "The transaction is closed because of the error(s):\n{errors}",
135 DatabaseNotFound { name: String } =
136 8: "Database '{name}' not found.",
137 MissingResponseField { field: &'static str } =
138 9: "Missing field in message received from server: '{field}'. This is either a version compatibility issue or a bug.",
139 UnknownRequestId { request_id: RequestID } =
140 10: "Received a response with unknown request id '{request_id}'",
141 UnexpectedResponse { response: String } =
142 11: "Received unexpected response from server: '{response}'. This is either a version compatibility issue or a bug.",
143 InvalidResponseField { name: &'static str } =
144 12: "Invalid field in message received from server: '{name}'. This is either a version compatibility issue or a bug.",
145 QueryStreamNoResponse =
146 13: "Didn't receive any server responses for the query.",
147 UnexpectedQueryType { query_type: i32 } =
148 14: "Unexpected query type in message received from server: {query_type}. This is either a version compatibility issue or a bug.",
149 UserManagementCloudOnly =
150 15: "User management is only available in TypeDB Cloud servers.",
151 CloudReplicaNotPrimary =
152 16: "The replica is not the primary replica.",
153 CloudAllNodesFailed { errors: String } =
154 17: "Attempted connecting to all TypeDB Cloud servers, but the following errors occurred: \n{errors}.",
155 CloudTokenCredentialInvalid =
156 18: "Invalid token credentials.",
157 CloudEncryptionSettingsMismatch =
158 19: "Unable to connect to TypeDB Cloud: possible encryption settings mismatch.",
159 CloudSSLCertificateNotValidated =
160 20: "SSL handshake with TypeDB Cloud failed: the server's identity could not be verified. Possible CA mismatch.",
161 BrokenPipe =
162 21: "Stream closed because of a broken pipe. This could happen if you are attempting to connect to an unencrypted cloud instance using a TLS-enabled credentials.",
163 ConnectionFailed =
164 22: "Connection failed. Please check the server is running and the address is accessible. Encrypted Cloud endpoints may also have misconfigured SSL certificates.",
165 MissingPort { address: String } =
166 23: "Invalid URL '{address}': missing port.",
167 AddressTranslationMismatch { unknown: HashSet<Address>, unmapped: HashSet<Address> } =
168 24: "Address translation map does not match the server's advertised address list. User-provided servers not in the advertised list: {unknown:?}. Advertised servers not mapped by user: {unmapped:?}.",
169 ValueTimeZoneNameNotRecognised { time_zone: String } =
170 25: "Time zone provided by the server has name '{time_zone}', which is not an officially recognized timezone.",
171 ValueTimeZoneOffsetNotRecognised { offset: i32 } =
172 26: "Time zone provided by the server has numerical offset '{offset}', which is not recognised as a valid value for offset in seconds.",
173 ValueStructNotImplemented =
174 27: "Struct valued responses are not yet supported by the driver.",
175 ListsNotImplemented =
176 28: "Lists are not yet supported by the driver.",
177 UnexpectedKind { kind: i32 } =
178 29: "Unexpected kind in message received from server: {kind}. This is either a version compatibility issue or a bug.",
179 UnexpectedConnectionClose =
180 30: "Connection closed unexpectedly.",
181}
182
183error_messages! { ConceptError
184 code: "CPT", type: "Concept Error",
185 UnavailableRowVariable { variable: String } =
186 1: "Cannot get concept from a concept row by variable '{variable}'.",
187 UnavailableRowIndex { index: usize } =
188 2: "Cannot get concept from a concept row by index '{index}'.",
189}
190
191error_messages! { InternalError
192 code: "INT", type: "Internal Error",
193 RecvError =
194 1: "Channel is closed.",
195 SendError =
196 2: "Unable to send response over callback channel (receiver dropped).",
197 UnexpectedRequestType { request_type: String } =
198 3: "Unexpected request type for remote procedure call: {request_type}. This is either a version compatibility issue or a bug.",
199 UnexpectedResponseType { response_type: String } =
200 4: "Unexpected response type for remote procedure call: {response_type}. This is either a version compatibility issue or a bug.",
201 UnknownServer { server: Address } =
202 5: "Received replica at unrecognized server: {server}.",
203 EnumOutOfBounds { value: i32, enum_name: &'static str } =
204 6: "Value '{value}' is out of bounds for enum '{enum_name}'.",
205}
206
207#[derive(Clone, PartialEq, Eq)]
208pub struct ServerError {
209 error_code: String,
210 error_domain: String,
211 message: String,
212 stack_trace: Vec<String>,
213}
214
215impl ServerError {
216 pub(crate) fn new(error_code: String, error_domain: String, message: String, stack_trace: Vec<String>) -> Self {
217 Self { error_code, error_domain, message, stack_trace }
218 }
219
220 pub(crate) fn format_code(&self) -> &str {
221 &self.error_code
222 }
223
224 pub(crate) fn message(&self) -> String {
225 self.to_string()
226 }
227
228 fn to_string(&self) -> String {
229 if self.stack_trace.is_empty() {
230 format!("[{}] {}. {}", self.error_code, self.error_domain, self.message)
231 } else {
232 format!("\n{}", self.stack_trace.join("\nCaused: "))
233 }
234 }
235}
236
237impl fmt::Display for ServerError {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 write!(f, "{}", self.to_string())
240 }
241}
242
243impl fmt::Debug for ServerError {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 fmt::Display::fmt(self, f)
246 }
247}
248
249#[derive(Clone, Debug, PartialEq, Eq)]
251pub enum Error {
252 Connection(ConnectionError),
253 Concept(ConceptError),
254 Internal(InternalError),
255 Server(ServerError),
256 Other(String),
257}
258
259impl Error {
260 pub fn code(&self) -> String {
261 match self {
262 Self::Connection(error) => error.format_code(),
263 Self::Concept(error) => error.format_code(),
264 Self::Internal(error) => error.format_code(),
265 Self::Server(error) => error.format_code().to_owned(),
266 Self::Other(_error) => String::new(),
267 }
268 }
269
270 pub fn message(&self) -> String {
271 match self {
272 Self::Connection(error) => error.message(),
273 Self::Concept(error) => error.message(),
274 Self::Internal(error) => error.message(),
275 Self::Server(error) => error.message(),
276 Self::Other(error) => error.clone(),
277 }
278 }
279
280 fn from_message(message: &str) -> Self {
281 Self::Other(message.to_owned())
283 }
284
285 fn parse_unavailable(status_message: &str) -> Error {
286 if status_message == "broken pipe" {
287 Error::Connection(ConnectionError::BrokenPipe)
288 } else if status_message.contains("received corrupt message") {
289 Error::Connection(ConnectionError::CloudEncryptionSettingsMismatch)
290 } else if status_message.contains("UnknownIssuer") {
291 Error::Connection(ConnectionError::CloudSSLCertificateNotValidated)
292 } else if status_message.contains("Connection refused") {
293 Error::Connection(ConnectionError::ConnectionFailed)
294 } else {
295 Error::Connection(ConnectionError::ServerConnectionFailedStatusError { error: status_message.to_owned() })
296 }
297 }
298}
299
300impl fmt::Display for Error {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 match self {
303 Self::Connection(error) => write!(f, "{error}"),
304 Self::Concept(error) => write!(f, "{error}"),
305 Self::Internal(error) => write!(f, "{error}"),
306 Self::Server(error) => write!(f, "{error}"),
307 Self::Other(message) => write!(f, "{message}"),
308 }
309 }
310}
311
312impl StdError for Error {
313 fn source(&self) -> Option<&(dyn StdError + 'static)> {
314 match self {
315 Self::Connection(error) => Some(error),
316 Self::Concept(error) => Some(error),
317 Self::Internal(error) => Some(error),
318 Self::Server(_) => None,
319 Self::Other(_) => None,
320 }
321 }
322}
323
324impl From<ConnectionError> for Error {
325 fn from(error: ConnectionError) -> Self {
326 Self::Connection(error)
327 }
328}
329
330impl From<ConceptError> for Error {
331 fn from(error: ConceptError) -> Self {
332 Self::Concept(error)
333 }
334}
335
336impl From<InternalError> for Error {
337 fn from(error: InternalError) -> Self {
338 Self::Internal(error)
339 }
340}
341
342impl From<ServerError> for Error {
343 fn from(error: ServerError) -> Self {
344 Self::Server(error)
345 }
346}
347
348impl From<Status> for Error {
349 fn from(status: Status) -> Self {
350 if let Ok(details) = status.check_error_details() {
351 if let Some(bad_request) = details.bad_request() {
352 Self::Connection(ConnectionError::ServerConnectionFailedWithError {
353 error: format!("{:?}", bad_request),
354 })
355 } else if let Some(error_info) = details.error_info() {
356 let code = error_info.reason.clone();
357 let domain = error_info.domain.clone();
358 let stack_trace =
359 if let Some(debug_info) = details.debug_info() { debug_info.stack_entries.clone() } else { vec![] };
360 Self::Server(ServerError::new(code, domain, status.message().to_owned(), stack_trace))
361 } else {
362 Self::from_message(status.message())
363 }
364 } else {
365 if status.code() == Code::Unavailable {
366 Self::parse_unavailable(status.message())
367 } else if status.code() == Code::Unknown
368 || is_rst_stream(&status)
369 || status.code() == Code::InvalidArgument
370 || status.code() == Code::FailedPrecondition
371 || status.code() == Code::AlreadyExists
372 {
373 Self::Connection(ConnectionError::ServerConnectionFailedStatusError {
374 error: status.message().to_owned(),
375 })
376 } else if status.code() == Code::Unimplemented {
377 Self::Connection(ConnectionError::RPCMethodUnavailable { message: status.message().to_owned() })
378 } else {
379 Self::from_message(status.message())
380 }
381 }
382 }
383}
384
385fn is_rst_stream(status: &Status) -> bool {
386 status.message().contains("Received Rst Stream")
388}
389
390impl From<http::uri::InvalidUri> for Error {
391 fn from(err: http::uri::InvalidUri) -> Self {
392 Self::Other(err.to_string())
393 }
394}
395
396impl From<tonic::transport::Error> for Error {
397 fn from(err: tonic::transport::Error) -> Self {
398 Self::Other(err.to_string())
399 }
400}
401
402impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
403 fn from(_err: tokio::sync::mpsc::error::SendError<T>) -> Self {
404 Self::Internal(InternalError::SendError)
405 }
406}
407
408impl From<tokio::sync::oneshot::error::RecvError> for Error {
409 fn from(_err: tokio::sync::oneshot::error::RecvError) -> Self {
410 Self::Internal(InternalError::RecvError)
411 }
412}
413
414impl From<crossbeam::channel::RecvError> for Error {
415 fn from(_err: crossbeam::channel::RecvError) -> Self {
416 Self::Internal(InternalError::RecvError)
417 }
418}
419
420impl<T> From<crossbeam::channel::SendError<T>> for Error {
421 fn from(_err: crossbeam::channel::SendError<T>) -> Self {
422 Self::Internal(InternalError::SendError)
423 }
424}
425
426impl From<String> for Error {
427 fn from(err: String) -> Self {
428 Self::Other(err)
429 }
430}
431
432impl From<std::io::Error> for Error {
433 fn from(err: std::io::Error) -> Self {
434 Self::Other(err.to_string())
435 }
436}