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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use crate::frame::frame_errors::{FrameError, ParseError};
use crate::frame::types::LegacyConsistency;
use crate::frame::value::SerializeValuesError;
use bytes::Bytes;
use std::io::ErrorKind;
use std::sync::Arc;
use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum QueryError {
#[error("Database returned an error: {0}, Error message: {1}")]
DbError(DbError, String),
#[error(transparent)]
BadQuery(#[from] BadQuery),
#[error("IO Error: {0}")]
IoError(Arc<std::io::Error>),
#[error("Protocol Error: {0}")]
ProtocolError(&'static str),
#[error("Invalid message: {0}")]
InvalidMessage(String),
#[error("Timeout Error")]
TimeoutError,
#[error("Too many orphaned stream ids: {0}")]
TooManyOrphanedStreamIds(u16),
#[error("Unable to allocate stream id")]
UnableToAllocStreamId,
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum DbError {
#[error("The submitted query has a syntax error")]
SyntaxError,
#[error("The query is syntatically correct but invalid")]
Invalid,
#[error(
"Attempted to create a keyspace or a table that was already existing \
(keyspace: {keyspace}, table: {table})"
)]
AlreadyExists {
keyspace: String,
table: String,
},
#[error(
"User defined function failed during execution \
(keyspace: {keyspace}, function: {function}, arg_types: {arg_types:?})"
)]
FunctionFailure {
keyspace: String,
function: String,
arg_types: Vec<String>,
},
#[error("Authentication failed - bad credentials")]
AuthenticationError,
#[error("The logged user doesn't have the right to perform the query")]
Unauthorized,
#[error("The query is invalid because of some configuration issue")]
ConfigError,
#[error(
"Not enough nodes are alive to satisfy required consistency level \
(consistency: {consistency}, required: {required}, alive: {alive})"
)]
Unavailable {
consistency: LegacyConsistency,
required: i32,
alive: i32,
},
#[error("The request cannot be processed because the coordinator node is overloaded")]
Overloaded,
#[error("The coordinator node is still bootstrapping")]
IsBootstrapping,
#[error("Error during truncate operation")]
TruncateError,
#[error("Not enough nodes responded to the read request in time to satisfy required consistency level \
(consistency: {consistency}, received: {received}, required: {required}, data_present: {data_present})")]
ReadTimeout {
consistency: LegacyConsistency,
received: i32,
required: i32,
data_present: bool,
},
#[error("Not enough nodes responded to the write request in time to satisfy required consistency level \
(consistency: {consistency}, received: {received}, required: {required}, write_type: {write_type})")]
WriteTimeout {
consistency: LegacyConsistency,
received: i32,
required: i32,
write_type: WriteType,
},
#[error(
"A non-timeout error during a read request \
(consistency: {consistency}, received: {received}, required: {required}, \
numfailures: {numfailures}, data_present: {data_present})"
)]
ReadFailure {
consistency: LegacyConsistency,
received: i32,
required: i32,
numfailures: i32,
data_present: bool,
},
#[error(
"A non-timeout error during a write request \
(consistency: {consistency}, received: {received}, required: {required}, \
numfailures: {numfailures}, write_type: {write_type}"
)]
WriteFailure {
consistency: LegacyConsistency,
received: i32,
required: i32,
numfailures: i32,
write_type: WriteType,
},
#[error(
"Tried to execute a prepared statement that is not prepared. Driver should prepare it again"
)]
Unprepared {
statement_id: Bytes,
},
#[error("Internal server error. This indicates a server-side bug")]
ServerError,
#[error("Invalid protocol message received from the driver")]
ProtocolError,
#[error("Other error not specified in the specification. Error code: {0}")]
Other(i32),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WriteType {
Simple,
Batch,
UnloggedBatch,
Counter,
BatchLog,
Cas,
View,
Cdc,
Other(String),
}
#[derive(Error, Debug, Clone)]
#[error("Invalid query passed to Session")]
pub enum BadQuery {
#[error("Serializing values failed: {0} ")]
SerializeValuesError(#[from] SerializeValuesError),
#[error("Length of provided values ({0}) must be equal to number of batch statements ({1})")]
ValueLenMismatch(usize, usize),
#[error("Serialized values are too long to compute partition key! Length: {0}, Max allowed length: {1}")]
ValuesTooLongForKey(usize, usize),
#[error("Passed invalid keyspace name to use: {0}")]
BadKeyspaceName(#[from] BadKeyspaceName),
}
#[derive(Error, Debug, Clone)]
pub enum NewSessionError {
#[error("Couldn't resolve address: {0}")]
FailedToResolveAddress(String),
#[error("Empty known nodes list")]
EmptyKnownNodesList,
#[error("Database returned an error: {0}, Error message: {1}")]
DbError(DbError, String),
#[error(transparent)]
BadQuery(#[from] BadQuery),
#[error("IO Error: {0}")]
IoError(Arc<std::io::Error>),
#[error("Protocol Error: {0}")]
ProtocolError(&'static str),
#[error("Invalid message: {0}")]
InvalidMessage(String),
#[error("Timeout Error")]
TimeoutError,
#[error("Too many orphaned stream ids: {0}")]
TooManyOrphanedStreamIds(u16),
#[error("Unable to allocate stream id")]
UnableToAllocStreamId,
}
#[derive(Debug, Error, Clone)]
pub enum BadKeyspaceName {
#[error("Keyspace name is empty")]
Empty,
#[error("Keyspace name too long, must be up to 48 characters, found {1} characters. Bad keyspace name: '{0}'")]
TooLong(String, usize),
#[error("Illegal character found: '{1}', only alphanumeric and underscores allowed. Bad keyspace name: '{0}'")]
IllegalCharacter(String, char),
}
impl std::fmt::Display for WriteType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl From<std::io::Error> for QueryError {
fn from(io_error: std::io::Error) -> QueryError {
QueryError::IoError(Arc::new(io_error))
}
}
impl From<SerializeValuesError> for QueryError {
fn from(serialized_err: SerializeValuesError) -> QueryError {
QueryError::BadQuery(BadQuery::SerializeValuesError(serialized_err))
}
}
impl From<ParseError> for QueryError {
fn from(parse_error: ParseError) -> QueryError {
QueryError::InvalidMessage(format!("Error parsing message: {}", parse_error))
}
}
impl From<FrameError> for QueryError {
fn from(frame_error: FrameError) -> QueryError {
QueryError::InvalidMessage(format!("Frame error: {}", frame_error))
}
}
impl From<std::io::Error> for NewSessionError {
fn from(io_error: std::io::Error) -> NewSessionError {
NewSessionError::IoError(Arc::new(io_error))
}
}
impl From<QueryError> for NewSessionError {
fn from(query_error: QueryError) -> NewSessionError {
match query_error {
QueryError::DbError(e, msg) => NewSessionError::DbError(e, msg),
QueryError::BadQuery(e) => NewSessionError::BadQuery(e),
QueryError::IoError(e) => NewSessionError::IoError(e),
QueryError::ProtocolError(m) => NewSessionError::ProtocolError(m),
QueryError::InvalidMessage(m) => NewSessionError::InvalidMessage(m),
QueryError::TimeoutError => NewSessionError::TimeoutError,
QueryError::TooManyOrphanedStreamIds(ids) => {
NewSessionError::TooManyOrphanedStreamIds(ids)
}
QueryError::UnableToAllocStreamId => NewSessionError::UnableToAllocStreamId,
}
}
}
impl From<BadKeyspaceName> for QueryError {
fn from(keyspace_err: BadKeyspaceName) -> QueryError {
QueryError::BadQuery(BadQuery::BadKeyspaceName(keyspace_err))
}
}
impl QueryError {
pub(crate) fn is_address_unavailable_for_use(&self) -> bool {
if let QueryError::IoError(io_error) = self {
match io_error.kind() {
ErrorKind::AddrInUse | ErrorKind::PermissionDenied => return true,
_ => {}
}
}
false
}
}
impl From<&str> for WriteType {
fn from(write_type_str: &str) -> WriteType {
match write_type_str {
"SIMPLE" => WriteType::Simple,
"BATCH" => WriteType::Batch,
"UNLOGGED_BATCH" => WriteType::UnloggedBatch,
"COUNTER" => WriteType::Counter,
"BATCH_LOG" => WriteType::BatchLog,
"CAS" => WriteType::Cas,
"VIEW" => WriteType::View,
"CDC" => WriteType::Cdc,
_ => WriteType::Other(write_type_str.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::{DbError, QueryError, WriteType};
use crate::frame::types::LegacyConsistency;
use crate::statement::Consistency;
#[test]
fn write_type_from_str() {
let test_cases: [(&str, WriteType); 9] = [
("SIMPLE", WriteType::Simple),
("BATCH", WriteType::Batch),
("UNLOGGED_BATCH", WriteType::UnloggedBatch),
("COUNTER", WriteType::Counter),
("BATCH_LOG", WriteType::BatchLog),
("CAS", WriteType::Cas),
("VIEW", WriteType::View),
("CDC", WriteType::Cdc),
("SOMEOTHER", WriteType::Other("SOMEOTHER".to_string())),
];
for (write_type_str, expected_write_type) in &test_cases {
let write_type = WriteType::from(*write_type_str);
assert_eq!(write_type, *expected_write_type);
}
}
#[test]
fn dberror_full_info() {
let db_error = DbError::Unavailable {
consistency: LegacyConsistency::Regular(Consistency::Three),
required: 3,
alive: 2,
};
let db_error_displayed: String = format!("{}", db_error);
let mut expected_dberr_msg =
"Not enough nodes are alive to satisfy required consistency level ".to_string();
expected_dberr_msg += "(consistency: Three, required: 3, alive: 2)";
assert_eq!(db_error_displayed, expected_dberr_msg);
let query_error =
QueryError::DbError(db_error, "a message about unavailable error".to_string());
let query_error_displayed: String = format!("{}", query_error);
let mut expected_querr_msg = "Database returned an error: ".to_string();
expected_querr_msg += &expected_dberr_msg;
expected_querr_msg += ", Error message: a message about unavailable error";
assert_eq!(query_error_displayed, expected_querr_msg);
}
}