Skip to main content

fusen_register/
error.rs

1use std::{fmt, sync::Arc};
2use thiserror::Error;
3
4/// Registry operation that produced an error.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6#[non_exhaustive]
7pub enum RegistryOperation {
8    /// A provider rejected a registration before activation.
9    PrepareRegistration,
10    /// Publishing a prepared registration failed.
11    ActivateRegistration,
12    /// Removing a prepared registration failed.
13    CloseRegistration,
14    /// A provider rejected a subscription before activation.
15    PrepareSubscription,
16    /// Starting a prepared subscription failed.
17    ActivateSubscription,
18    /// Stopping a prepared subscription failed.
19    CloseSubscription,
20    /// Reading or publishing a directory snapshot failed.
21    Directory,
22}
23
24impl fmt::Display for RegistryOperation {
25    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26        formatter.write_str(match self {
27            Self::PrepareRegistration => "prepare registration",
28            Self::ActivateRegistration => "activate registration",
29            Self::CloseRegistration => "close registration",
30            Self::PrepareSubscription => "prepare subscription",
31            Self::ActivateSubscription => "activate subscription",
32            Self::CloseSubscription => "close subscription",
33            Self::Directory => "access directory",
34        })
35    }
36}
37
38/// Stable classification for registry failures.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum RegistryErrorKind {
42    /// The provider or its backing service is unavailable.
43    Unavailable,
44    /// A configured operation deadline elapsed.
45    Timeout,
46    /// The provider rejected the supplied credentials or identity.
47    Unauthorized,
48    /// A registration, selector, capability declaration, or endpoint is invalid.
49    InvalidResource,
50    /// The requested resource conflicts with existing provider state.
51    Conflict,
52    /// The operation was closed before activation completed.
53    Cancelled,
54    /// Provider cleanup ended without publishing a terminal result.
55    CleanupAborted,
56    /// An invariant, task, or provider implementation failed internally.
57    Internal,
58}
59
60impl RegistryErrorKind {
61    /// Returns whether a fresh provider operation may succeed without changing its input.
62    pub const fn is_retryable(self) -> bool {
63        matches!(self, Self::Unavailable | Self::Timeout)
64    }
65}
66
67impl fmt::Display for RegistryErrorKind {
68    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69        formatter.write_str(match self {
70            Self::Unavailable => "unavailable",
71            Self::Timeout => "timeout",
72            Self::Unauthorized => "unauthorized",
73            Self::InvalidResource => "invalid resource",
74            Self::Conflict => "conflict",
75            Self::Cancelled => "cancelled",
76            Self::CleanupAborted => "cleanup aborted",
77            Self::Internal => "internal",
78        })
79    }
80}
81
82/// Cloneable registry failure with stable operation and kind metadata.
83#[derive(Error, Clone)]
84#[non_exhaustive]
85#[error("registry {operation} failed ({kind}): {message}")]
86pub struct RegistryError {
87    operation: RegistryOperation,
88    kind: RegistryErrorKind,
89    message: Arc<str>,
90    #[source]
91    source: Arc<dyn std::error::Error + Send + Sync + 'static>,
92}
93
94impl RegistryError {
95    /// Creates a classified registry error while retaining its provider source.
96    pub fn new<E>(operation: RegistryOperation, kind: RegistryErrorKind, source: E) -> Self
97    where
98        E: std::error::Error + Send + Sync + 'static,
99    {
100        Self {
101            operation,
102            kind,
103            message: Arc::from(default_message(kind)),
104            source: Arc::new(source),
105        }
106    }
107
108    /// Creates a classified registry error from a safe public diagnostic message.
109    ///
110    /// The message is included in [`Debug`](fmt::Debug) and [`Display`](fmt::Display) output.
111    pub fn message(
112        operation: RegistryOperation,
113        kind: RegistryErrorKind,
114        message: impl Into<String>,
115    ) -> Self {
116        let message = message.into();
117        Self {
118            operation,
119            kind,
120            message: Arc::from(message.as_str()),
121            source: Arc::new(RegistryMessage(message)),
122        }
123    }
124
125    /// Returns the operation that failed.
126    pub const fn operation(&self) -> RegistryOperation {
127        self.operation
128    }
129
130    /// Returns the stable failure classification.
131    pub const fn kind(&self) -> RegistryErrorKind {
132        self.kind
133    }
134
135    /// Returns the safe public diagnostic message.
136    pub fn safe_message(&self) -> &str {
137        &self.message
138    }
139
140    /// Returns whether a fresh provider operation may succeed without changing its input.
141    pub const fn is_retryable(&self) -> bool {
142        self.kind.is_retryable()
143    }
144
145    /// Returns the retained provider or framework source.
146    pub fn source_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
147        self.source.as_ref()
148    }
149}
150
151impl fmt::Debug for RegistryError {
152    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
153        formatter
154            .debug_struct("RegistryError")
155            .field("operation", &self.operation)
156            .field("kind", &self.kind)
157            .field("message", &self.message)
158            .finish_non_exhaustive()
159    }
160}
161
162const fn default_message(kind: RegistryErrorKind) -> &'static str {
163    match kind {
164        RegistryErrorKind::Unavailable => "registry provider is unavailable",
165        RegistryErrorKind::Timeout => "registry operation timed out",
166        RegistryErrorKind::Unauthorized => "registry provider rejected the operation",
167        RegistryErrorKind::InvalidResource => "registry resource is invalid",
168        RegistryErrorKind::Conflict => "registry resource conflicts with existing state",
169        RegistryErrorKind::Cancelled => "registry operation was cancelled",
170        RegistryErrorKind::CleanupAborted => "registry cleanup did not complete",
171        RegistryErrorKind::Internal => "registry operation failed internally",
172    }
173}
174
175#[derive(Debug)]
176struct RegistryMessage(String);
177
178impl fmt::Display for RegistryMessage {
179    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
180        formatter.write_str(&self.0)
181    }
182}
183
184impl std::error::Error for RegistryMessage {}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn errors_preserve_operation_kind_and_source() {
192        let error = RegistryError::new(
193            RegistryOperation::ActivateSubscription,
194            RegistryErrorKind::Unavailable,
195            std::io::Error::other("provider offline"),
196        );
197
198        assert_eq!(error.operation(), RegistryOperation::ActivateSubscription);
199        assert_eq!(error.kind(), RegistryErrorKind::Unavailable);
200        assert!(error.is_retryable());
201        assert_eq!(error.safe_message(), "registry provider is unavailable");
202        assert!(error.source_ref().to_string().contains("provider offline"));
203        assert!(
204            std::error::Error::source(&error)
205                .unwrap()
206                .to_string()
207                .contains("provider offline")
208        );
209    }
210
211    #[test]
212    fn formatting_shows_safe_message_without_exposing_provider_source() {
213        let error = RegistryError::new(
214            RegistryOperation::ActivateSubscription,
215            RegistryErrorKind::Unavailable,
216            std::io::Error::other("provider-token=secret"),
217        );
218
219        let debug = format!("{error:?}");
220        let display = error.to_string();
221        assert!(debug.contains("ActivateSubscription"));
222        assert!(debug.contains("Unavailable"));
223        assert!(debug.contains("registry provider is unavailable"));
224        assert!(display.contains("registry provider is unavailable"));
225        assert!(!debug.contains("provider-token=secret"));
226        assert!(!display.contains("provider-token=secret"));
227    }
228
229    #[test]
230    fn explicit_public_message_is_preserved() {
231        let error = RegistryError::message(
232            RegistryOperation::Directory,
233            RegistryErrorKind::InvalidResource,
234            "directory snapshot is invalid",
235        );
236
237        assert_eq!(error.safe_message(), "directory snapshot is invalid");
238        assert!(format!("{error:?}").contains("directory snapshot is invalid"));
239        assert!(error.to_string().contains("directory snapshot is invalid"));
240        assert_eq!(
241            error.source_ref().to_string(),
242            "directory snapshot is invalid"
243        );
244    }
245}