use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use uuid::Uuid;
use crate::{Error, Result};
macro_rules! string_id {
($name:ident, $doc:literal) => {
#[doc = $doc]
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $name(String);
impl $name {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if value.is_empty()
|| value.len() > 256
|| value.chars().any(char::is_control)
|| value.trim() != value
{
return Err(Error::invalid_input(
"identifier",
"expected a non-empty, trimmed string of at most 256 bytes without control characters",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(concat!(stringify!($name), "([REDACTED])"))
}
}
impl fmt::Display for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(concat!(stringify!($name), "([REDACTED])"))
}
}
impl FromStr for $name {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl TryFrom<String> for $name {
type Error = Error;
fn try_from(value: String) -> Result<Self> {
Self::new(value)
}
}
impl From<$name> for String {
fn from(value: $name) -> Self {
value.0
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
};
}
string_id!(SubjectId, "An opaque IS DMVS subject identifier.");
string_id!(
RequestId,
"An opaque server-issued asynchronous request identifier."
);
string_id!(
InfrastructurePartId,
"An opaque infrastructure-part identifier."
);
string_id!(RegionCode, "An IS DTMK region code, retained as a string.");
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct CorrelationId(Uuid);
impl CorrelationId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(value: Uuid) -> Self {
Self(value)
}
pub fn as_uuid(&self) -> Uuid {
self.0
}
}
impl Default for CorrelationId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for CorrelationId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("CorrelationId([REDACTED])")
}
}
impl fmt::Display for CorrelationId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("CorrelationId([REDACTED])")
}
}
impl FromStr for CorrelationId {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Uuid::parse_str(value)
.map(Self)
.map_err(|_| Error::invalid_input("correlation_id", "expected a UUID"))
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for CorrelationId {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.as_uuid().to_string())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for CorrelationId {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ProcessingState {
Ok,
Accepted,
InProgress,
Completed,
Failed,
Other(String),
}
impl ProcessingState {
pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
match raw.as_str() {
"OK" => Self::Ok,
"Prijato" => Self::Accepted,
"ProbihaZpracovani" => Self::InProgress,
"Zpracovano" => Self::Completed,
"Chyba" => Self::Failed,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Ok => "OK",
Self::Accepted => "Prijato",
Self::InProgress => "ProbihaZpracovani",
Self::Completed => "Zpracovano",
Self::Failed => "Chyba",
Self::Other(raw) => raw,
}
}
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Ok | Self::Completed | Self::Failed)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageLevel {
Information,
Warning,
Error,
Other(String),
}
impl MessageLevel {
pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
match raw.as_str() {
"Informace" => Self::Information,
"Varovani" => Self::Warning,
"Chyba" => Self::Error,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Information => "Informace",
Self::Warning => "Varovani",
Self::Error => "Chyba",
Self::Other(raw) => raw,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageCode {
Success,
Accepted,
Processing,
Completed,
CertificateExpiring,
InvalidSubjectState,
Authentication,
Forbidden,
UnknownRequest,
InvalidInput,
InputRead,
NotFound,
UnexpectedState,
ProcessingTimeout,
Internal,
Other(String),
}
impl MessageCode {
pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
let raw = raw.into();
match raw.as_str() {
"1000" => Self::Success,
"1010" => Self::Accepted,
"1020" => Self::Processing,
"1030" => Self::Completed,
"2000" => Self::CertificateExpiring,
"3100" => Self::InvalidSubjectState,
"3150" => Self::Authentication,
"3200" => Self::Forbidden,
"4000" => Self::UnknownRequest,
"4100" => Self::InvalidInput,
"4110" => Self::InputRead,
"4400" => Self::NotFound,
"4500" => Self::UnexpectedState,
"4900" => Self::ProcessingTimeout,
"5000" => Self::Internal,
_ => Self::Other(raw),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Success => "1000",
Self::Accepted => "1010",
Self::Processing => "1020",
Self::Completed => "1030",
Self::CertificateExpiring => "2000",
Self::InvalidSubjectState => "3100",
Self::Authentication => "3150",
Self::Forbidden => "3200",
Self::UnknownRequest => "4000",
Self::InvalidInput => "4100",
Self::InputRead => "4110",
Self::NotFound => "4400",
Self::UnexpectedState => "4500",
Self::ProcessingTimeout => "4900",
Self::Internal => "5000",
Self::Other(raw) => raw,
}
}
}
impl fmt::Display for MessageCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ServiceMessage {
pub code: MessageCode,
pub level: MessageLevel,
pub text: String,
pub detail: Option<String>,
}
impl fmt::Debug for ServiceMessage {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ServiceMessage")
.field("code", &self.code)
.field("level", &self.level)
.field("text", &"[REDACTED]")
.field("detail", &self.detail.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ResponseMetadata {
pub response_id: CorrelationId,
pub request_id: CorrelationId,
pub state: ProcessingState,
pub messages: Vec<ServiceMessage>,
}
impl fmt::Debug for ResponseMetadata {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResponseMetadata")
.field("response_id", &"[REDACTED]")
.field("request_id", &"[REDACTED]")
.field("state", &self.state)
.field("messages", &self.messages)
.finish()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Response<T> {
pub value: T,
pub metadata: ResponseMetadata,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PageRequest {
pub offset: u32,
pub limit: u32,
pub include_total: bool,
}
impl PageRequest {
pub fn new(offset: u32, limit: u32) -> Result<Self> {
if !(1..=250).contains(&limit) {
return Err(Error::invalid_input(
"page.limit",
"page size must be between 1 and 250",
));
}
Ok(Self {
offset,
limit,
include_total: true,
})
}
pub fn with_total(mut self, include_total: bool) -> Self {
self.include_total = include_total;
self
}
}
impl Default for PageRequest {
fn default() -> Self {
Self {
offset: 0,
limit: 250,
include_total: true,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Page<T> {
pub offset: u32,
pub count: u32,
pub total: Option<u32>,
pub items: Vec<T>,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct XmlDate(String);
impl XmlDate {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
let value = value.trim();
value
.parse::<jiff::civil::Date>()
.map_err(|_| Error::invalid_input("date", "expected a valid YYYY-MM-DD date"))?;
Ok(Self(value.to_owned()))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn date(&self) -> jiff::civil::Date {
self.0.parse().expect("validated XML date")
}
}
impl fmt::Display for XmlDate {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for XmlDate {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
impl From<jiff::civil::Date> for XmlDate {
fn from(value: jiff::civil::Date) -> Self {
Self(value.to_string())
}
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct XmlDateTime(String);
impl XmlDateTime {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
let value = value.trim();
if value.parse::<jiff::Timestamp>().is_ok()
|| value.parse::<jiff::civil::DateTime>().is_ok()
{
Ok(Self(value.to_owned()))
} else {
Err(Error::invalid_input(
"date_time",
"expected a valid naive or offset-bearing XML date-time",
))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn timestamp(&self) -> Option<jiff::Timestamp> {
self.0.parse().ok()
}
pub fn civil(&self) -> Option<jiff::civil::DateTime> {
if self.timestamp().is_some() {
None
} else {
self.0.parse().ok()
}
}
}
impl fmt::Debug for XmlDateTime {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("XmlDateTime")
.field(&self.as_str())
.finish()
}
}
impl fmt::Display for XmlDateTime {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for XmlDateTime {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
Self::new(value)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum WaitBackoff {
Fixed,
Exponential {
max_interval: Duration,
},
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct WaitOptions {
pub initial_delay: Duration,
pub interval: Duration,
pub max_elapsed: Duration,
pub backoff: WaitBackoff,
}
impl WaitOptions {
pub(crate) fn validate(self) -> Result<()> {
if self.interval < Duration::from_secs(60) {
return Err(Error::invalid_input(
"wait.interval",
"DMVS result polling requires an interval of at least 60 seconds",
));
}
if self.max_elapsed.is_zero() {
return Err(Error::invalid_input(
"wait.max_elapsed",
"wait deadline must be greater than zero",
));
}
if let WaitBackoff::Exponential { max_interval } = self.backoff
&& (max_interval < self.interval || max_interval.is_zero())
{
return Err(Error::invalid_input(
"wait.backoff.max_interval",
"maximum backoff interval must be at least the base interval",
));
}
Ok(())
}
pub(crate) fn next_interval(self, current: Duration) -> Duration {
match self.backoff {
WaitBackoff::Fixed => self.interval,
WaitBackoff::Exponential { max_interval } => {
current.saturating_mul(2).min(max_interval)
}
}
}
}
impl Default for WaitOptions {
fn default() -> Self {
Self {
initial_delay: Duration::ZERO,
interval: Duration::from_secs(60),
max_elapsed: Duration::from_secs(15 * 60),
backoff: WaitBackoff::Fixed,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct JvfVersionInfo {
pub version: String,
pub valid_from: XmlDateTime,
pub valid_to: Option<XmlDateTime>,
pub description: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identifiers_validate_and_serde_uses_the_same_validation() {
let id = SubjectId::new("SUBJ-00000000").unwrap();
assert_eq!(id.as_str(), "SUBJ-00000000");
assert!(SubjectId::new(" bad ").is_err());
assert!(SubjectId::new("").is_err());
assert_eq!(format!("{id:?}"), "SubjectId([REDACTED])");
#[cfg(feature = "serde")]
{
assert_eq!(serde_json::to_string(&id).unwrap(), "\"SUBJ-00000000\"");
assert!(serde_json::from_str::<SubjectId>("\" bad \"").is_err());
}
}
#[test]
fn sensitive_identifier_display_is_redacted() {
let subject = SubjectId::new("synthetic-sensitive-subject").unwrap();
let request = RequestId::new("synthetic-sensitive-request").unwrap();
let uuid = Uuid::parse_str("ed8af7af-5b39-4dff-96ab-7561214336f1").unwrap();
let correlation = CorrelationId::from_uuid(uuid);
assert_eq!(subject.to_string(), "SubjectId([REDACTED])");
assert_eq!(request.to_string(), "RequestId([REDACTED])");
assert_eq!(correlation.to_string(), "CorrelationId([REDACTED])");
assert_eq!(correlation.as_uuid().to_string(), uuid.to_string());
#[cfg(feature = "serde")]
assert_eq!(
serde_json::to_string(&correlation).unwrap(),
"\"ed8af7af-5b39-4dff-96ab-7561214336f1\""
);
}
#[test]
fn xml_date_time_preserves_naive_and_offset_values() {
let offset = XmlDateTime::new("2022-01-01T00:00:00.000+01:00").unwrap();
assert!(offset.timestamp().is_some());
assert!(offset.civil().is_none());
let naive = XmlDateTime::new("2024-01-17T10:11:26.880").unwrap();
assert!(naive.timestamp().is_none());
assert!(naive.civil().is_some());
assert!(XmlDateTime::new("not-a-date").is_err());
}
#[test]
fn page_limit_is_bounded() {
assert!(PageRequest::new(0, 0).is_err());
assert!(PageRequest::new(0, 251).is_err());
assert_eq!(PageRequest::new(0, 250).unwrap().limit, 250);
}
}