mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! The SDK's own error type — a crate-owned facade over the internal
//! `mxc_common` error, so the public API never exposes the foundation crate.

use crate::mxc_common::mxc_error::{ApiFailure, MxcError, MxcErrorCode};

/// Error codes returned by the SDK, corresponding one-for-one to the
/// snake_case codes reported by MXC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
    MalformedRequest,
    UnsupportedContainment,
    UnsupportedPhase,
    BackendUnavailable,
    MalformedId,
    StaleId,
    NotProvisioned,
    NotStarted,
    AlreadyStarted,
    AlreadyStopped,
    PolicyValidation,
    BackendError,
}

impl ErrorCode {
    /// The snake_case value used in JSON errors, such as `"backend_error"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MalformedRequest => "malformed_request",
            Self::UnsupportedContainment => "unsupported_containment",
            Self::UnsupportedPhase => "unsupported_phase",
            Self::BackendUnavailable => "backend_unavailable",
            Self::MalformedId => "malformed_id",
            Self::StaleId => "stale_id",
            Self::NotProvisioned => "not_provisioned",
            Self::NotStarted => "not_started",
            Self::AlreadyStarted => "already_started",
            Self::AlreadyStopped => "already_stopped",
            Self::PolicyValidation => "policy_validation",
            Self::BackendError => "backend_error",
        }
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl ErrorCode {
    /// The internal code this facade code stands for.
    fn to_internal(self) -> MxcErrorCode {
        match self {
            Self::MalformedRequest => MxcErrorCode::MalformedRequest,
            Self::UnsupportedContainment => MxcErrorCode::UnsupportedContainment,
            Self::UnsupportedPhase => MxcErrorCode::UnsupportedPhase,
            Self::BackendUnavailable => MxcErrorCode::BackendUnavailable,
            Self::MalformedId => MxcErrorCode::MalformedId,
            Self::StaleId => MxcErrorCode::StaleId,
            Self::NotProvisioned => MxcErrorCode::NotProvisioned,
            Self::NotStarted => MxcErrorCode::NotStarted,
            Self::AlreadyStarted => MxcErrorCode::AlreadyStarted,
            Self::AlreadyStopped => MxcErrorCode::AlreadyStopped,
            Self::PolicyValidation => MxcErrorCode::PolicyValidation,
            Self::BackendError => MxcErrorCode::BackendError,
        }
    }
}

impl From<MxcErrorCode> for ErrorCode {
    fn from(code: MxcErrorCode) -> Self {
        match code {
            MxcErrorCode::MalformedRequest => Self::MalformedRequest,
            MxcErrorCode::UnsupportedContainment => Self::UnsupportedContainment,
            MxcErrorCode::UnsupportedPhase => Self::UnsupportedPhase,
            MxcErrorCode::BackendUnavailable => Self::BackendUnavailable,
            MxcErrorCode::MalformedId => Self::MalformedId,
            MxcErrorCode::StaleId => Self::StaleId,
            MxcErrorCode::NotProvisioned => Self::NotProvisioned,
            MxcErrorCode::NotStarted => Self::NotStarted,
            MxcErrorCode::AlreadyStarted => Self::AlreadyStarted,
            MxcErrorCode::AlreadyStopped => Self::AlreadyStopped,
            MxcErrorCode::PolicyValidation => Self::PolicyValidation,
            MxcErrorCode::BackendError => Self::BackendError,
        }
    }
}

/// An error returned by SDK operations such as [`spawn`](crate::v1::spawn).
///
/// `operation`, `native_code`, and `remediation` are top-level fields also
/// exposed by Node, .NET, and `mxc_ffi`. Backend-specific `details` are preserved
/// in Rust errors and executor JSON error envelopes. The C error structure
/// does not expose them.
///
/// This type is `#[non_exhaustive]`. Use [`Error::new`] rather than a struct
/// literal so future versions can add fields without breaking construction.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Error {
    /// The SDK error code.
    pub code: ErrorCode,
    /// A human-readable message.
    pub message: String,
    /// The API call that failed, namespaced by its interface and free of call
    /// parameters, so it can be grouped in telemetry. Absent when the failure
    /// was raised before any API call.
    pub operation: Option<String>,
    /// The underlying platform status, e.g. `0x80070490`. Absent when the
    /// failure carries none.
    pub native_code: Option<String>,
    /// An actionable "how to fix it" hint, when the failure carries one.
    pub remediation: Option<String>,
    /// Backend-specific structured context. May contain sensitive recovery
    /// identifiers; inspect it explicitly rather than logging it wholesale.
    pub details: Option<Box<serde_json::Value>>,
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Error")
            .field("code", &self.code)
            .field("message", &self.message)
            .field("operation", &self.operation)
            .field("native_code", &self.native_code)
            .field("remediation", &self.remediation)
            .field("details", &self.details.as_ref().map(|_| "<redacted>"))
            .finish()
    }
}

impl Error {
    /// An error with no API detail — the shape for failures raised before any
    /// API call was made.
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            operation: None,
            native_code: None,
            remediation: None,
            details: None,
        }
    }
}

/// Renders `code: message`, then the failing call and its status in brackets
/// when present — so a consumer that only logs the error does not silently lose
/// the diagnosis. Mirrors the internal type's rendering.
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)?;
        if let Some(operation) = &self.operation {
            write!(f, " [{operation}")?;
            if let Some(native_code) = &self.native_code {
                write!(f, " {native_code}")?;
            }
            write!(f, "]")?;
        }
        Ok(())
    }
}

impl std::error::Error for Error {}

impl From<MxcError> for Error {
    fn from(error: MxcError) -> Self {
        let (operation, native_code) = match error.api_failure {
            Some(failure) => {
                let failure = *failure;
                (Some(failure.operation), failure.native_code)
            }
            None => (None, None),
        };
        Self {
            code: error.code.into(),
            message: error.message,
            operation,
            native_code,
            remediation: error.remediation,
            details: error.details.map(Box::new),
        }
    }
}

impl Error {
    /// Recover the internal error this facade error stands for, so an
    /// in-repo binary can emit the typed envelope and exit status its code
    /// implies.
    ///
    /// Deliberately an inherent method rather than `impl From<Error> for
    /// MxcError`: a second `MxcError: From<_>` impl makes `?` ambiguous
    /// wherever the error type is inferred.
    ///
    #[doc(hidden)]
    pub fn into_mxc_error(self) -> MxcError {
        let mut error = MxcError::new(self.code.to_internal(), self.message);
        if let Some(operation) = self.operation {
            let mut failure = ApiFailure::new(operation);
            failure.native_code = self.native_code;
            error = error.with_api_failure(failure);
        }
        if let Some(remediation) = self.remediation {
            error = error.with_remediation(remediation);
        }
        error.details = self.details.map(|details| *details);
        error
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::mxc_error::{ApiFailure as InnerFailure, MxcError};
    /// The conversion carries the API detail across, rather than keeping only
    /// the code and message.
    ///
    /// The regression this pins: the facade used to copy `code`/`message` and
    /// drop `api_failure` on the floor, so every in-process caller — Rust SDK,
    /// FFI, and C# alike — lost the operation and platform status that the
    /// backend had already produced.
    #[test]
    fn the_conversion_preserves_the_api_detail() {
        let inner = MxcError::backend_error("The provision was not found.")
            .with_api_failure(
                InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
            )
            .with_remediation("Provision the session first.");

        let error = Error::from(inner);

        assert_eq!(error.code, ErrorCode::BackendError);
        assert_eq!(error.message, "The provision was not found.");
        assert_eq!(
            error.operation.as_deref(),
            Some("IsoSessionOps.StopSessionAsync")
        );
        assert_eq!(error.native_code.as_deref(), Some("0x80070490"));
        assert_eq!(
            error.remediation.as_deref(),
            Some("Provision the session first.")
        );
    }

    /// A failure that names only its operation leaves the status absent rather
    /// than empty — `None` and `Some("")` are different answers to "did the API
    /// supply a status?".
    #[test]
    fn an_operation_without_a_status_leaves_the_rest_absent() {
        let error = Error::from(
            MxcError::backend_error("boom").with_api_failure(InnerFailure::new("Iface.Call")),
        );

        assert_eq!(error.operation.as_deref(), Some("Iface.Call"));
        assert_eq!(error.native_code, None);
        assert_eq!(error.remediation, None);
    }

    /// An error raised before any API call carries no detail at all, whether it
    /// came through the conversion or was constructed directly.
    #[test]
    fn an_error_raised_before_any_api_call_carries_no_detail() {
        let converted = Error::from(MxcError::malformed_request("bad json"));

        assert_eq!(converted.operation, None);
        assert_eq!(converted.native_code, None);
        assert_eq!(converted.remediation, None);

        let constructed = Error::new(ErrorCode::BackendError, "x");

        assert_eq!(constructed.operation, None);
        assert_eq!(constructed.native_code, None);
        assert_eq!(constructed.remediation, None);
    }

    /// A hint with no API call behind it survives the conversion, and `Display`
    /// renders only the operation and status — so that combination comes out as
    /// plain `code: message` rather than as an empty bracket.
    #[test]
    fn a_remediation_without_an_operation_renders_without_brackets() {
        let error = Error::from(
            MxcError::policy_validation("unsupported policy")
                .with_remediation("Supply a supported policy."),
        );

        assert_eq!(error.operation, None);
        assert_eq!(
            error.remediation.as_deref(),
            Some("Supply a supported policy.")
        );
        assert_eq!(error.to_string(), "policy_validation: unsupported policy");
    }

    /// Rendering keeps the operation and status visible, so a consumer that
    /// only logs `{e}` does not lose the diagnosis.
    #[test]
    fn display_keeps_the_operation_and_status_visible() {
        let with_status = Error::from(
            MxcError::backend_error("The provision was not found.").with_api_failure(
                InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
            ),
        );
        assert_eq!(
            with_status.to_string(),
            "backend_error: The provision was not found. \
             [IsoSessionOps.StopSessionAsync 0x80070490]"
        );

        // No status: the brackets carry the operation alone rather than a
        // dangling separator.
        let without_status = Error::from(
            MxcError::backend_error("nope").with_api_failure(InnerFailure::new("Iface.Call")),
        );
        assert_eq!(
            without_status.to_string(),
            "backend_error: nope [Iface.Call]"
        );

        // No detail at all: unchanged from before this change.
        assert_eq!(
            Error::from(MxcError::malformed_request("bad")).to_string(),
            "malformed_request: bad"
        );
    }
}