-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy patherror.rs
More file actions
343 lines (320 loc) · 13.8 KB
/
error.rs
File metadata and controls
343 lines (320 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use axum::response::IntoResponse;
use hyper::StatusCode;
use tonic::metadata::errors::InvalidMetadataValueBytes;
use crate::{
auth::AuthError,
namespace::{configurator::fork::ForkError, NamespaceName},
query_result_builder::QueryResultBuilderError,
};
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("LibSQL failed to bind provided query parameters: `{0}`")]
LibSqlInvalidQueryParams(anyhow::Error),
#[error("Transaction timed-out")]
LibSqlTxTimeout,
#[error("Server can't handle additional transactions")]
LibSqlTxBusy,
#[error(transparent)]
IOError(std::io::Error),
#[error(transparent)]
RusqliteError(#[from] rusqlite::Error),
#[error("{0}")]
RusqliteErrorExtended(rusqlite::Error, i32),
#[error("Failed to execute query via RPC. Error code: {}, message: {}", .0.code, .0.message)]
RpcQueryError(crate::rpc::proxy::rpc::Error),
#[error("Failed to execute queries via RPC protocol: `{0}`")]
RpcQueryExecutionError(#[from] tonic::Status),
#[error("Database value error: `{0}`")]
DbValueError(String),
// Dedicated for most generic internal errors. Please use it sparingly.
// Consider creating a dedicate enum value for your error.
#[error("Internal Error: `{0}`")]
Internal(String),
#[error("Invalid batch step: {0}")]
InvalidBatchStep(usize),
#[error("Not authorized to execute query: {0}")]
NotAuthorized(String),
#[error("Authorization forbidden: {0}")]
Forbidden(String),
#[error("The replicator exited, instance cannot make any progress.")]
ReplicatorExited,
#[error("Timed out while opening database connection")]
DbCreateTimeout,
#[error(transparent)]
BuilderError(#[from] QueryResultBuilderError),
#[error("Operation was blocked{}", .0.as_ref().map(|msg| format!(": {}", msg)).unwrap_or_default())]
Blocked(Option<String>),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error("Too many concurrent requests")]
TooManyRequests,
#[error("Failed to parse query: `{0}`")]
FailedToParse(String),
#[error("Query error: `{0}`")]
QueryError(String),
#[error("Unauthorized: `{0}`")]
AuthError(#[from] AuthError),
// Catch-all error since we use anyhow in certain places
#[error("Internal Error: `{0}`")]
Anyhow(#[from] anyhow::Error),
#[error("Invalid host header: `{0}`")]
InvalidHost(String),
#[error("Invalid path in URI: `{0}`")]
InvalidPath(String),
#[error("Namespace `{0}` doesn't exist")]
NamespaceDoesntExist(String),
#[error("Namespace `{0}` already exists")]
NamespaceAlreadyExist(String),
#[error("Invalid namespace")]
InvalidNamespace,
#[error("Invalid namespace bytes: `{0}`")]
InvalidNamespaceBytes(Box<dyn std::error::Error + Sync + Send + 'static>),
#[error("Replica meta error: {0}")]
ReplicaMetaError(#[from] libsql_replication::meta::Error),
#[error("Replicator error: {0}")]
ReplicatorError(#[from] libsql_replication::replicator::Error),
#[error("Failed to connect to primary")]
PrimaryConnectionTimeout,
#[error("Error while loading dump: {0}")]
LoadDumpError(#[from] LoadDumpError),
#[error("Unable to convert metadata value: `{0}`")]
InvalidMetadataBytes(#[from] InvalidMetadataValueBytes),
#[error("Cannot call parametrized restore over replica")]
ReplicaRestoreError,
#[error("Cannot load from a dump if a database already exists.")]
LoadDumpExistingDb,
#[error("Cannot restore database when conflicting params were provided")]
ConflictingRestoreParameters,
#[error("Failed to fork database: {0}")]
Fork(#[from] ForkError),
#[error("Fatal replication error")]
FatalReplicationError,
#[error("Connection with primary broken")]
PrimaryStreamDisconnect,
#[error("Proxy protocal misuse")]
PrimaryStreamMisuse,
#[error("Proxy request interupted")]
PrimaryStreamInterupted,
#[error("Wrong URL: {0}")]
UrlParseError(#[from] url::ParseError),
#[error("Namespace store has shutdown")]
NamespaceStoreShutdown,
#[error("Unable to update metastore: {0}")]
MetaStoreUpdateFailure(Box<dyn std::error::Error + Send + Sync>),
// This is for errors returned by moka
#[error(transparent)]
Ref(#[from] std::sync::Arc<Self>),
#[error("Unable to decode protobuf: {0}")]
ProstDecode(#[from] prost::DecodeError),
#[error("Shared schema error: {0}")]
SharedSchemaCreationError(String),
#[error("Shared schema usage error: {0}")]
SharedSchemaUsageError(String),
#[error("migration error: {0}")]
Migration(#[from] crate::schema::Error),
#[error("cannot create/update/delete database config while there are pending migration on the shared schema `{0}`")]
PendingMigrationOnSchema(NamespaceName),
#[error("couldn't find requested migration job")]
MigrationJobNotFound,
#[error("cannot delete `{0}` because databases are still refering to it")]
HasLinkedDbs(NamespaceName),
#[error("ATTACH is not permitted in migration scripts")]
AttachInMigration,
#[error("join failure: {0}")]
RuntimeTaskJoinError(#[from] tokio::task::JoinError),
#[error("database is not a primary")]
NotAPrimary,
}
impl AsRef<Self> for Error {
fn as_ref(&self) -> &Self {
match self {
Self::Ref(this) => this.as_ref(),
_ => self,
}
}
}
pub trait ResponseError: std::error::Error {
fn format_err(&self, status: StatusCode) -> axum::response::Response {
let json = serde_json::json!({ "error": self.to_string() });
tracing::error!("HTTP API: {}, {:?}", status, self);
(status, axum::Json(json)).into_response()
}
}
impl ResponseError for Error {}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
(&self).into_response()
}
}
impl IntoResponse for &Error {
fn into_response(self) -> axum::response::Response {
use Error::*;
match self {
FailedToParse(_) => self.format_err(StatusCode::BAD_REQUEST),
AuthError(_) => self.format_err(StatusCode::UNAUTHORIZED),
Anyhow(e) => match e.downcast_ref::<Error>() {
Some(err) => err.into_response(),
None => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
},
LibSqlInvalidQueryParams(_) => self.format_err(StatusCode::BAD_REQUEST),
LibSqlTxTimeout => self.format_err(StatusCode::BAD_REQUEST),
LibSqlTxBusy => self.format_err(StatusCode::TOO_MANY_REQUESTS),
IOError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
RusqliteError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
RusqliteErrorExtended(_, _) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
RpcQueryError(_) => self.format_err(StatusCode::BAD_REQUEST),
RpcQueryExecutionError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
DbValueError(_) => self.format_err(StatusCode::BAD_REQUEST),
Internal(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
InvalidBatchStep(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
NotAuthorized(_) => self.format_err(StatusCode::UNAUTHORIZED),
Forbidden(_) => self.format_err(StatusCode::FORBIDDEN),
ReplicatorExited => self.format_err(StatusCode::SERVICE_UNAVAILABLE),
DbCreateTimeout => self.format_err(StatusCode::TOO_MANY_REQUESTS),
BuilderError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
Blocked(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
Json(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
TooManyRequests => self.format_err(StatusCode::TOO_MANY_REQUESTS),
QueryError(_) => self.format_err(StatusCode::BAD_REQUEST),
InvalidHost(_) => self.format_err(StatusCode::BAD_REQUEST),
InvalidPath(_) => self.format_err(StatusCode::BAD_REQUEST),
NamespaceDoesntExist(_) => self.format_err(StatusCode::NOT_FOUND),
PrimaryConnectionTimeout => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
NamespaceAlreadyExist(_) => self.format_err(StatusCode::BAD_REQUEST),
InvalidNamespace => self.format_err(StatusCode::BAD_REQUEST),
InvalidNamespaceBytes(_) => self.format_err(StatusCode::BAD_REQUEST),
LoadDumpError(e) => e.into_response(),
InvalidMetadataBytes(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
ReplicaRestoreError => self.format_err(StatusCode::BAD_REQUEST),
LoadDumpExistingDb => self.format_err(StatusCode::BAD_REQUEST),
ConflictingRestoreParameters => self.format_err(StatusCode::BAD_REQUEST),
Fork(e) => e.into_response(),
FatalReplicationError => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
ReplicatorError(e) => match e {
libsql_replication::replicator::Error::NamespaceDoesntExist => {
self.format_err(StatusCode::NOT_FOUND)
}
_ => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
},
ReplicaMetaError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
PrimaryStreamDisconnect => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
PrimaryStreamMisuse => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
PrimaryStreamInterupted => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
UrlParseError(_) => self.format_err(StatusCode::BAD_REQUEST),
NamespaceStoreShutdown => self.format_err(StatusCode::SERVICE_UNAVAILABLE),
MetaStoreUpdateFailure(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
Ref(this) => this.as_ref().into_response(),
ProstDecode(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
SharedSchemaCreationError(_) => self.format_err(StatusCode::BAD_REQUEST),
SharedSchemaUsageError(_) => self.format_err(StatusCode::BAD_REQUEST),
Migration(e) => e.into_response(),
PendingMigrationOnSchema(_) => self.format_err(StatusCode::BAD_REQUEST),
MigrationJobNotFound => self.format_err(StatusCode::NOT_FOUND),
HasLinkedDbs(_) => self.format_err(StatusCode::BAD_REQUEST),
AttachInMigration => self.format_err(StatusCode::BAD_REQUEST),
RuntimeTaskJoinError(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
NotAPrimary => self.format_err(StatusCode::BAD_REQUEST),
}
}
}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
tracing::error!("IO error reported: {:?}", value);
Error::IOError(value)
}
}
impl From<tokio::sync::oneshot::error::RecvError> for Error {
fn from(inner: tokio::sync::oneshot::error::RecvError) -> Self {
Self::Internal(format!(
"Failed to receive response via oneshot channel: {inner}"
))
}
}
impl From<wincode::WriteError> for Error {
fn from(other: wincode::WriteError) -> Self {
Self::Internal(other.to_string())
}
}
impl From<wincode::ReadError> for Error {
fn from(other: wincode::ReadError) -> Self {
Self::Internal(other.to_string())
}
}
macro_rules! internal_from {
($to:ty => { $($from:ty,)* }) => {
$(
impl From<$from> for $to {
fn from(v: $from) -> Self {
<$to>::Internal(v.to_string())
}
}
)*
};
}
internal_from! {
LoadDumpError => {
std::io::Error,
rusqlite::Error,
hyper::Error,
tokio::task::JoinError,
}
}
#[derive(Debug, thiserror::Error)]
pub enum LoadDumpError {
#[error("Internal error: {0}")]
Internal(String),
#[error("Cannot load a dump on a replica")]
ReplicaLoadDump,
#[error("Cannot load from a dump if a database already exists")]
LoadDumpExistingDb,
#[error("The passed dump file path is not absolute")]
DumpFilePathNotAbsolute,
#[error("The passed dump file path doesn't exist")]
DumpFileDoesntExist,
#[error("Invalid dump url")]
InvalidDumpUrl,
#[error("Unsupported dump url scheme `{0}`, supported schemes are: `http`, `file`")]
UnsupportedUrlScheme(String),
#[error("A dump should execute within a transaction.")]
NoTxn,
#[error("The dump should commit the transaction.")]
NoCommit,
#[error("Path is not a file")]
NotAFile,
#[error("The passed dump sql is invalid: {0}")]
InvalidSqlInput(String),
}
impl ResponseError for LoadDumpError {}
impl IntoResponse for &LoadDumpError {
fn into_response(self) -> axum::response::Response {
use LoadDumpError::*;
match &self {
Internal(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
ReplicaLoadDump
| LoadDumpExistingDb
| InvalidDumpUrl
| DumpFileDoesntExist
| UnsupportedUrlScheme(_)
| NoTxn
| NoCommit
| NotAFile
| DumpFilePathNotAbsolute
| InvalidSqlInput(_) => self.format_err(StatusCode::BAD_REQUEST),
}
}
}
impl ResponseError for ForkError {}
impl IntoResponse for &ForkError {
fn into_response(self) -> axum::response::Response {
match self {
ForkError::Internal(_)
| ForkError::Io(_)
| ForkError::LogRead(_)
| ForkError::BackupServiceNotConfigured
| ForkError::CreateNamespace(_) => self.format_err(StatusCode::INTERNAL_SERVER_ERROR),
ForkError::ForkReplica => self.format_err(StatusCode::BAD_REQUEST),
ForkError::ForkNoStorage => self.format_err(StatusCode::BAD_REQUEST),
}
}
}