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
use std::{error::Error, fmt::Display, sync::Arc};
use serde::Serialize;
use tauri::http::HeaderMap;
type StatusMessage = Arc<Box<dyn Error + Send + Sync + 'static>>;
#[derive(Debug, Serialize, Clone)]
pub struct Status {
code: Code,
#[serde(with = "crate::ipc::header_map")]
metadata: HeaderMap,
#[serde(with = "self::message")]
message: StatusMessage,
}
/// gRPC status codes used by [`Status`].
///
/// These variants match the [gRPC status codes].
///
/// [gRPC status codes]: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md#status-codes-and-their-use-in-grpc
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Code {
/// The operation completed successfully.
Ok = 0,
/// The operation was cancelled.
Cancelled = 1,
/// Unknown error.
Unknown = 2,
/// Client specified an invalid argument.
InvalidArgument = 3,
/// Deadline expired before operation could complete.
DeadlineExceeded = 4,
/// Some requested entity was not found.
NotFound = 5,
/// Some entity that we attempted to create already exists.
AlreadyExists = 6,
/// The caller does not have permission to execute the specified operation.
PermissionDenied = 7,
/// Some resource has been exhausted.
ResourceExhausted = 8,
/// The system is not in a state required for the operation's execution.
FailedPrecondition = 9,
/// The operation was aborted.
Aborted = 10,
/// Operation was attempted past the valid range.
OutOfRange = 11,
/// Operation is not implemented or not supported.
Unimplemented = 12,
/// Internal error.
Internal = 13,
/// The service is currently unavailable.
Unavailable = 14,
/// Unrecoverable data loss or corruption.
DataLoss = 15,
/// The request does not have valid authentication credentials
Unauthenticated = 16,
}
impl Serialize for Code {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u16(*self as u16)
}
}
impl Code {
/// Get description of this `Code`.
/// ```
/// fn make_grpc_request() -> kanamaru::Code {
/// // ...
/// kanamaru::Code::Ok
/// }
/// let code = make_grpc_request();
/// println!("Operation completed. Human readable description: {}", code.description());
/// ```
/// If you only need description in `println`, `format`, `log` and other
/// formatting contexts, you may want to use `Display` impl for `Code`
/// instead.
pub fn description(&self) -> &'static str {
match self {
Code::Ok => "The operation completed successfully",
Code::Cancelled => "The operation was cancelled",
Code::Unknown => "Unknown error",
Code::InvalidArgument => "Client specified an invalid argument",
Code::DeadlineExceeded => "Deadline expired before operation could complete",
Code::NotFound => "Some requested entity was not found",
Code::AlreadyExists => "Some entity that we attempted to create already exists",
Code::PermissionDenied => {
"The caller does not have permission to execute the specified operation"
}
Code::ResourceExhausted => "Some resource has been exhausted",
Code::FailedPrecondition => {
"The system is not in a state required for the operation's execution"
}
Code::Aborted => "The operation was aborted",
Code::OutOfRange => "Operation was attempted past the valid range",
Code::Unimplemented => "Operation is not implemented or not supported",
Code::Internal => "Internal error",
Code::Unavailable => "The service is currently unavailable",
Code::DataLoss => "Unrecoverable data loss or corruption",
Code::Unauthenticated => "The request does not have valid authentication credentials",
}
}
}
mod message {
use serde::{Serialize, Serializer};
use super::StatusMessage;
pub fn serialize<S>(message: &StatusMessage, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
message.to_string().serialize(serializer)
}
}
impl<E: Error + Send + Sync + 'static> From<E> for Status {
fn from(value: E) -> Self {
Self {
code: Code::Unknown,
metadata: Default::default(),
message: Arc::new(Box::new(value)),
}
}
}
pub trait AsCode {
fn as_code(&self) -> Code;
}
impl AsCode for Status {
fn as_code(&self) -> Code {
self.code
}
}
impl Status {
/// Create a new `Status` with the associated code and message.
pub fn new<M>(code: Code, message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status {
code,
message: Arc::new(message.into()),
metadata: HeaderMap::new(),
}
}
/// The operation completed successfully.
pub fn ok<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Ok, message)
}
/// The operation was cancelled (typically by the caller).
pub fn cancelled<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Cancelled, message)
}
/// Unknown error. An example of where this error may be returned is if a
/// `Status` value received from another address space belongs to an error-space
/// that is not known in this address space. Also errors raised by APIs that
/// do not return enough error information may be converted to this error.
pub fn unknown<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Unknown, message)
}
/// Client specified an invalid argument. Note that this differs from
/// `FailedPrecondition`. `InvalidArgument` indicates arguments that are
/// problematic regardless of the state of the system (e.g., a malformed file
/// name).
pub fn invalid_argument<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::InvalidArgument, message)
}
/// Deadline expired before operation could complete. For operations that
/// change the state of the system, this error may be returned even if the
/// operation has completed successfully. For example, a successful response
/// from a server could have been delayed long enough for the deadline to
/// expire.
pub fn deadline_exceeded<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::DeadlineExceeded, message)
}
/// Some requested entity (e.g., file or directory) was not found.
pub fn not_found<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::NotFound, message)
}
/// Some entity that we attempted to create (e.g., file or directory) already
/// exists.
pub fn already_exists<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::AlreadyExists, message)
}
/// The caller does not have permission to execute the specified operation.
/// `PermissionDenied` must not be used for rejections caused by exhausting
/// some resource (use `ResourceExhausted` instead for those errors).
/// `PermissionDenied` must not be used if the caller cannot be identified
/// (use `Unauthenticated` instead for those errors).
pub fn permission_denied<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::PermissionDenied, message)
}
/// Some resource has been exhausted, perhaps a per-user quota, or perhaps
/// the entire file system is out of space.
pub fn resource_exhausted<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::ResourceExhausted, message)
}
/// Operation was rejected because the system is not in a state required for
/// the operation's execution. For example, directory to be deleted may be
/// non-empty, an rmdir operation is applied to a non-directory, etc.
///
/// A litmus test that may help a service implementor in deciding between
/// `FailedPrecondition`, `Aborted`, and `Unavailable`:
/// (a) Use `Unavailable` if the client can retry just the failing call.
/// (b) Use `Aborted` if the client should retry at a higher-level (e.g.,
/// restarting a read-modify-write sequence).
/// (c) Use `FailedPrecondition` if the client should not retry until the
/// system state has been explicitly fixed. E.g., if an "rmdir" fails
/// because the directory is non-empty, `FailedPrecondition` should be
/// returned since the client should not retry unless they have first
/// fixed up the directory by deleting files from it.
pub fn failed_precondition<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::FailedPrecondition, message)
}
/// The operation was aborted, typically due to a concurrency issue like
/// sequencer check failures, transaction aborts, etc.
///
/// See litmus test above for deciding between `FailedPrecondition`,
/// `Aborted`, and `Unavailable`.
pub fn aborted<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Aborted, message)
}
/// Operation was attempted past the valid range. E.g., seeking or reading
/// past end of file.
///
/// Unlike `InvalidArgument`, this error indicates a problem that may be
/// fixed if the system state changes. For example, a 32-bit file system will
/// generate `InvalidArgument if asked to read at an offset that is not in the
/// range [0,2^32-1], but it will generate `OutOfRange` if asked to read from
/// an offset past the current file size.
///
/// There is a fair bit of overlap between `FailedPrecondition` and
/// `OutOfRange`. We recommend using `OutOfRange` (the more specific error)
/// when it applies so that callers who are iterating through a space can
/// easily look for an `OutOfRange` error to detect when they are done.
pub fn out_of_range<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::OutOfRange, message)
}
/// Operation is not implemented or not supported/enabled in this service.
pub fn unimplemented<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Unimplemented, message)
}
/// Internal errors. Means some invariants expected by underlying system has
/// been broken. If you see one of these errors, something is very broken.
pub fn internal<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Internal, message)
}
/// The service is currently unavailable. This is a most likely a transient
/// condition and may be corrected by retrying with a back-off.
///
/// See litmus test above for deciding between `FailedPrecondition`,
/// `Aborted`, and `Unavailable`.
pub fn unavailable<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Unavailable, message)
}
/// Unrecoverable data loss or corruption.
pub fn data_loss<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::DataLoss, message)
}
/// The request does not have valid authentication credentials for the
/// operation.
pub fn unauthenticated<M>(message: M) -> Status
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
Status::new(Code::Unauthenticated, message)
}
pub fn message(&self) -> &(dyn Error + Send + Sync + 'static) {
&**self.message.as_ref() as _
}
pub fn metadata(&self) -> &HeaderMap {
&self.metadata
}
pub fn metadata_mut(&mut self) -> &mut HeaderMap {
&mut self.metadata
}
pub fn set_message<M>(&mut self, message: M)
where
M: Into<Box<dyn Error + Send + Sync + 'static>>,
{
self.message = Arc::new(message.into())
}
pub fn set_code(&mut self, code: Code) {
self.code = code
}
}
impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"status: {:?}, message: {:?}, metadata: {:?}",
self.code, self.message, self.metadata
)
}
}