Skip to main content

mxc_sdk/core/mxc_engine/
error.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The SDK's own error type — a crate-owned facade over the internal
5//! `mxc_common` error, so the public API never exposes the foundation crate.
6
7use crate::mxc_common::mxc_error::{ApiFailure, MxcError, MxcErrorCode};
8
9/// Error codes returned by the SDK, corresponding one-for-one to the
10/// snake_case codes reported by MXC.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum ErrorCode {
13    MalformedRequest,
14    UnsupportedContainment,
15    UnsupportedPhase,
16    BackendUnavailable,
17    MalformedId,
18    StaleId,
19    NotProvisioned,
20    NotStarted,
21    AlreadyStarted,
22    AlreadyStopped,
23    PolicyValidation,
24    BackendError,
25}
26
27impl ErrorCode {
28    /// The snake_case value used in JSON errors, such as `"backend_error"`.
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::MalformedRequest => "malformed_request",
32            Self::UnsupportedContainment => "unsupported_containment",
33            Self::UnsupportedPhase => "unsupported_phase",
34            Self::BackendUnavailable => "backend_unavailable",
35            Self::MalformedId => "malformed_id",
36            Self::StaleId => "stale_id",
37            Self::NotProvisioned => "not_provisioned",
38            Self::NotStarted => "not_started",
39            Self::AlreadyStarted => "already_started",
40            Self::AlreadyStopped => "already_stopped",
41            Self::PolicyValidation => "policy_validation",
42            Self::BackendError => "backend_error",
43        }
44    }
45}
46
47impl std::fmt::Display for ErrorCode {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.write_str(self.as_str())
50    }
51}
52
53impl ErrorCode {
54    /// The internal code this facade code stands for.
55    fn to_internal(self) -> MxcErrorCode {
56        match self {
57            Self::MalformedRequest => MxcErrorCode::MalformedRequest,
58            Self::UnsupportedContainment => MxcErrorCode::UnsupportedContainment,
59            Self::UnsupportedPhase => MxcErrorCode::UnsupportedPhase,
60            Self::BackendUnavailable => MxcErrorCode::BackendUnavailable,
61            Self::MalformedId => MxcErrorCode::MalformedId,
62            Self::StaleId => MxcErrorCode::StaleId,
63            Self::NotProvisioned => MxcErrorCode::NotProvisioned,
64            Self::NotStarted => MxcErrorCode::NotStarted,
65            Self::AlreadyStarted => MxcErrorCode::AlreadyStarted,
66            Self::AlreadyStopped => MxcErrorCode::AlreadyStopped,
67            Self::PolicyValidation => MxcErrorCode::PolicyValidation,
68            Self::BackendError => MxcErrorCode::BackendError,
69        }
70    }
71}
72
73impl From<MxcErrorCode> for ErrorCode {
74    fn from(code: MxcErrorCode) -> Self {
75        match code {
76            MxcErrorCode::MalformedRequest => Self::MalformedRequest,
77            MxcErrorCode::UnsupportedContainment => Self::UnsupportedContainment,
78            MxcErrorCode::UnsupportedPhase => Self::UnsupportedPhase,
79            MxcErrorCode::BackendUnavailable => Self::BackendUnavailable,
80            MxcErrorCode::MalformedId => Self::MalformedId,
81            MxcErrorCode::StaleId => Self::StaleId,
82            MxcErrorCode::NotProvisioned => Self::NotProvisioned,
83            MxcErrorCode::NotStarted => Self::NotStarted,
84            MxcErrorCode::AlreadyStarted => Self::AlreadyStarted,
85            MxcErrorCode::AlreadyStopped => Self::AlreadyStopped,
86            MxcErrorCode::PolicyValidation => Self::PolicyValidation,
87            MxcErrorCode::BackendError => Self::BackendError,
88        }
89    }
90}
91
92/// An error returned by SDK operations such as [`spawn`](crate::v1::spawn).
93///
94/// `operation`, `native_code`, and `remediation` are top-level fields also
95/// exposed by Node, .NET, and `mxc_ffi`. Backend-specific `details` are
96/// preserved in Rust errors, executor JSON error envelopes, and the C error
97/// structure; Node and .NET expose them as `details` and `Details`.
98///
99/// This type is `#[non_exhaustive]`. Use [`Error::new`] rather than a struct
100/// literal so future versions can add fields without breaking construction.
101#[derive(Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Error {
104    /// The SDK error code.
105    pub code: ErrorCode,
106    /// A human-readable message.
107    pub message: String,
108    /// The API call that failed, namespaced by its interface and free of call
109    /// parameters, so it can be grouped in telemetry. Absent when the failure
110    /// was raised before any API call.
111    pub operation: Option<String>,
112    /// The underlying platform status, e.g. `0x80070490`. Absent when the
113    /// failure carries none.
114    pub native_code: Option<String>,
115    /// An actionable "how to fix it" hint, when the failure carries one.
116    pub remediation: Option<String>,
117    /// Backend-specific structured context. May contain sensitive recovery
118    /// identifiers; inspect it explicitly rather than logging it wholesale.
119    pub details: Option<Box<serde_json::Value>>,
120}
121
122impl std::fmt::Debug for Error {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        f.debug_struct("Error")
125            .field("code", &self.code)
126            .field("message", &self.message)
127            .field("operation", &self.operation)
128            .field("native_code", &self.native_code)
129            .field("remediation", &self.remediation)
130            .field("details", &self.details.as_ref().map(|_| "<redacted>"))
131            .finish()
132    }
133}
134
135impl Error {
136    /// An error with no API detail — the shape for failures raised before any
137    /// API call was made.
138    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
139        Self {
140            code,
141            message: message.into(),
142            operation: None,
143            native_code: None,
144            remediation: None,
145            details: None,
146        }
147    }
148}
149
150/// Renders `code: message`, then the failing call and its status in brackets
151/// when present — so a consumer that only logs the error does not silently lose
152/// the diagnosis. Mirrors the internal type's rendering.
153impl std::fmt::Display for Error {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        write!(f, "{}: {}", self.code, self.message)?;
156        if let Some(operation) = &self.operation {
157            write!(f, " [{operation}")?;
158            if let Some(native_code) = &self.native_code {
159                write!(f, " {native_code}")?;
160            }
161            write!(f, "]")?;
162        }
163        Ok(())
164    }
165}
166
167impl std::error::Error for Error {}
168
169impl From<MxcError> for Error {
170    fn from(error: MxcError) -> Self {
171        let (operation, native_code) = match error.api_failure {
172            Some(failure) => {
173                let failure = *failure;
174                (Some(failure.operation), failure.native_code)
175            }
176            None => (None, None),
177        };
178        Self {
179            code: error.code.into(),
180            message: error.message,
181            operation,
182            native_code,
183            remediation: error.remediation,
184            details: error.details.map(Box::new),
185        }
186    }
187}
188
189impl Error {
190    /// Recover the internal error this facade error stands for, so an
191    /// in-repo binary can emit the typed envelope and exit status its code
192    /// implies.
193    ///
194    /// Deliberately an inherent method rather than `impl From<Error> for
195    /// MxcError`: a second `MxcError: From<_>` impl makes `?` ambiguous
196    /// wherever the error type is inferred.
197    ///
198    #[doc(hidden)]
199    pub fn into_mxc_error(self) -> MxcError {
200        let mut error = MxcError::new(self.code.to_internal(), self.message);
201        if let Some(operation) = self.operation {
202            let mut failure = ApiFailure::new(operation);
203            failure.native_code = self.native_code;
204            error = error.with_api_failure(failure);
205        }
206        if let Some(remediation) = self.remediation {
207            error = error.with_remediation(remediation);
208        }
209        error.details = self.details.map(|details| *details);
210        error
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::mxc_common::mxc_error::{ApiFailure as InnerFailure, MxcError};
218    use crate::mxc_common::policy_failures::PolicyFailures;
219
220    #[test]
221    fn policy_failures_error_debug_does_not_render_structured_resources() {
222        let payload =
223            serde_json::json!({ "policyFailures": { "resource": "POLICY_RESOURCE_MARKER" } });
224        let inner = MxcError::backend_error("Creation refused.").with_details(payload);
225        assert!(!format!("{inner:?}").contains("POLICY_RESOURCE_MARKER"));
226        let error = Error::from(inner);
227        assert!(!format!("{error:?}").contains("POLICY_RESOURCE_MARKER"));
228        assert!(error
229            .details
230            .as_deref()
231            .unwrap()
232            .get("policyFailures")
233            .is_some());
234    }
235
236    #[test]
237    fn policy_failures_details_survive_sdk_conversions() {
238        let payload = serde_json::json!({ "policyFailures": PolicyFailures::default() });
239        let original = MxcError::backend_error("Creation refused.").with_details(payload.clone());
240        let converted = Error::from(original);
241        assert_eq!(converted.details.as_deref(), Some(&payload));
242        assert_eq!(converted.into_mxc_error().details, Some(payload));
243        assert!(std::mem::size_of::<Error>() < 128);
244    }
245
246    /// The conversion carries the API detail across, rather than keeping only
247    /// the code and message.
248    ///
249    /// The regression this pins: the facade used to copy `code`/`message` and
250    /// drop `api_failure` on the floor, so every in-process caller — Rust SDK,
251    /// FFI, and C# alike — lost the operation and platform status that the
252    /// backend had already produced.
253    #[test]
254    fn the_conversion_preserves_the_api_detail() {
255        let inner = MxcError::backend_error("The provision was not found.")
256            .with_details(serde_json::json!({"backend": "test"}))
257            .with_api_failure(
258                InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
259            )
260            .with_remediation("Provision the session first.");
261
262        let error = Error::from(inner);
263
264        assert_eq!(error.code, ErrorCode::BackendError);
265        assert_eq!(error.message, "The provision was not found.");
266        assert_eq!(
267            error.details,
268            Some(Box::new(serde_json::json!({"backend": "test"})))
269        );
270        assert_eq!(
271            error.operation.as_deref(),
272            Some("IsoSessionOps.StopSessionAsync")
273        );
274        assert_eq!(error.native_code.as_deref(), Some("0x80070490"));
275        assert_eq!(
276            error.remediation.as_deref(),
277            Some("Provision the session first.")
278        );
279    }
280
281    /// A failure that names only its operation leaves the status absent rather
282    /// than empty — `None` and `Some("")` are different answers to "did the API
283    /// supply a status?".
284    #[test]
285    fn an_operation_without_a_status_leaves_the_rest_absent() {
286        let error = Error::from(
287            MxcError::backend_error("boom").with_api_failure(InnerFailure::new("Iface.Call")),
288        );
289
290        assert_eq!(error.operation.as_deref(), Some("Iface.Call"));
291        assert_eq!(error.native_code, None);
292        assert_eq!(error.remediation, None);
293    }
294
295    /// An error raised before any API call carries no detail at all, whether it
296    /// came through the conversion or was constructed directly.
297    #[test]
298    fn an_error_raised_before_any_api_call_carries_no_detail() {
299        let converted = Error::from(MxcError::malformed_request("bad json"));
300
301        assert_eq!(converted.operation, None);
302        assert_eq!(converted.native_code, None);
303        assert_eq!(converted.remediation, None);
304        assert_eq!(converted.details, None);
305
306        let constructed = Error::new(ErrorCode::BackendError, "x");
307
308        assert_eq!(constructed.operation, None);
309        assert_eq!(constructed.native_code, None);
310        assert_eq!(constructed.remediation, None);
311        assert_eq!(constructed.details, None);
312    }
313
314    #[test]
315    fn the_conversion_round_trip_preserves_details() {
316        let inner = MxcError::backend_error("boom")
317            .with_details(serde_json::json!({"phase": "wait"}))
318            .with_api_failure(InnerFailure::new("Iface.Wait").with_native_code("0x80004005"))
319            .with_remediation("Retry.");
320
321        assert_eq!(Error::from(inner.clone()).into_mxc_error(), inner);
322    }
323
324    /// A hint with no API call behind it survives the conversion, and `Display`
325    /// renders only the operation and status — so that combination comes out as
326    /// plain `code: message` rather than as an empty bracket.
327    #[test]
328    fn a_remediation_without_an_operation_renders_without_brackets() {
329        let error = Error::from(
330            MxcError::policy_validation("unsupported policy")
331                .with_remediation("Supply a supported policy."),
332        );
333
334        assert_eq!(error.operation, None);
335        assert_eq!(
336            error.remediation.as_deref(),
337            Some("Supply a supported policy.")
338        );
339        assert_eq!(error.to_string(), "policy_validation: unsupported policy");
340    }
341
342    /// Rendering keeps the operation and status visible, so a consumer that
343    /// only logs `{e}` does not lose the diagnosis.
344    #[test]
345    fn display_keeps_the_operation_and_status_visible() {
346        let with_status = Error::from(
347            MxcError::backend_error("The provision was not found.").with_api_failure(
348                InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
349            ),
350        );
351        assert_eq!(
352            with_status.to_string(),
353            "backend_error: The provision was not found. \
354             [IsoSessionOps.StopSessionAsync 0x80070490]"
355        );
356
357        // No status: the brackets carry the operation alone rather than a
358        // dangling separator.
359        let without_status = Error::from(
360            MxcError::backend_error("nope").with_api_failure(InnerFailure::new("Iface.Call")),
361        );
362        assert_eq!(
363            without_status.to_string(),
364            "backend_error: nope [Iface.Call]"
365        );
366
367        // No detail at all: unchanged from before this change.
368        assert_eq!(
369            Error::from(MxcError::malformed_request("bad")).to_string(),
370            "malformed_request: bad"
371        );
372    }
373}