forked from anthropics/connect-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
469 lines (425 loc) · 15.5 KB
/
error.rs
File metadata and controls
469 lines (425 loc) · 15.5 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
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
465
466
467
468
469
//! ConnectRPC error types and HTTP status mapping.
//!
//! This module provides error types that conform to the ConnectRPC protocol
//! specification, including proper error code mappings to HTTP status codes.
use bytes::Bytes;
use http::StatusCode;
use serde::Deserialize;
use serde::Serialize;
/// ConnectRPC error codes.
///
/// These codes follow the ConnectRPC protocol specification and map to
/// corresponding HTTP status codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
/// The operation was cancelled.
Canceled,
/// Unknown error.
Unknown,
/// Invalid argument provided by the client.
InvalidArgument,
/// Deadline expired before operation completed.
DeadlineExceeded,
/// Requested entity was not found.
NotFound,
/// Entity already exists.
AlreadyExists,
/// Permission denied.
PermissionDenied,
/// Resource exhausted (e.g., rate limit).
ResourceExhausted,
/// Operation rejected due to system state.
FailedPrecondition,
/// Operation was aborted.
Aborted,
/// Operation was out of range.
OutOfRange,
/// Operation is not implemented.
Unimplemented,
/// Internal error.
Internal,
/// Service is unavailable.
Unavailable,
/// Unrecoverable data loss.
DataLoss,
/// Request is unauthenticated.
Unauthenticated,
}
impl ErrorCode {
/// Get the string representation of this error code.
#[inline]
pub fn as_str(&self) -> &'static str {
match self {
Self::Canceled => "canceled",
Self::Unknown => "unknown",
Self::InvalidArgument => "invalid_argument",
Self::DeadlineExceeded => "deadline_exceeded",
Self::NotFound => "not_found",
Self::AlreadyExists => "already_exists",
Self::PermissionDenied => "permission_denied",
Self::ResourceExhausted => "resource_exhausted",
Self::FailedPrecondition => "failed_precondition",
Self::Aborted => "aborted",
Self::OutOfRange => "out_of_range",
Self::Unimplemented => "unimplemented",
Self::Internal => "internal",
Self::Unavailable => "unavailable",
Self::DataLoss => "data_loss",
Self::Unauthenticated => "unauthenticated",
}
}
/// Get the HTTP status code for this error code.
#[inline]
pub fn http_status(&self) -> StatusCode {
match self {
// 499 Client Closed Request (nginx-style, used by Connect protocol for Canceled)
Self::Canceled => {
// 499 is always valid (100-999 range), but avoid panic in library code.
StatusCode::from_u16(499).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
Self::Unknown => StatusCode::INTERNAL_SERVER_ERROR,
Self::InvalidArgument => StatusCode::BAD_REQUEST,
Self::DeadlineExceeded => StatusCode::GATEWAY_TIMEOUT,
Self::NotFound => StatusCode::NOT_FOUND,
Self::AlreadyExists => StatusCode::CONFLICT,
Self::PermissionDenied => StatusCode::FORBIDDEN,
Self::ResourceExhausted => StatusCode::TOO_MANY_REQUESTS,
Self::FailedPrecondition => StatusCode::BAD_REQUEST,
Self::Aborted => StatusCode::CONFLICT,
Self::OutOfRange => StatusCode::BAD_REQUEST,
Self::Unimplemented => StatusCode::NOT_IMPLEMENTED,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
Self::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
Self::DataLoss => StatusCode::INTERNAL_SERVER_ERROR,
Self::Unauthenticated => StatusCode::UNAUTHORIZED,
}
}
}
impl ErrorCode {
/// Get the gRPC numeric status code for this error code.
#[inline]
pub fn grpc_code(&self) -> u32 {
match self {
Self::Canceled => 1,
Self::Unknown => 2,
Self::InvalidArgument => 3,
Self::DeadlineExceeded => 4,
Self::NotFound => 5,
Self::AlreadyExists => 6,
Self::PermissionDenied => 7,
Self::ResourceExhausted => 8,
Self::FailedPrecondition => 9,
Self::Aborted => 10,
Self::OutOfRange => 11,
Self::Unimplemented => 12,
Self::Internal => 13,
Self::Unavailable => 14,
Self::DataLoss => 15,
Self::Unauthenticated => 16,
}
}
/// Create an error code from a gRPC numeric status code.
///
/// Returns `None` for unknown codes. Code 0 (OK) returns `None` since
/// it represents success, not an error.
#[inline]
pub fn from_grpc_code(code: u32) -> Option<Self> {
match code {
1 => Some(Self::Canceled),
2 => Some(Self::Unknown),
3 => Some(Self::InvalidArgument),
4 => Some(Self::DeadlineExceeded),
5 => Some(Self::NotFound),
6 => Some(Self::AlreadyExists),
7 => Some(Self::PermissionDenied),
8 => Some(Self::ResourceExhausted),
9 => Some(Self::FailedPrecondition),
10 => Some(Self::Aborted),
11 => Some(Self::OutOfRange),
12 => Some(Self::Unimplemented),
13 => Some(Self::Internal),
14 => Some(Self::Unavailable),
15 => Some(Self::DataLoss),
16 => Some(Self::Unauthenticated),
_ => None,
}
}
}
impl std::str::FromStr for ErrorCode {
type Err = ();
/// Parse an error code from a string.
///
/// Returns `Err(())` if the string doesn't match any known error code.
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"canceled" => Ok(Self::Canceled),
"unknown" => Ok(Self::Unknown),
"invalid_argument" => Ok(Self::InvalidArgument),
"deadline_exceeded" => Ok(Self::DeadlineExceeded),
"not_found" => Ok(Self::NotFound),
"already_exists" => Ok(Self::AlreadyExists),
"permission_denied" => Ok(Self::PermissionDenied),
"resource_exhausted" => Ok(Self::ResourceExhausted),
"failed_precondition" => Ok(Self::FailedPrecondition),
"aborted" => Ok(Self::Aborted),
"out_of_range" => Ok(Self::OutOfRange),
"unimplemented" => Ok(Self::Unimplemented),
"internal" => Ok(Self::Internal),
"unavailable" => Ok(Self::Unavailable),
"data_loss" => Ok(Self::DataLoss),
"unauthenticated" => Ok(Self::Unauthenticated),
_ => Err(()),
}
}
}
/// Additional error details that can be attached to a ConnectRPC error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorDetail {
/// The type URL for this detail.
/// Named `type` per Connect protocol (distinct from protobuf JSON `@type`).
#[serde(rename = "type")]
pub type_url: String,
/// Base64-encoded protobuf message.
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
/// Debug information (JSON representation).
#[serde(skip_serializing_if = "Option::is_none")]
pub debug: Option<serde_json::Value>,
}
/// A ConnectRPC error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectError {
/// The error code.
pub code: ErrorCode,
/// Human-readable error message.
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// Additional error details.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub details: Vec<ErrorDetail>,
/// Optional HTTP status override (not serialized).
/// When set, this overrides the default HTTP status for the error code.
#[serde(skip)]
http_status_override: Option<StatusCode>,
/// Response headers to include in error response (not serialized).
#[serde(skip)]
pub response_headers: http::HeaderMap,
/// Response trailers to include in error response (not serialized).
#[serde(skip)]
pub trailers: http::HeaderMap,
}
impl ConnectError {
/// Create a new error with the given code and message.
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: Some(message.into()),
details: Vec::new(),
http_status_override: None,
response_headers: http::HeaderMap::new(),
trailers: http::HeaderMap::new(),
}
}
/// Add response headers to be included in the error response.
#[must_use]
pub fn with_headers(mut self, headers: http::HeaderMap) -> Self {
self.response_headers = headers;
self
}
/// Add response trailers to be included in the error response.
#[must_use]
pub fn with_trailers(mut self, trailers: http::HeaderMap) -> Self {
self.trailers = trailers;
self
}
/// Set an HTTP status override for this error.
///
/// When set, this overrides the default HTTP status derived from the error code.
/// This is useful for HTTP-level errors like 415 Unsupported Media Type.
#[must_use]
pub fn with_http_status(mut self, status: StatusCode) -> Self {
self.http_status_override = Some(status);
self
}
/// Create an error for unsupported media type (HTTP 415).
///
/// This is used when the client sends a content type that the server doesn't support.
pub fn unsupported_media_type(message: impl Into<String>) -> Self {
// Connect protocol specifies Unknown for unsupported content types
Self::new(ErrorCode::Unknown, message).with_http_status(StatusCode::UNSUPPORTED_MEDIA_TYPE)
}
/// Create an error for method not allowed (HTTP 405).
///
/// This is used when the client uses an HTTP method other than POST.
pub fn method_not_allowed(message: impl Into<String>) -> Self {
// Connect protocol specifies Unknown for wrong HTTP method
Self::new(ErrorCode::Unknown, message).with_http_status(StatusCode::METHOD_NOT_ALLOWED)
}
/// Create a canceled error.
#[inline]
pub fn canceled(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Canceled, message)
}
/// Create an unknown error.
#[inline]
pub fn unknown(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unknown, message)
}
/// Create an invalid argument error.
#[inline]
pub fn invalid_argument(message: impl Into<String>) -> Self {
Self::new(ErrorCode::InvalidArgument, message)
}
/// Create a deadline exceeded error.
#[inline]
pub fn deadline_exceeded(message: impl Into<String>) -> Self {
Self::new(ErrorCode::DeadlineExceeded, message)
}
/// Create a not found error.
#[inline]
pub fn not_found(message: impl Into<String>) -> Self {
Self::new(ErrorCode::NotFound, message)
}
/// Create an already exists error.
#[inline]
pub fn already_exists(message: impl Into<String>) -> Self {
Self::new(ErrorCode::AlreadyExists, message)
}
/// Create a permission denied error.
#[inline]
pub fn permission_denied(message: impl Into<String>) -> Self {
Self::new(ErrorCode::PermissionDenied, message)
}
/// Create a resource exhausted error.
#[inline]
pub fn resource_exhausted(message: impl Into<String>) -> Self {
Self::new(ErrorCode::ResourceExhausted, message)
}
/// Create a failed precondition error.
#[inline]
pub fn failed_precondition(message: impl Into<String>) -> Self {
Self::new(ErrorCode::FailedPrecondition, message)
}
/// Create an aborted error.
#[inline]
pub fn aborted(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Aborted, message)
}
/// Create an out of range error.
#[inline]
pub fn out_of_range(message: impl Into<String>) -> Self {
Self::new(ErrorCode::OutOfRange, message)
}
/// Create an unimplemented error.
#[inline]
pub fn unimplemented(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unimplemented, message)
}
/// Create an internal error.
#[inline]
pub fn internal(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Internal, message)
}
/// Create an unavailable error.
#[inline]
pub fn unavailable(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unavailable, message)
}
/// Create a data loss error.
#[inline]
pub fn data_loss(message: impl Into<String>) -> Self {
Self::new(ErrorCode::DataLoss, message)
}
/// Create an unauthenticated error.
#[inline]
pub fn unauthenticated(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unauthenticated, message)
}
/// Add an error detail.
#[must_use]
pub fn with_detail(mut self, detail: ErrorDetail) -> Self {
self.details.push(detail);
self
}
/// Get the HTTP status code for this error.
///
/// Returns the HTTP status override if set, otherwise derives it from the error code.
pub fn http_status(&self) -> StatusCode {
self.http_status_override
.unwrap_or_else(|| self.code.http_status())
}
/// Encode this error as JSON bytes.
pub fn to_json(&self) -> Bytes {
Bytes::from(serde_json::to_vec(self).unwrap_or_else(|_| {
// Fallback: produce minimal valid Connect error JSON.
format!(r#"{{"code":"{}"}}"#, self.code.as_str()).into_bytes()
}))
}
}
impl std::fmt::Display for ConnectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.code.as_str())?;
if let Some(ref message) = self.message {
write!(f, ": {message}")?;
}
Ok(())
}
}
impl std::error::Error for ConnectError {}
impl From<std::io::Error> for ConnectError {
fn from(err: std::io::Error) -> Self {
Self::internal(err.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_grpc_code_round_trip() {
let codes = [
ErrorCode::Canceled,
ErrorCode::Unknown,
ErrorCode::InvalidArgument,
ErrorCode::DeadlineExceeded,
ErrorCode::NotFound,
ErrorCode::AlreadyExists,
ErrorCode::PermissionDenied,
ErrorCode::ResourceExhausted,
ErrorCode::FailedPrecondition,
ErrorCode::Aborted,
ErrorCode::OutOfRange,
ErrorCode::Unimplemented,
ErrorCode::Internal,
ErrorCode::Unavailable,
ErrorCode::DataLoss,
ErrorCode::Unauthenticated,
];
for code in codes {
let grpc = code.grpc_code();
let back = ErrorCode::from_grpc_code(grpc);
assert_eq!(
back,
Some(code),
"round-trip failed for {code:?} (grpc code {grpc})"
);
}
}
#[test]
fn test_grpc_code_values() {
assert_eq!(ErrorCode::Canceled.grpc_code(), 1);
assert_eq!(ErrorCode::Unknown.grpc_code(), 2);
assert_eq!(ErrorCode::Internal.grpc_code(), 13);
assert_eq!(ErrorCode::Unauthenticated.grpc_code(), 16);
}
#[test]
fn test_from_grpc_code_ok_returns_none() {
assert_eq!(ErrorCode::from_grpc_code(0), None);
}
#[test]
fn test_from_grpc_code_unknown_returns_none() {
assert_eq!(ErrorCode::from_grpc_code(17), None);
assert_eq!(ErrorCode::from_grpc_code(999), None);
}
}