dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
use std::fmt;

use crate::{MessageCode, MessageLevel, RequestId, Response, ResponseMetadata, ServiceMessage};

/// A decoded asynchronous submission response that can be resumed by its durable request ID.
///
/// The response is retained in full so an unexpected processing state does not discard the
/// server-issued identifier or correlation metadata. Debugging redacts the complete response.
#[derive(Clone, Eq, PartialEq)]
pub struct SubmissionRecovery {
    /// The complete decoded submission response.
    pub response: Response<RequestId>,
}

impl SubmissionRecovery {
    pub(crate) fn new(response: Response<RequestId>) -> Self {
        Self { response }
    }

    /// Returns the complete decoded submission response.
    pub fn response(&self) -> &Response<RequestId> {
        &self.response
    }

    /// Returns the durable server-issued request ID to use for subsequent status operations.
    pub fn request_id(&self) -> &RequestId {
        &self.response.value
    }

    /// Returns the correlated response metadata, including its unexpected processing state.
    pub fn metadata(&self) -> &ResponseMetadata {
        &self.response.metadata
    }

    /// Consumes this recovery value and returns the complete decoded response.
    pub fn into_response(self) -> Response<RequestId> {
        self.response
    }
}

impl fmt::Debug for SubmissionRecovery {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("SubmissionRecovery([REDACTED])")
    }
}

/// An application-level DMVS error containing the complete server message list.
#[derive(Clone, Eq, PartialEq)]
pub struct ServiceError {
    messages: Vec<ServiceMessage>,
}

impl ServiceError {
    pub(crate) fn new(messages: Vec<ServiceMessage>) -> Self {
        Self { messages }
    }

    /// Returns every message supplied by the service, including non-errors.
    pub fn messages(&self) -> &[ServiceMessage] {
        &self.messages
    }

    /// Returns the first application-error code as a typed, raw-preserving value.
    pub fn message_code(&self) -> Option<&MessageCode> {
        self.messages
            .iter()
            .find(|message| message.level == MessageLevel::Error)
            .map(|message| &message.code)
    }

    /// Returns the first application-error code as a string, if present.
    pub fn code(&self) -> Option<&str> {
        self.message_code().map(|code| code.as_str())
    }
}

impl fmt::Debug for ServiceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ServiceError")
            .field("message_count", &self.messages.len())
            .finish_non_exhaustive()
    }
}

impl fmt::Display for ServiceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.code() {
            Some(code) => write!(
                formatter,
                "DMVS rejected the operation with message code {code}"
            ),
            None => formatter.write_str("DMVS rejected the operation"),
        }
    }
}

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

/// Errors produced while configuring or calling the DMVS client.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// An input, identifier, or client configuration value is invalid.
    #[error("invalid input for {field}: {message}")]
    InvalidInput {
        /// Name of the invalid field.
        field: &'static str,
        /// Safe description of the violated invariant.
        message: String,
    },

    /// The PEM client identity could not be constructed.
    #[error("invalid DMVS TLS identity: {message}")]
    TlsIdentity {
        /// Safe parsing or key-format description.
        message: String,
    },

    /// An HTTP request failed in transport.
    #[error("DMVS transport failed")]
    Transport(#[source] reqwest::Error),

    /// The server rejected authentication or authorization at HTTP level.
    #[error("DMVS authentication failed with HTTP status {status}")]
    Authentication {
        /// Numeric HTTP status code.
        status: u16,
    },

    /// The server returned an HTTP error without a usable SOAP fault.
    #[error("DMVS returned HTTP status {status}")]
    Http {
        /// Numeric HTTP status code.
        status: u16,
    },

    /// The SOAP endpoint returned a fault. Fault text is explicit but never displayed.
    #[error("SOAP fault {code}")]
    SoapFault {
        /// SOAP fault code.
        code: String,
        /// SOAP fault text, redacted from normal display/debug output.
        message: String,
    },

    /// DMVS returned an application `Chyba` response.
    #[error("{0}")]
    Service(#[from] ServiceError),

    /// A response exceeded its configured buffered-byte limit.
    #[error("DMVS response exceeded the configured {limit}-byte limit")]
    ResponseTooLarge {
        /// Maximum permitted response size.
        limit: usize,
    },

    /// A response was malformed or did not match the requested operation.
    #[error("invalid DMVS response: {message}")]
    InvalidResponse {
        /// Safe description that never includes the response body.
        message: String,
    },

    /// An asynchronous submission was dispatched but its acceptance is uncertain.
    #[error("asynchronous submission outcome is uncertain: {source}")]
    SubmissionUncertain {
        /// Safe underlying transport, HTTP, or decoding error.
        source: Box<Error>,
    },

    /// An asynchronous submission returned a durable ID with an unexpected processing state.
    #[error("asynchronous submission outcome is uncertain: {source}")]
    SubmissionUncertainWithRecovery {
        /// Safe description of the unexpected response state.
        source: Box<Error>,
        /// Complete decoded response needed to resume without another submission.
        recovery: SubmissionRecovery,
    },

    /// Bounded waiting elapsed before a ready state.
    #[error("asynchronous request wait deadline elapsed")]
    WaitTimeout {
        /// Request ID to resume later without resubmission.
        id: RequestId,
    },

    /// An asynchronous request reached a failed or unclassifiable state.
    #[error("asynchronous request is not ready")]
    RequestUnavailable {
        /// Request ID to inspect or reconcile.
        id: RequestId,
    },

    /// Downloaded content does not match its declared size or checksum.
    #[error("downloaded content failed integrity verification")]
    IntegrityMismatch,

    /// A dataset URL or download response is invalid or exceeds its configured limit.
    #[error("dataset download failed: {message}")]
    Download {
        /// Safe validation or protocol description.
        message: String,
    },
}

impl fmt::Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidInput { field, message } => formatter
                .debug_struct("InvalidInput")
                .field("field", field)
                .field("message", message)
                .finish(),
            Self::TlsIdentity { message } => formatter
                .debug_struct("TlsIdentity")
                .field("message", message)
                .finish(),
            Self::Transport(_) => formatter.write_str("Transport([REDACTED])"),
            Self::Authentication { status } => formatter
                .debug_struct("Authentication")
                .field("status", status)
                .finish(),
            Self::Http { status } => formatter
                .debug_struct("Http")
                .field("status", status)
                .finish(),
            Self::SoapFault { code, .. } => formatter
                .debug_struct("SoapFault")
                .field("code", code)
                .field("message", &"[REDACTED]")
                .finish(),
            Self::Service(error) => fmt::Debug::fmt(error, formatter),
            Self::ResponseTooLarge { limit } => formatter
                .debug_struct("ResponseTooLarge")
                .field("limit", limit)
                .finish(),
            Self::InvalidResponse { message } => formatter
                .debug_struct("InvalidResponse")
                .field("message", message)
                .finish(),
            Self::SubmissionUncertain { source } => formatter
                .debug_struct("SubmissionUncertain")
                .field("source", source)
                .finish(),
            Self::SubmissionUncertainWithRecovery { source, recovery } => formatter
                .debug_struct("SubmissionUncertainWithRecovery")
                .field("source", source)
                .field("recovery", recovery)
                .finish(),
            Self::WaitTimeout { .. } => formatter.write_str("WaitTimeout([REDACTED])"),
            Self::RequestUnavailable { .. } => {
                formatter.write_str("RequestUnavailable([REDACTED])")
            }
            Self::IntegrityMismatch => formatter.write_str("IntegrityMismatch"),
            Self::Download { message } => formatter
                .debug_struct("Download")
                .field("message", message)
                .finish(),
        }
    }
}

impl Error {
    pub(crate) fn invalid_input(field: &'static str, message: impl Into<String>) -> Self {
        Self::InvalidInput {
            field,
            message: message.into(),
        }
    }

    pub(crate) fn invalid_response(message: impl Into<String>) -> Self {
        Self::InvalidResponse {
            message: message.into(),
        }
    }

    pub(crate) fn unexpected_submission_state(response: Response<RequestId>) -> Self {
        Self::SubmissionUncertainWithRecovery {
            source: Box::new(Self::invalid_response(
                "asynchronous submission state is not Prijato",
            )),
            recovery: SubmissionRecovery::new(response),
        }
    }

    /// Returns the decoded submission response when a durable request ID is available.
    ///
    /// Transport and pre-decode failures return `None`; no request ID is inferred or generated.
    pub fn recovery(&self) -> Option<&SubmissionRecovery> {
        match self {
            Self::SubmissionUncertainWithRecovery { recovery, .. } => Some(recovery),
            Self::SubmissionUncertain { source } => source.recovery(),
            _ => None,
        }
    }

    /// Returns true for HTTP authentication failures or common DMVS authentication codes.
    pub fn is_authentication_failure(&self) -> bool {
        match self {
            Self::Authentication { .. } => true,
            Self::Service(error) => error.messages().iter().any(|message| {
                matches!(
                    message.code,
                    MessageCode::Authentication | MessageCode::Forbidden
                )
            }),
            Self::SubmissionUncertain { source }
            | Self::SubmissionUncertainWithRecovery { source, .. } => {
                source.is_authentication_failure()
            }
            _ => false,
        }
    }

    /// Returns true if an asynchronous submission may have been accepted despite the error.
    pub fn submission_outcome_uncertain(&self) -> bool {
        matches!(
            self,
            Self::SubmissionUncertain { .. } | Self::SubmissionUncertainWithRecovery { .. }
        )
    }
}

/// Result alias used by the DMVS crate.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn service_errors_retain_messages_without_leaking_text() {
        let error = ServiceError::new(vec![ServiceMessage {
            code: MessageCode::Forbidden,
            level: MessageLevel::Error,
            text: "sensitive server text".into(),
            detail: Some("sensitive detail".into()),
        }]);
        assert_eq!(error.code(), Some("3200"));
        let rendered = format!("{error:?}");
        assert!(!rendered.contains("sensitive"));
        assert!(Error::from(error).is_authentication_failure());
    }

    #[test]
    fn submission_uncertain_without_a_decoded_response_has_no_recovery() {
        let error = Error::SubmissionUncertain {
            source: Box::new(Error::invalid_response("response could not be decoded")),
        };
        assert!(error.recovery().is_none());
        assert!(error.submission_outcome_uncertain());
        assert!(!error.is_authentication_failure());

        let authentication = Error::SubmissionUncertain {
            source: Box::new(Error::Authentication { status: 401 }),
        };
        assert!(authentication.recovery().is_none());
        assert!(authentication.is_authentication_failure());
        assert!(authentication.submission_outcome_uncertain());
    }
}