dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
use std::future::Future;
#[cfg(test)]
use std::time::Duration;

use tokio::time::{Instant, timeout};

use crate::model::{
    CustomAreaDatasetResult, DatasetOutcome, DatasetRegionState, ProcessingState, RequestId,
    Response, WaitOptions,
};
use crate::{Client, Error, Result};

impl Client {
    /// Polls an R19 public result with bounded pacing through
    /// `ctiVysledekVyhotovVerejnouDatovouSadu`.
    ///
    /// The helper performs no submission or dataset download. Regional failure
    /// or rejection is returned as a complete result, not collapsed into success.
    pub async fn wait_for_public_custom_area_dataset(
        &self,
        request_id: &RequestId,
        options: WaitOptions,
    ) -> Result<Response<CustomAreaDatasetResult>> {
        wait_for_async(request_id, options, custom_area_terminal, || {
            self.read_public_custom_area_dataset_result(request_id)
        })
        .await
    }

    /// Polls an R19 non-public result with bounded pacing through
    /// `ctiVysledekVyhotovNeverejnouDatovouSadu`.
    pub async fn wait_for_non_public_custom_area_dataset(
        &self,
        request_id: &RequestId,
        options: WaitOptions,
    ) -> Result<Response<CustomAreaDatasetResult>> {
        wait_for_async(request_id, options, custom_area_terminal, || {
            self.read_non_public_custom_area_dataset_result(request_id)
        })
        .await
    }
}

fn custom_area_terminal(result: &CustomAreaDatasetResult) -> bool {
    result.regions.iter().any(|region| {
        matches!(
            region.state,
            DatasetRegionState::Failed | DatasetRegionState::Other(_)
        ) || matches!(
            region.outcome,
            Some(DatasetOutcome::Rejected | DatasetOutcome::Other(_))
        )
    })
}

pub(crate) async fn wait_for_async<T, Fut>(
    request_id: &RequestId,
    options: WaitOptions,
    domain_terminal: impl Fn(&T) -> bool,
    mut poll: impl FnMut() -> Fut,
) -> Result<Response<T>>
where
    Fut: Future<Output = Result<Response<Option<T>>>>,
{
    options.validate()?;
    let started = Instant::now();
    let deadline = started.checked_add(options.max_elapsed).ok_or_else(|| {
        Error::invalid_input("wait.max_elapsed", "wait deadline exceeds the clock range")
    })?;
    if !options.initial_delay.is_zero() {
        let requested = started
            .checked_add(options.initial_delay)
            .unwrap_or(deadline);
        sleep_until(deadline, requested, request_id).await?;
    }
    let mut interval = options.interval;
    loop {
        let now = Instant::now();
        if now >= deadline {
            return Err(Error::WaitTimeout {
                id: request_id.clone(),
            });
        }
        let response =
            timeout(deadline - now, poll())
                .await
                .map_err(|_| Error::WaitTimeout {
                    id: request_id.clone(),
                })??;
        let terminal_domain = response.value.as_ref().is_some_and(&domain_terminal);
        match response.metadata.state {
            ProcessingState::Completed => {
                return response
                    .value
                    .map(|value| Response {
                        value,
                        metadata: response.metadata,
                    })
                    .ok_or_else(|| Error::RequestUnavailable {
                        id: request_id.clone(),
                    });
            }
            ProcessingState::Accepted | ProcessingState::InProgress if !terminal_domain => {}
            // A domain-level failure/rejection is a visible terminal result even
            // if an outer header has not caught up with every region yet.
            ProcessingState::Accepted | ProcessingState::InProgress => {
                return response
                    .value
                    .map(|value| Response {
                        value,
                        metadata: response.metadata,
                    })
                    .ok_or_else(|| Error::RequestUnavailable {
                        id: request_id.clone(),
                    });
            }
            ProcessingState::Ok | ProcessingState::Failed | ProcessingState::Other(_) => {
                return Err(Error::RequestUnavailable {
                    id: request_id.clone(),
                });
            }
        }

        let next = Instant::now();
        if next >= deadline {
            return Err(Error::WaitTimeout {
                id: request_id.clone(),
            });
        }
        let requested = next.checked_add(interval).unwrap_or(deadline);
        sleep_until(deadline, requested, request_id).await?;
        interval = options.next_interval(interval);
    }
}

async fn sleep_until(deadline: Instant, requested: Instant, request_id: &RequestId) -> Result<()> {
    let target = requested.min(deadline);
    tokio::time::sleep_until(target).await;
    if Instant::now() >= deadline {
        Err(Error::WaitTimeout {
            id: request_id.clone(),
        })
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use crate::model::{CorrelationId, ResponseMetadata};

    use super::*;

    fn response<T>(state: ProcessingState, value: Option<T>) -> Response<Option<T>> {
        let id = CorrelationId::new();
        Response {
            value,
            metadata: ResponseMetadata {
                response_id: id,
                request_id: id,
                state,
                messages: Vec::new(),
            },
        }
    }

    fn options() -> WaitOptions {
        WaitOptions {
            initial_delay: Duration::ZERO,
            interval: Duration::from_secs(60),
            max_elapsed: Duration::from_secs(180),
            backoff: crate::WaitBackoff::Fixed,
        }
    }

    #[tokio::test(start_paused = true)]
    async fn pending_result_is_polled_after_sixty_seconds_until_ready() {
        let calls = Arc::new(AtomicUsize::new(0));
        let observed = calls.clone();
        let result = wait_for_async(
            &RequestId::new("synthetic-request").unwrap(),
            options(),
            |_| false,
            move || {
                let call = observed.fetch_add(1, Ordering::SeqCst);
                let state = if call == 0 {
                    ProcessingState::InProgress
                } else {
                    ProcessingState::Completed
                };
                async move { Ok(response(state, Some(call as u32))) }
            },
        )
        .await
        .unwrap();
        assert_eq!(result.value, 1);
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test(start_paused = true)]
    async fn deadline_bounds_an_inflight_request() {
        let id = RequestId::new("synthetic-request").unwrap();
        let error = wait_for_async::<(), _>(
            &id,
            options(),
            |_| false,
            || async {
                tokio::time::sleep(Duration::from_secs(600)).await;
                Ok(response(ProcessingState::Completed, Some(())))
            },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, Error::WaitTimeout { .. }));
    }

    #[tokio::test(start_paused = true)]
    async fn extreme_initial_delay_times_out_without_overflow_or_polling() {
        let mut options = options();
        options.initial_delay = Duration::MAX;
        let error = wait_for_async::<(), _>(
            &RequestId::new("synthetic-request").unwrap(),
            options,
            |_| false,
            || async { panic!("must not poll") },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, Error::WaitTimeout { .. }));
    }

    #[tokio::test(start_paused = true)]
    async fn extreme_interval_times_out_without_overflow_or_second_poll() {
        let calls = Arc::new(AtomicUsize::new(0));
        let observed = calls.clone();
        let mut options = options();
        options.interval = Duration::MAX;
        let error = wait_for_async(
            &RequestId::new("synthetic-request").unwrap(),
            options,
            |_| false,
            move || {
                observed.fetch_add(1, Ordering::SeqCst);
                async { Ok(response(ProcessingState::InProgress, Some(()))) }
            },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, Error::WaitTimeout { .. }));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn rejects_too_frequent_polling_without_calling_transport() {
        let id = RequestId::new("synthetic-request").unwrap();
        let mut invalid = options();
        invalid.interval = Duration::from_secs(59);
        let error = wait_for_async::<(), _>(
            &id,
            invalid,
            |_| false,
            || async { panic!("must not poll") },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, Error::InvalidInput { .. }));
    }
}