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
use crate::errors::NeedRetry::IdempotentOnly;
use crate::grpc_wrapper::raw_errors::RawError;
use std::fmt::{Debug, Display, Formatter};
use std::sync::Arc;
use ydb_grpc::ydb_proto::status_ids::StatusCode;
/// T result or YdbError as Error
pub type YdbResult<T> = std::result::Result<T, YdbError>;
/// T result or YdbOrCustomerError as Error
pub type YdbResultWithCustomerErr<T> = std::result::Result<T, YdbOrCustomerError>;
/// Error for wrap user errors while return it from callback
#[derive(Clone)]
pub enum YdbOrCustomerError {
/// Usual YDB errors
YDB(YdbError),
/// Wrap for customer error
Customer(Arc<Box<dyn std::error::Error + Send + Sync>>),
}
impl YdbOrCustomerError {
#[allow(dead_code)]
pub(crate) fn from_mess<T: Into<String>>(s: T) -> Self {
Self::Customer(Arc::new(Box::new(YdbError::Custom(s.into()))))
}
/// Create YdbOrCustomerError from customer error
pub fn from_err<T: std::error::Error + 'static + Send + Sync>(err: T) -> Self {
Self::Customer(Arc::new(Box::new(err)))
}
pub fn to_ydb_error(self) -> YdbError {
match self {
Self::YDB(err) => err,
Self::Customer(err) => YdbError::custom(format!("{err}")),
}
}
}
impl Debug for YdbOrCustomerError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::YDB(err) => Debug::fmt(err, f),
Self::Customer(err) => Debug::fmt(err, f),
}
}
}
impl Display for YdbOrCustomerError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::YDB(err) => Display::fmt(err, f),
Self::Customer(err) => Display::fmt(err, f),
}
}
}
impl std::error::Error for YdbOrCustomerError {}
impl From<YdbError> for YdbOrCustomerError {
fn from(e: YdbError) -> Self {
Self::YDB(e)
}
}
pub(crate) enum NeedRetry {
True, // operation guarantee to not completed, error is temporary, need retry
IdempotentOnly, // operation in unknown state - it may be completed or not, error temporary. Operation may be auto retry for idempotent operations only.
False, // operation is completed or error is stable (for example yql syntaxt errror) and no need retry
}
/// Error which can be returned from the crate.
///
/// Now most of errors are simple Custom error with custom text.
/// Please not parse the text - it can be change at any time without compile check.
/// Write about error type you need or PR it.
#[derive(Clone, Debug)]
#[cfg_attr(not(feature = "force-exhaustive-all"), non_exhaustive)]
pub enum YdbError {
/// Common error
///
/// Not parse text of error for detect error type.
/// It will change.
Custom(String),
/// Errors of convert between native rust types and ydb value
Convert(String),
/// No rows in result set
NoRows,
/// Unexpected error. Write issue if it will happen.
InternalError(String),
/// Error while dial to ydb server
TransportDial(Arc<tonic::transport::Error>),
/// Error on transport level of request/response
Transport(String),
/// Error from GRPC status code
TransportGRPCStatus(Arc<tonic::Status>),
/// Error from operation status
YdbStatusError(YdbStatusError),
}
impl YdbError {
pub(crate) fn custom<T: Into<String>>(message: T) -> Self {
Self::Custom(message.into())
}
}
/// Describe operation status from server
///
/// Messages and codes doesn't have stable gurantee. But codes more stable.
/// If you want detect some errors prefer code over text parse. Messages for human usage only.
#[derive(Clone, Debug, Default)]
#[cfg_attr(not(feature = "force-exhaustive-all"), non_exhaustive)]
// Combine with YdbIssue?
pub struct YdbStatusError {
/// Human readable message described status
#[allow(dead_code)]
pub message: String,
/// Operation status code
///
/// Struct field presended as i32 - for repr any of received value
/// For get typed status use fn YdbStatusError::operation_status()
///
/// ```
/// # use ydb::{YdbResult, YdbStatusError};
/// # use ydb_grpc::ydb_proto::status_ids::StatusCode;
/// # fn main()->YdbResult<()>{
/// let mut status =YdbStatusError::default();
/// status.operation_status = StatusCode::AlreadyExists as i32;
/// assert_eq!(status.operation_status, 400130);
/// assert_eq!(status.operation_status()?, StatusCode::AlreadyExists);
/// # return Ok(());
/// # }
/// ```
pub operation_status: i32,
/// Ydb issue from server for the message
///
/// It describe internal errors, warnings, etc more detail then operation_status or message.
pub issues: Vec<YdbIssue>,
}
impl YdbStatusError {
/// Got typed operation status or error
///
/// ```
/// # use ydb::{YdbResult, YdbStatusError};
/// # use ydb_grpc::ydb_proto::status_ids::StatusCode;
/// # fn main()->YdbResult<()>{
/// let mut status = YdbStatusError::default();
/// status.operation_status= StatusCode::AlreadyExists as i32;
/// assert_eq!(status.operation_status, 400130);
/// assert_eq!(status.operation_status()?, StatusCode::AlreadyExists);
/// # return Ok(());
/// # }
/// ```
pub fn operation_status(&self) -> YdbResult<StatusCode> {
StatusCode::try_from(self.operation_status)
.map_err(|e| YdbError::InternalError(format!("unknown status code: {e}")))
}
}
/// Severity of issue
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(not(feature = "force-exhaustive-all"), non_exhaustive)]
pub enum YdbIssueSeverity {
#[default]
Fatal,
Error,
Warning,
Info,
// no use Unknown for own logic (use for debug/log only) - for prevent broke your code when new level will be defined.
// use convert to u32 for temporary use int code and ask a maintainer to add new level as explicit value
Unknown(u32),
}
impl From<YdbIssueSeverity> for u32 {
fn from(value: YdbIssueSeverity) -> Self {
match value {
YdbIssueSeverity::Fatal => 0,
YdbIssueSeverity::Error => 1,
YdbIssueSeverity::Warning => 2,
YdbIssueSeverity::Info => 3,
YdbIssueSeverity::Unknown(code) => code,
}
}
}
impl From<u32> for YdbIssueSeverity {
fn from(value: u32) -> Self {
match value {
0 => YdbIssueSeverity::Fatal,
1 => YdbIssueSeverity::Error,
2 => YdbIssueSeverity::Warning,
3 => YdbIssueSeverity::Info,
value => YdbIssueSeverity::Unknown(value),
}
}
}
/// Describe issue from server
///
/// Messages and codes doesn't have stable gurantee. But codes more stable.
/// If you want detect some errors prefer code over text parse. Messages for human usage only.
#[derive(Clone, Debug, Default)]
#[cfg_attr(not(feature = "force-exhaustive-all"), non_exhaustive)]
// Combine with YdbStatusError?
pub struct YdbIssue {
pub issue_code: u32,
pub message: String,
/// Recursive issues, explained current problems
pub issues: Vec<YdbIssue>,
/// Severity of the issue.
/// For get numeric code - use convert to u32.
/// ```
/// # use ydb::{YdbIssue, YdbIssueSeverity, YdbResult};
/// # fn main()->YdbResult<()>{
/// let mut issue = YdbIssue::default();
/// issue.severity = YdbIssueSeverity::Warning;
/// assert_eq!(u32::from(issue.severity), 2);
/// # return Ok(());
/// # }
/// ```
pub severity: YdbIssueSeverity,
}
impl YdbError {
pub(crate) fn from_str<T: Into<String>>(s: T) -> YdbError {
YdbError::Custom(s.into())
}
pub(crate) fn need_retry(&self) -> NeedRetry {
match self {
Self::Convert(_) => NeedRetry::False,
Self::Custom(_) => NeedRetry::False,
Self::InternalError(_) => NeedRetry::False,
Self::NoRows => NeedRetry::False,
Self::TransportDial(_) => NeedRetry::True,
Self::Transport(_) => IdempotentOnly, // TODO: check when transport error created
Self::TransportGRPCStatus(status) => {
use tonic::Code;
match status.code() {
Code::Aborted | Code::ResourceExhausted => NeedRetry::True,
Code::Internal | Code::Cancelled | Code::Unavailable => {
NeedRetry::IdempotentOnly
}
_ => NeedRetry::False,
}
}
Self::YdbStatusError(ydb_err) => {
let Ok(status) = StatusCode::try_from(ydb_err.operation_status) else {
return NeedRetry::False;
};
match status {
StatusCode::Aborted
| StatusCode::Unavailable
| StatusCode::Overloaded
| StatusCode::BadSession
| StatusCode::SessionBusy => NeedRetry::True,
StatusCode::Undetermined => NeedRetry::IdempotentOnly,
_ => NeedRetry::False,
}
}
}
}
}
impl Display for YdbError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self::Debug::fmt(self, f)
}
}
macro_rules! to_custom_ydb_err {
($($t:ty),+) => {
$(
impl From<$t> for YdbError {
fn from(e: $t) -> Self {
return YdbError::Custom(e.to_string());
}
}
)+
};
}
impl std::error::Error for YdbError {}
to_custom_ydb_err!(
YdbOrCustomerError,
std::convert::Infallible,
http::Error,
http::uri::InvalidUriParts,
reqwest::Error,
serde_json::Error,
std::env::VarError,
std::io::Error,
std::num::TryFromIntError,
std::string::FromUtf8Error,
std::time::SystemTimeError,
&str,
strum::ParseError,
tonic::transport::Error,
tokio::sync::AcquireError,
tokio::sync::oneshot::error::RecvError,
tokio::sync::watch::error::RecvError,
tokio::task::JoinError,
tonic::codegen::http::uri::InvalidUri,
url::ParseError
);
impl From<Box<dyn std::any::Any + Send>> for YdbError {
fn from(e: Box<dyn std::any::Any + Send>) -> Self {
YdbError::Custom(format!("{e:?}"))
}
}
impl<T> From<std::sync::PoisonError<T>> for YdbError {
fn from(e: std::sync::PoisonError<T>) -> Self {
YdbError::Custom(e.to_string())
}
}
impl From<tonic::Status> for YdbError {
fn from(e: tonic::Status) -> Self {
YdbError::TransportGRPCStatus(Arc::new(e))
}
}
impl From<RawError> for YdbError {
fn from(e: RawError) -> Self {
match e {
RawError::Custom(message) => YdbError::Custom(format!("raw custom error: {message}")),
RawError::ProtobufDecodeError(message) => {
YdbError::Custom(format!("decode protobuf error: {message}"))
}
RawError::TonicStatus(s) => YdbError::TransportGRPCStatus(Arc::new(*s)),
RawError::YdbStatus(status_error) => YdbError::YdbStatusError(status_error),
}
}
}