1use crate::authz::AuthzError;
11use crate::fork::ForkError;
12use crate::graph::GraphError;
13use crate::kv::KvError;
14use crate::query::QueryError;
15use crate::session::SessionError;
16use serde::{Deserialize, Serialize};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[serde(rename_all = "snake_case")]
24#[non_exhaustive]
25pub enum ResultCode {
26 Ok,
28 Unsupported,
30 NotFound,
32 InvalidArgument,
34 TooLarge,
36 Conflict,
39 Stale,
42 VersionSkew,
44 Unauthenticated,
46 Backend,
48 Forbidden,
50 StepUpRequired,
53 Unavailable,
61 ResourceLimit,
63 Cancelled,
65 DeadlineExceeded,
67 ExpiredSnapshot,
69 StaleGeneration,
71 TargetUnavailable,
73 Pending,
78 BackendUnavailable,
82 Unrecognized(u16),
88}
89
90impl ResultCode {
91 pub const fn code(self) -> u16 {
93 match self {
94 ResultCode::Ok => 0,
95 ResultCode::Unsupported => 1,
96 ResultCode::NotFound => 2,
97 ResultCode::InvalidArgument => 3,
98 ResultCode::TooLarge => 4,
99 ResultCode::Conflict => 5,
100 ResultCode::Stale => 6,
101 ResultCode::VersionSkew => 7,
102 ResultCode::Unauthenticated => 8,
103 ResultCode::Backend => 9,
104 ResultCode::Forbidden => 10,
105 ResultCode::StepUpRequired => 11,
106 ResultCode::Unavailable => 12,
107 ResultCode::ResourceLimit => 13,
108 ResultCode::Cancelled => 14,
109 ResultCode::DeadlineExceeded => 15,
110 ResultCode::ExpiredSnapshot => 16,
111 ResultCode::StaleGeneration => 17,
112 ResultCode::TargetUnavailable => 18,
113 ResultCode::Pending => 19,
114 ResultCode::BackendUnavailable => 20,
115 ResultCode::Unrecognized(code) => code,
116 }
117 }
118
119 pub const fn from_code(code: u16) -> Self {
122 match code {
123 0 => ResultCode::Ok,
124 1 => ResultCode::Unsupported,
125 2 => ResultCode::NotFound,
126 3 => ResultCode::InvalidArgument,
127 4 => ResultCode::TooLarge,
128 5 => ResultCode::Conflict,
129 6 => ResultCode::Stale,
130 7 => ResultCode::VersionSkew,
131 8 => ResultCode::Unauthenticated,
132 9 => ResultCode::Backend,
133 10 => ResultCode::Forbidden,
134 11 => ResultCode::StepUpRequired,
135 12 => ResultCode::Unavailable,
136 13 => ResultCode::ResourceLimit,
137 14 => ResultCode::Cancelled,
138 15 => ResultCode::DeadlineExceeded,
139 16 => ResultCode::ExpiredSnapshot,
140 17 => ResultCode::StaleGeneration,
141 18 => ResultCode::TargetUnavailable,
142 19 => ResultCode::Pending,
143 20 => ResultCode::BackendUnavailable,
144 other => ResultCode::Unrecognized(other),
145 }
146 }
147
148 pub const fn http_status(self) -> u16 {
151 match self {
152 ResultCode::Ok => 200,
153 ResultCode::Unsupported => 501,
154 ResultCode::NotFound => 404,
155 ResultCode::InvalidArgument => 400,
156 ResultCode::TooLarge => 413,
157 ResultCode::Conflict => 409,
158 ResultCode::Stale => 503,
159 ResultCode::VersionSkew => 400,
160 ResultCode::Unauthenticated => 401,
161 ResultCode::Backend => 502,
162 ResultCode::Forbidden => 403,
166 ResultCode::StepUpRequired => 403,
167 ResultCode::Unavailable => 503,
169 ResultCode::ResourceLimit => 429,
170 ResultCode::Cancelled => 409,
171 ResultCode::DeadlineExceeded => 408,
172 ResultCode::ExpiredSnapshot => 410,
173 ResultCode::StaleGeneration => 409,
174 ResultCode::TargetUnavailable => 503,
175 ResultCode::Pending => 503,
178 ResultCode::BackendUnavailable => 503,
179 ResultCode::Unrecognized(_) => 500,
180 }
181 }
182
183 pub const fn is_retryable(self) -> bool {
191 matches!(
192 self,
193 ResultCode::Unavailable
194 | ResultCode::Stale
195 | ResultCode::TargetUnavailable
196 | ResultCode::BackendUnavailable
197 )
198 }
199
200 pub const fn is_unavailable(self) -> bool {
204 matches!(
205 self,
206 ResultCode::Unavailable
207 | ResultCode::TargetUnavailable
208 | ResultCode::BackendUnavailable
209 )
210 }
211
212 pub const fn is_permission_denied(self) -> bool {
216 matches!(self, ResultCode::Forbidden | ResultCode::Unauthenticated)
217 }
218
219 pub const fn is_pending(self) -> bool {
222 matches!(self, ResultCode::Pending)
223 }
224
225 pub const fn is_backend_unavailable(self) -> bool {
232 matches!(self, ResultCode::BackendUnavailable)
233 }
234}
235
236#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
247#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
248pub struct CommandError {
249 pub code: ResultCode,
250 pub message: String,
251}
252
253impl CommandError {
254 pub fn new(code: ResultCode, message: impl Into<String>) -> Self {
256 Self {
257 code,
258 message: message.into(),
259 }
260 }
261
262 pub fn unsupported(message: impl Into<String>) -> Self {
264 Self::new(ResultCode::Unsupported, message)
265 }
266}
267
268impl From<&QueryError> for ResultCode {
269 fn from(error: &QueryError) -> Self {
270 match error {
271 QueryError::Unsupported(_) => ResultCode::Unsupported,
272 QueryError::Invalid(_) => ResultCode::InvalidArgument,
273 QueryError::Unauthorized(_) => ResultCode::Forbidden,
276 QueryError::IndexNotFound(_)
277 | QueryError::ForkNotFound(_)
278 | QueryError::SchemaNotFound(_) => ResultCode::NotFound,
279 QueryError::Backend(_) => ResultCode::Backend,
280 QueryError::Unavailable(_) => ResultCode::Unavailable,
281 QueryError::TooLarge { .. } => ResultCode::TooLarge,
282 QueryError::Version { .. } => ResultCode::VersionSkew,
283 QueryError::Stale { .. } => ResultCode::Stale,
284 QueryError::DeadlineExceeded { .. } => ResultCode::DeadlineExceeded,
285 QueryError::StaleGeneration { .. } => ResultCode::StaleGeneration,
286 }
287 }
288}
289
290impl From<&KvError> for ResultCode {
291 fn from(error: &KvError) -> Self {
292 match error {
293 KvError::Unsupported(_) => ResultCode::Unsupported,
294 KvError::InvalidKey(_) => ResultCode::InvalidArgument,
295 KvError::InvalidNamespace(_) => ResultCode::InvalidArgument,
296 KvError::TooLarge { .. } => ResultCode::TooLarge,
297 KvError::Backend(_) => ResultCode::Backend,
298 KvError::Unavailable(_) => ResultCode::Unavailable,
299 KvError::Version { .. } => ResultCode::VersionSkew,
300 KvError::VersionConflict { .. } => ResultCode::Conflict,
301 KvError::LeaseLost => ResultCode::Conflict,
302 KvError::LeaseHeld { .. } => ResultCode::Conflict,
303 KvError::BarrierUnreachable { .. } => ResultCode::StaleGeneration,
304 KvError::NotFound => ResultCode::NotFound,
305 KvError::NotLeader => ResultCode::Unavailable,
306 KvError::Stale { .. } => ResultCode::Stale,
307 KvError::Forbidden(_) => ResultCode::Forbidden,
308 KvError::InvalidExpiry(_) => ResultCode::InvalidArgument,
309 }
310 }
311}
312
313impl From<&ForkError> for ResultCode {
314 fn from(error: &ForkError) -> Self {
315 match error {
316 ForkError::Unsupported(_) => ResultCode::Unsupported,
317 ForkError::NotFound(_) => ResultCode::NotFound,
318 ForkError::InvalidFork(_) => ResultCode::InvalidArgument,
319 ForkError::Conflict(_) => ResultCode::Conflict,
320 ForkError::Backend(_) => ResultCode::Backend,
321 ForkError::Unavailable(_) => ResultCode::Unavailable,
322 ForkError::Version { .. } => ResultCode::VersionSkew,
323 ForkError::NotLeader => ResultCode::Unavailable,
324 }
325 }
326}
327
328impl From<&GraphError> for ResultCode {
329 fn from(error: &GraphError) -> Self {
330 match error {
331 GraphError::Unsupported(_) => ResultCode::Unsupported,
332 GraphError::Unauthorized(_) => ResultCode::Forbidden,
333 GraphError::InvalidName(_) => ResultCode::InvalidArgument,
334 GraphError::NotFound(_) => ResultCode::NotFound,
335 GraphError::TooLarge { .. } => ResultCode::TooLarge,
336 GraphError::Backend(_) => ResultCode::Backend,
337 GraphError::Unavailable(_) => ResultCode::Unavailable,
338 GraphError::Version { .. } => ResultCode::VersionSkew,
339 }
340 }
341}
342
343impl From<&AuthzError> for ResultCode {
344 fn from(error: &AuthzError) -> Self {
345 match error {
346 AuthzError::Unsupported(_) => ResultCode::Unsupported,
347 AuthzError::Unauthorized => ResultCode::Forbidden,
348 AuthzError::UnknownRole(_) => ResultCode::NotFound,
349 AuthzError::InvalidName(_)
350 | AuthzError::InvalidGrant(_)
351 | AuthzError::TenancyViolation(_) => ResultCode::InvalidArgument,
352 AuthzError::Conflict { .. } | AuthzError::MutationConflict(_) => ResultCode::Conflict,
353 AuthzError::Version { .. } => ResultCode::VersionSkew,
354 AuthzError::ResourceLimit(_) => ResultCode::ResourceLimit,
355 }
356 }
357}
358
359impl From<&SessionError> for ResultCode {
360 fn from(error: &SessionError) -> Self {
361 match error {
362 SessionError::Unsupported(_) => ResultCode::Unsupported,
363 SessionError::NotFound(_) | SessionError::NotRegistered(_) => ResultCode::NotFound,
364 SessionError::Invalid(_) => ResultCode::InvalidArgument,
365 SessionError::Unauthorized(_) => ResultCode::Forbidden,
366 SessionError::Stale(_) => ResultCode::StaleGeneration,
367 SessionError::Backend(_) => ResultCode::Backend,
368 SessionError::Unavailable(_) => ResultCode::Unavailable,
369 }
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376
377 #[test]
378 fn given_result_codes_when_mapped_then_should_round_trip_through_the_numeric_value() {
379 for code in [
380 ResultCode::Ok,
381 ResultCode::Unsupported,
382 ResultCode::NotFound,
383 ResultCode::InvalidArgument,
384 ResultCode::TooLarge,
385 ResultCode::Conflict,
386 ResultCode::Stale,
387 ResultCode::VersionSkew,
388 ResultCode::Unauthenticated,
389 ResultCode::Backend,
390 ResultCode::Forbidden,
391 ResultCode::StepUpRequired,
392 ResultCode::Unavailable,
393 ResultCode::TargetUnavailable,
394 ResultCode::Pending,
395 ResultCode::BackendUnavailable,
396 ] {
397 assert_eq!(ResultCode::from_code(code.code()), code);
398 }
399 assert_eq!(ResultCode::Pending.code(), 19);
400 assert_eq!(ResultCode::BackendUnavailable.code(), 20);
401 assert!(ResultCode::BackendUnavailable.is_retryable());
402 assert!(ResultCode::BackendUnavailable.is_backend_unavailable());
403 assert!(!ResultCode::Unavailable.is_backend_unavailable());
404 assert_eq!(ResultCode::from_code(21), ResultCode::Unrecognized(21));
405 assert_eq!(ResultCode::from_code(900), ResultCode::Unrecognized(900));
407 assert_eq!(ResultCode::Unrecognized(900).code(), 900);
408 }
409
410 #[test]
411 fn given_surface_errors_when_classified_then_should_map_to_the_shared_code() {
412 assert_eq!(
413 ResultCode::from(&QueryError::IndexNotFound("readings".to_owned())),
414 ResultCode::NotFound
415 );
416 assert_eq!(
417 ResultCode::from(&QueryError::Stale {
418 what: "readings".to_owned(),
419 applied: 4,
420 required: 9,
421 }),
422 ResultCode::Stale
423 );
424 assert_eq!(
425 ResultCode::from(&KvError::VersionConflict { current: Some(3) }),
426 ResultCode::Conflict
427 );
428 assert_eq!(
429 ResultCode::from(&ForkError::Conflict("open".to_owned())),
430 ResultCode::Conflict
431 );
432 assert_eq!(
433 ResultCode::from(&KvError::NotLeader),
434 ResultCode::Unavailable
435 );
436 assert_eq!(
437 ResultCode::from(&ForkError::NotLeader),
438 ResultCode::Unavailable
439 );
440 assert_eq!(
441 ResultCode::from(&AuthzError::TenancyViolation("prefix acme".to_owned())),
442 ResultCode::InvalidArgument
443 );
444 assert_eq!(
445 ResultCode::from(&AuthzError::Unauthorized),
446 ResultCode::Forbidden
447 );
448 }
449
450 #[test]
453 fn given_one_condition_on_every_surface_when_classified_then_should_share_one_code() {
454 let text = || "x".to_owned();
455 let table: [(ResultCode, Vec<ResultCode>); 6] = [
456 (
457 ResultCode::InvalidArgument,
458 vec![
459 ResultCode::from(&KvError::InvalidKey(text())),
460 ResultCode::from(&KvError::InvalidNamespace(text())),
461 ResultCode::from(&ForkError::InvalidFork(text())),
462 ResultCode::from(&GraphError::InvalidName(text())),
463 ResultCode::from(&AuthzError::InvalidName(text())),
464 ResultCode::from(&AuthzError::InvalidGrant(text())),
465 ResultCode::from(&SessionError::Invalid(text())),
466 ResultCode::from(&QueryError::Invalid(text())),
467 ],
468 ),
469 (
470 ResultCode::Forbidden,
471 vec![
472 ResultCode::from(&QueryError::Unauthorized(text())),
473 ResultCode::from(&GraphError::Unauthorized(text())),
474 ResultCode::from(&AuthzError::Unauthorized),
475 ResultCode::from(&SessionError::Unauthorized(text())),
476 ],
477 ),
478 (
479 ResultCode::NotFound,
480 vec![
481 ResultCode::from(&QueryError::IndexNotFound(text())),
482 ResultCode::from(&KvError::NotFound),
483 ResultCode::from(&ForkError::NotFound(text())),
484 ResultCode::from(&GraphError::NotFound(text())),
485 ResultCode::from(&AuthzError::UnknownRole(text())),
486 ResultCode::from(&SessionError::NotFound(text())),
487 ],
488 ),
489 (
490 ResultCode::Unavailable,
491 vec![
492 ResultCode::from(&QueryError::Unavailable(text())),
493 ResultCode::from(&KvError::Unavailable(text())),
494 ResultCode::from(&ForkError::Unavailable(text())),
495 ResultCode::from(&GraphError::Unavailable(text())),
496 ResultCode::from(&SessionError::Unavailable(text())),
497 ],
498 ),
499 (
500 ResultCode::Unsupported,
501 vec![
502 ResultCode::from(&QueryError::Unsupported(text())),
503 ResultCode::from(&KvError::Unsupported(text())),
504 ResultCode::from(&ForkError::Unsupported(text())),
505 ResultCode::from(&GraphError::Unsupported(text())),
506 ResultCode::from(&AuthzError::Unsupported(text())),
507 ResultCode::from(&SessionError::Unsupported(text())),
508 ],
509 ),
510 (
511 ResultCode::Backend,
512 vec![
513 ResultCode::from(&QueryError::Backend(text())),
514 ResultCode::from(&KvError::Backend(text())),
515 ResultCode::from(&ForkError::Backend(text())),
516 ResultCode::from(&GraphError::Backend(text())),
517 ResultCode::from(&SessionError::Backend(text())),
518 ],
519 ),
520 ];
521 for (expected, codes) in table {
522 for (surface, code) in codes.into_iter().enumerate() {
523 assert_eq!(code, expected, "surface {surface} of {expected:?}");
524 }
525 assert!(
526 !expected.is_retryable() || expected == ResultCode::Unavailable,
527 "only unavailable is retryable among these"
528 );
529 }
530 }
531
532 #[test]
535 fn given_transient_outcomes_when_classified_then_should_be_the_only_retryable_codes() {
536 for surface in [
537 ResultCode::from(&QueryError::Unavailable("dropped".to_owned())),
538 ResultCode::from(&KvError::Unavailable("dropped".to_owned())),
539 ResultCode::from(&ForkError::Unavailable("dropped".to_owned())),
540 ] {
541 assert_eq!(surface, ResultCode::Unavailable);
542 }
543 assert_eq!(ResultCode::Unavailable.http_status(), 503);
544 assert!(ResultCode::Unavailable.is_retryable());
545 assert!(ResultCode::Stale.is_retryable());
546 for code in [
547 ResultCode::Ok,
548 ResultCode::Unsupported,
549 ResultCode::NotFound,
550 ResultCode::InvalidArgument,
551 ResultCode::TooLarge,
552 ResultCode::Conflict,
553 ResultCode::VersionSkew,
554 ResultCode::Unauthenticated,
555 ResultCode::Backend,
556 ResultCode::Forbidden,
557 ResultCode::StepUpRequired,
558 ResultCode::Pending,
559 ResultCode::Unrecognized(900),
560 ] {
561 assert!(
562 !code.is_retryable(),
563 "{code:?} must not invite a blind retry"
564 );
565 }
566 }
567
568 #[test]
569 fn given_result_codes_when_mapped_to_http_then_should_match_the_binding_table() {
570 assert_eq!(ResultCode::NotFound.http_status(), 404);
571 assert_eq!(ResultCode::Unsupported.http_status(), 501);
572 assert_eq!(ResultCode::TooLarge.http_status(), 413);
573 assert_eq!(ResultCode::Conflict.http_status(), 409);
574 assert_eq!(ResultCode::Stale.http_status(), 503);
575 assert_eq!(ResultCode::Unauthenticated.http_status(), 401);
576 assert_eq!(ResultCode::Forbidden.http_status(), 403);
577 assert_eq!(ResultCode::StepUpRequired.http_status(), 403);
578 assert_eq!(ResultCode::Backend.http_status(), 502);
579 assert_eq!(ResultCode::Unrecognized(777).http_status(), 500);
582 assert_eq!(ResultCode::Unrecognized(777).code(), 777);
583 }
584
585 #[cfg(feature = "cbor")]
586 #[test]
587 fn given_a_result_code_when_round_tripped_through_cbor_then_should_preserve_the_variant() {
588 use crate::framing::{decode_named, encode_named};
589 for code in [
590 ResultCode::Ok,
591 ResultCode::Conflict,
592 ResultCode::Stale,
593 ResultCode::Unrecognized(4242),
594 ] {
595 let bytes = encode_named(&code).expect("serializes");
596 let back: ResultCode = decode_named(&bytes).expect("deserializes");
597 assert_eq!(back, code);
598 }
599 }
600
601 #[test]
602 fn given_backend_unavailable_when_serialized_then_should_use_the_backend_unavailable_string() {
603 let json = serde_json::to_string(&ResultCode::BackendUnavailable).expect("serializes");
604 assert_eq!(json, "\"backend_unavailable\"");
605 let back: ResultCode =
606 serde_json::from_str("\"backend_unavailable\"").expect("deserializes");
607 assert_eq!(back, ResultCode::BackendUnavailable);
608 }
609
610 #[cfg(feature = "cbor")]
611 #[test]
612 fn given_a_command_error_when_round_tripped_then_should_preserve_code_and_message() {
613 use crate::framing::{decode_named, encode_named};
614 let error = CommandError::unsupported("AGDX_KV_CAS not served on this build");
615 assert_eq!(error.code, ResultCode::Unsupported);
616 let bytes = encode_named(&error).expect("serializes");
617 let back: CommandError = decode_named(&bytes).expect("deserializes");
618 assert_eq!(back, error);
619 }
620}