Skip to main content

loonfs_api/
error.rs

1//! The wire error registry: every stable machine-readable error code and
2//! its caller-action category.
3
4use std::fmt;
5
6/// Broad error category for caller or operator action.
7///
8/// Each kind implies one served HTTP status (`status_for_error_kind` in
9/// `loonfs-server`); a code's kind and its documented status in the API spec
10/// must agree in spirit, and the server's spec-table sync test enforces the
11/// composition exactly.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum ErrorKind {
15    /// Fix the request before retrying.
16    InvalidRequest,
17    /// The request was not authorized. Fix credentials before retrying.
18    Unauthorized,
19    /// The request body exceeds the deployment's size limit for this
20    /// operation. Send a smaller payload (for uploads, prefer `direct_put`);
21    /// retrying unchanged will not succeed.
22    ContentTooLarge,
23    /// The caller may not perform this operation. Request access; retrying
24    /// unchanged will not succeed.
25    PermissionDenied,
26    /// The deployment does not implement this operation. Gate on the
27    /// capability document instead of retrying.
28    NotSupported,
29    /// The requested object does not exist. Refresh state or choose another target.
30    NotFound,
31    /// The path routes somewhere, but not for this HTTP method. Fix the
32    /// request; retrying unchanged will not succeed.
33    MethodNotAllowed,
34    /// The target was deleted and its id is permanently retired. Do not
35    /// retry; choose another target.
36    Gone,
37    /// The create target already exists. Pick another id or treat this as idempotent.
38    AlreadyExists,
39    /// The request raced with current namespace state, or a caller-supplied
40    /// precondition (base revision, expected head) no longer holds. Re-read
41    /// fresh state, re-plan, and retry if desired.
42    Conflict,
43    /// The server cancelled work that exceeded its configured request
44    /// deadline. Reconcile any mutation before deciding whether to retry.
45    DeadlineExceeded,
46    /// Status grouping for conditions served as unavailable.
47    ///
48    /// This kind is not a retry predicate: some grouped conditions require
49    /// maintenance before another attempt can succeed. Use
50    /// [`ErrorCode::retryable_without_operator_action`] for that decision.
51    Unavailable,
52    /// The operation may have committed: its acknowledgment was lost. Retry
53    /// with the same commit id or reconcile against namespace state; do not
54    /// assume failure.
55    OutcomeUnknown,
56    /// Durable state is malformed. Treat this as operator or repair work.
57    DataCorruption,
58    /// LoonFS hit an internal failure. Capture details and report it.
59    Internal,
60}
61
62/// Declares the complete wire error-code registry in one place.
63///
64/// One `Variant => "wire_string"` line emits the enum variant, its
65/// [`ErrorCode::ALL`] entry (in registry order), its `as_str` arm, its
66/// `parse` arm, and the string-backed serde impls — so registering a new
67/// code is one line here plus a [`ErrorCode::kind`] arm and an api.md row.
68macro_rules! error_codes {
69    (@count) => { 0 };
70    (@count $head:ident $($tail:ident)*) => { 1 + error_codes!(@count $($tail)*) };
71    ($($variant:ident => $wire:literal),+ $(,)?) => {
72        /// Stable machine-readable error reason.
73        ///
74        /// This is the complete registry of `code` values carried by
75        /// [`ApiError`](crate::ApiError) bodies and embedded errors. Codes are
76        /// permanent once released: the API spec documents each code's meaning and HTTP
77        /// status, and clients must tolerate codes they do not recognize.
78        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
79        #[non_exhaustive]
80        pub enum ErrorCode {
81            $(
82                #[doc = concat!("Carries the stable wire code `", $wire, "`.")]
83                $variant,
84            )+
85        }
86
87        impl ErrorCode {
88            /// Every registered code, in registry order.
89            pub const ALL: [ErrorCode; error_codes!(@count $($variant)+)] =
90                [$(ErrorCode::$variant,)+];
91
92            /// Returns the stable wire string for this code.
93            pub fn as_str(self) -> &'static str {
94                match self {
95                    $(ErrorCode::$variant => $wire,)+
96                }
97            }
98
99            /// Parses a registered code string, returning `None` for codes this
100            /// build does not know (clients must tolerate those).
101            pub fn parse(value: &str) -> Option<ErrorCode> {
102                match value {
103                    $($wire => Some(ErrorCode::$variant),)+
104                    _ => None,
105                }
106            }
107        }
108
109        impl serde::Serialize for ErrorCode {
110            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
111                serializer.serialize_str(self.as_str())
112            }
113        }
114
115        impl<'de> serde::Deserialize<'de> for ErrorCode {
116            // Strict: unknown codes fail to deserialize. Wire structs carry
117            // codes as plain strings (`ApiError::code`) precisely so unknown
118            // codes stay tolerated; deserialize into `ErrorCode` only where
119            // strictness is intended.
120            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
121                let value = String::deserialize(deserializer)?;
122                ErrorCode::parse(&value).ok_or_else(|| {
123                    serde::de::Error::custom(format_args!("unknown error code `{value}`"))
124                })
125            }
126        }
127    };
128}
129
130error_codes! {
131    InvalidRequest => "invalid_request",
132    Unauthorized => "unauthorized",
133    PermissionDenied => "permission_denied",
134    ContentTooLarge => "content_too_large",
135    NotSupported => "not_supported",
136    RouteNotFound => "route_not_found",
137    MethodNotAllowed => "method_not_allowed",
138    NamespaceNotFound => "namespace_not_found",
139    NamespaceDeleted => "namespace_deleted",
140    NamespaceExists => "namespace_exists",
141    ContentNotPrepared => "content_not_prepared",
142    PathNotFound => "path_not_found",
143    InodeNotFound => "inode_not_found",
144    RevisionNotFound => "revision_not_found",
145    PathConflict => "path_conflict",
146    DirectoryNotEmpty => "directory_not_empty",
147    StaleHead => "stale_head",
148    StaleRevision => "stale_revision",
149    StaleAttributes => "stale_attributes",
150    NotDeleted => "not_deleted",
151    WriterFenced => "writer_fenced",
152    WouldCycle => "would_cycle",
153    CommitIdReuseConflict => "commit_id_reuse_conflict",
154    CommitOutcomeUnknown => "commit_outcome_unknown",
155    CommitQueueFull => "commit_queue_full",
156    ServerBusy => "server_busy",
157    ShuttingDown => "shutting_down",
158    DeadlineExceeded => "deadline_exceeded",
159    CheckpointUnavailable => "checkpoint_unavailable",
160    MaintenanceRequired => "maintenance_required",
161    UploadNotFound => "upload_not_found",
162    UploadAlreadyCompleted => "upload_already_completed",
163    UploadContentConflict => "upload_content_conflict",
164    RebootstrapRequired => "rebootstrap_required",
165    QueryUnindexable => "query_unindexable",
166    IndexLagging => "index_lagging",
167    IndexCorrupt => "index_corrupt",
168    NamespaceCorrupt => "namespace_corrupt",
169    ServerError => "server_error",
170}
171
172impl ErrorCode {
173    /// Returns the caller-action category for this code.
174    ///
175    /// The kind agrees with the HTTP status the api.md error table documents
176    /// for the code; the server derives the served status from it.
177    pub fn kind(self) -> ErrorKind {
178        match self {
179            // A pattern with no required grams is a property of the request,
180            // not the namespace: the caller rewrites the pattern or opts
181            // into a capped scan.
182            ErrorCode::InvalidRequest | ErrorCode::QueryUnindexable => ErrorKind::InvalidRequest,
183            ErrorCode::Unauthorized => ErrorKind::Unauthorized,
184            // Produced when the backing object store rejects the
185            // deployment's credentials: operator-actionable and never
186            // transient, exactly the kind's contract.
187            ErrorCode::PermissionDenied => ErrorKind::PermissionDenied,
188            ErrorCode::ContentTooLarge => ErrorKind::ContentTooLarge,
189            ErrorCode::NotSupported => ErrorKind::NotSupported,
190            ErrorCode::NamespaceNotFound
191            | ErrorCode::PathNotFound
192            | ErrorCode::InodeNotFound
193            | ErrorCode::RevisionNotFound
194            | ErrorCode::UploadNotFound
195            | ErrorCode::RouteNotFound => ErrorKind::NotFound,
196            ErrorCode::MethodNotAllowed => ErrorKind::MethodNotAllowed,
197            ErrorCode::NamespaceDeleted => ErrorKind::Gone,
198            ErrorCode::NamespaceExists => ErrorKind::AlreadyExists,
199            ErrorCode::DeadlineExceeded => ErrorKind::DeadlineExceeded,
200            ErrorCode::CommitQueueFull
201            | ErrorCode::ServerBusy
202            | ErrorCode::ShuttingDown
203            | ErrorCode::CheckpointUnavailable
204            | ErrorCode::IndexLagging
205            | ErrorCode::MaintenanceRequired => ErrorKind::Unavailable,
206            ErrorCode::CommitOutcomeUnknown => ErrorKind::OutcomeUnknown,
207            ErrorCode::IndexCorrupt | ErrorCode::NamespaceCorrupt => ErrorKind::DataCorruption,
208            ErrorCode::ServerError => ErrorKind::Internal,
209            // The spec deliberately surfaces precondition failures
210            // (`stale_revision`, `stale_head`, `commit_id_reuse_conflict`) as
211            // 409 resource-state conflicts, not 412 (api.md, "Standard error
212            // contract").
213            ErrorCode::ContentNotPrepared
214            | ErrorCode::PathConflict
215            | ErrorCode::DirectoryNotEmpty
216            | ErrorCode::StaleHead
217            | ErrorCode::StaleRevision
218            // An attribute update was decided against a different attribute
219            // revision than the one it wrote from, whether the caller stated
220            // that revision or the update's own guard observed it.
221            | ErrorCode::StaleAttributes
222            // Undelete's target is not the root of a live deletion: a
223            // state conflict, resolved by re-reading namespace state.
224            | ErrorCode::NotDeleted
225            | ErrorCode::WriterFenced
226            | ErrorCode::WouldCycle
227            | ErrorCode::CommitIdReuseConflict
228            | ErrorCode::UploadAlreadyCompleted
229            | ErrorCode::UploadContentConflict
230            | ErrorCode::RebootstrapRequired => ErrorKind::Conflict,
231        }
232    }
233
234    /// Returns whether this condition can clear without caller or operator action.
235    ///
236    /// This predicate is deliberately narrower than [`ErrorKind::Unavailable`]:
237    /// it includes only admission pressure and shutdown handoff that settle on
238    /// their own. Transport failures are classified separately by clients.
239    /// Reconciliation, request changes, and maintenance are caller or operator
240    /// actions and therefore return `false` here.
241    pub fn retryable_without_operator_action(self) -> bool {
242        match self {
243            ErrorCode::CommitQueueFull | ErrorCode::ServerBusy | ErrorCode::ShuttingDown => true,
244            ErrorCode::InvalidRequest
245            | ErrorCode::Unauthorized
246            | ErrorCode::PermissionDenied
247            | ErrorCode::ContentTooLarge
248            | ErrorCode::NotSupported
249            | ErrorCode::RouteNotFound
250            | ErrorCode::MethodNotAllowed
251            | ErrorCode::NamespaceNotFound
252            | ErrorCode::NamespaceDeleted
253            | ErrorCode::NamespaceExists
254            | ErrorCode::ContentNotPrepared
255            | ErrorCode::PathNotFound
256            | ErrorCode::InodeNotFound
257            | ErrorCode::RevisionNotFound
258            | ErrorCode::PathConflict
259            | ErrorCode::DirectoryNotEmpty
260            | ErrorCode::StaleHead
261            | ErrorCode::StaleRevision
262            | ErrorCode::StaleAttributes
263            | ErrorCode::NotDeleted
264            | ErrorCode::WriterFenced
265            | ErrorCode::WouldCycle
266            | ErrorCode::CommitIdReuseConflict
267            | ErrorCode::CommitOutcomeUnknown
268            | ErrorCode::DeadlineExceeded
269            | ErrorCode::CheckpointUnavailable
270            | ErrorCode::MaintenanceRequired
271            | ErrorCode::UploadNotFound
272            | ErrorCode::UploadAlreadyCompleted
273            | ErrorCode::UploadContentConflict
274            | ErrorCode::RebootstrapRequired
275            | ErrorCode::QueryUnindexable
276            | ErrorCode::IndexLagging
277            | ErrorCode::IndexCorrupt
278            | ErrorCode::NamespaceCorrupt
279            | ErrorCode::ServerError => false,
280        }
281    }
282}
283
284impl fmt::Display for ErrorCode {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        f.write_str(self.as_str())
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::ErrorCode;
293
294    #[test]
295    fn error_codes_round_trip_through_their_strings() {
296        for code in ErrorCode::ALL {
297            assert_eq!(ErrorCode::parse(code.as_str()), Some(code));
298        }
299        assert_eq!(ErrorCode::parse("not_a_code"), None);
300    }
301
302    #[test]
303    fn error_codes_serde_uses_the_wire_strings() {
304        for code in ErrorCode::ALL {
305            let value = serde_json::to_value(code).expect("serialize error code");
306            assert_eq!(value, serde_json::Value::String(code.as_str().to_owned()));
307            let parsed: ErrorCode = serde_json::from_value(value).expect("deserialize error code");
308            assert_eq!(parsed, code);
309        }
310        assert!(serde_json::from_str::<ErrorCode>("\"not_a_code\"").is_err());
311    }
312
313    #[test]
314    fn retryability_is_limited_to_self_clearing_admission_conditions() {
315        let retryable: Vec<_> = ErrorCode::ALL
316            .into_iter()
317            .filter(|code| code.retryable_without_operator_action())
318            .collect();
319
320        assert_eq!(
321            retryable,
322            [
323                ErrorCode::CommitQueueFull,
324                ErrorCode::ServerBusy,
325                ErrorCode::ShuttingDown,
326            ]
327        );
328    }
329}