use std::fmt;
use crate::{MessageCode, MessageLevel, RequestId, Response, ResponseMetadata, ServiceMessage};
#[derive(Clone, Eq, PartialEq)]
pub struct SubmissionRecovery {
pub response: Response<RequestId>,
}
impl SubmissionRecovery {
pub(crate) fn new(response: Response<RequestId>) -> Self {
Self { response }
}
pub fn response(&self) -> &Response<RequestId> {
&self.response
}
pub fn request_id(&self) -> &RequestId {
&self.response.value
}
pub fn metadata(&self) -> &ResponseMetadata {
&self.response.metadata
}
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])")
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ServiceError {
messages: Vec<ServiceMessage>,
}
impl ServiceError {
pub(crate) fn new(messages: Vec<ServiceMessage>) -> Self {
Self { messages }
}
pub fn messages(&self) -> &[ServiceMessage] {
&self.messages
}
pub fn message_code(&self) -> Option<&MessageCode> {
self.messages
.iter()
.find(|message| message.level == MessageLevel::Error)
.map(|message| &message.code)
}
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 {}
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("invalid input for {field}: {message}")]
InvalidInput {
field: &'static str,
message: String,
},
#[error("invalid DMVS TLS identity: {message}")]
TlsIdentity {
message: String,
},
#[error("DMVS transport failed")]
Transport(#[source] reqwest::Error),
#[error("DMVS authentication failed with HTTP status {status}")]
Authentication {
status: u16,
},
#[error("DMVS returned HTTP status {status}")]
Http {
status: u16,
},
#[error("SOAP fault {code}")]
SoapFault {
code: String,
message: String,
},
#[error("{0}")]
Service(#[from] ServiceError),
#[error("DMVS response exceeded the configured {limit}-byte limit")]
ResponseTooLarge {
limit: usize,
},
#[error("invalid DMVS response: {message}")]
InvalidResponse {
message: String,
},
#[error("asynchronous submission outcome is uncertain: {source}")]
SubmissionUncertain {
source: Box<Error>,
},
#[error("asynchronous submission outcome is uncertain: {source}")]
SubmissionUncertainWithRecovery {
source: Box<Error>,
recovery: SubmissionRecovery,
},
#[error("asynchronous request wait deadline elapsed")]
WaitTimeout {
id: RequestId,
},
#[error("asynchronous request is not ready")]
RequestUnavailable {
id: RequestId,
},
#[error("downloaded content failed integrity verification")]
IntegrityMismatch,
#[error("dataset download failed: {message}")]
Download {
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),
}
}
pub fn recovery(&self) -> Option<&SubmissionRecovery> {
match self {
Self::SubmissionUncertainWithRecovery { recovery, .. } => Some(recovery),
Self::SubmissionUncertain { source } => source.recovery(),
_ => None,
}
}
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,
}
}
pub fn submission_outcome_uncertain(&self) -> bool {
matches!(
self,
Self::SubmissionUncertain { .. } | Self::SubmissionUncertainWithRecovery { .. }
)
}
}
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());
}
}