dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use crate::wire::soap::XmlWriter as Writer;

use crate::model::{
    CorrelationId, CustomAreaDatasetResult, InputFile, NonPublicCustomAreaDatasetRequest,
    ProcessingState, PublicCustomAreaDatasetRequest, RequestId, Response,
};
use crate::wire::datasets;
use crate::wire::soap::{self, Operation, Service};
use crate::{Client, Error, Result};

const SUBMIT_PUBLIC_CUSTOM_AREA: Operation = Operation::new(
    Service::R19,
    "vyhotovVerejnouDatovouSadu",
    "VyhotovVerejnouDatovouSadu",
    "VyhotovVerejnouDatovouSaduOdpoved",
)
.with_response_data_namespace(soap::ISDMVS_MESSAGES_NS);
const READ_PUBLIC_CUSTOM_AREA_RESULT: Operation = Operation::new(
    Service::R19,
    "ctiVysledekVyhotovVerejnouDatovouSadu",
    "CtiVysledekVyhotovVerejnouDatovouSadu",
    "CtiVysledekVyhotovVerejnouDatovouSaduOdpoved",
);
const SUBMIT_NON_PUBLIC_CUSTOM_AREA: Operation = Operation::new(
    Service::R19,
    "vyhotovNeverejnouDatovouSadu",
    "VyhotovNeverejnouDatovouSadu",
    "VyhotovNeverejnouDatovouSaduOdpoved",
)
.with_response_data_namespace(soap::ISDMVS_MESSAGES_NS);
const READ_NON_PUBLIC_CUSTOM_AREA_RESULT: Operation = Operation::new(
    Service::R19,
    "ctiVysledekVyhotovNeverejnouDatovouSadu",
    "CtiVysledekVyhotovNeverejnouDatovouSadu",
    "CtiVysledekVyhotovNeverejnouDatovouSaduOdpoved",
);

impl Client {
    /// Submits a public custom-area dataset through R19
    /// `vyhotovVerejnouDatovouSadu`.
    ///
    /// Exactly one submission is attempted, without retries. The client's
    /// configured subject is serialized as the requester. The durable
    /// [`RequestId`] can be persisted and passed to
    /// [`Client::read_public_custom_area_dataset_result`].
    pub async fn submit_public_custom_area_dataset(
        &self,
        request: &PublicCustomAreaDatasetRequest,
    ) -> Result<Response<RequestId>> {
        self.submit_public_custom_area_dataset_with_correlation_id(CorrelationId::new(), request)
            .await
    }

    /// Submits a public custom-area dataset using an explicit SOAP correlation ID.
    ///
    /// Exactly one submission is attempted, without retries. The correlation ID supports
    /// transport-level reconciliation; it is not the durable server-issued [`RequestId`].
    pub async fn submit_public_custom_area_dataset_with_correlation_id(
        &self,
        correlation_id: CorrelationId,
        request: &PublicCustomAreaDatasetRequest,
    ) -> Result<Response<RequestId>> {
        self.execute_dataset_submission(SUBMIT_PUBLIC_CUSTOM_AREA, correlation_id, &[], |writer| {
            datasets::write_public_custom_area_request(writer, self.subject_id(), request)
        })
        .await
    }

    /// Reads one public custom-area result through R19
    /// `ctiVysledekVyhotovVerejnouDatovouSadu`.
    ///
    /// This performs one request, never downloads datasets, and returns `None`
    /// when the service omits result `Data`; header state and messages are retained.
    pub async fn read_public_custom_area_dataset_result(
        &self,
        request_id: &RequestId,
    ) -> Result<Response<Option<CustomAreaDatasetResult>>> {
        self.read_public_custom_area_dataset_result_at(CorrelationId::new(), request_id)
            .await
    }

    async fn read_public_custom_area_dataset_result_at(
        &self,
        correlation_id: CorrelationId,
        request_id: &RequestId,
    ) -> Result<Response<Option<CustomAreaDatasetResult>>> {
        self.execute(
            READ_PUBLIC_CUSTOM_AREA_RESULT,
            correlation_id,
            |writer| datasets::write_result_request(writer, request_id),
            datasets::decode_custom_area_result,
        )
        .await
    }

    /// Submits a non-public custom-area dataset through R19
    /// `vyhotovNeverejnouDatovouSadu`.
    ///
    /// Exactly one submission is attempted, without retries. The client's
    /// configured subject is serialized as the requester. Evidence, when present,
    /// is sent as one MTOM attachment. Eligibility remains a server-side decision.
    pub async fn submit_non_public_custom_area_dataset(
        &self,
        request: &NonPublicCustomAreaDatasetRequest,
    ) -> Result<Response<RequestId>> {
        self.submit_non_public_custom_area_dataset_with_correlation_id(
            CorrelationId::new(),
            request,
        )
        .await
    }

    /// Submits a non-public custom-area dataset using an explicit SOAP correlation ID.
    ///
    /// Exactly one submission is attempted, without retries. Evidence, when present, is sent as
    /// one MTOM attachment. The correlation ID supports transport-level reconciliation; it is not
    /// the durable server-issued [`RequestId`]. Eligibility remains a server-side decision.
    pub async fn submit_non_public_custom_area_dataset_with_correlation_id(
        &self,
        correlation_id: CorrelationId,
        request: &NonPublicCustomAreaDatasetRequest,
    ) -> Result<Response<RequestId>> {
        let files = evidence_files(request.evidence.as_ref().map(|evidence| &evidence.file));
        self.execute_dataset_submission(
            SUBMIT_NON_PUBLIC_CUSTOM_AREA,
            correlation_id,
            files,
            |writer| {
                datasets::write_non_public_custom_area_request(writer, self.subject_id(), request)
            },
        )
        .await
    }

    /// Reads one non-public custom-area result through R19
    /// `ctiVysledekVyhotovNeverejnouDatovouSadu`.
    ///
    /// This performs one request and never downloads datasets. Missing result
    /// `Data` is returned as `None` without discarding response metadata.
    pub async fn read_non_public_custom_area_dataset_result(
        &self,
        request_id: &RequestId,
    ) -> Result<Response<Option<CustomAreaDatasetResult>>> {
        self.read_non_public_custom_area_dataset_result_at(CorrelationId::new(), request_id)
            .await
    }

    async fn read_non_public_custom_area_dataset_result_at(
        &self,
        correlation_id: CorrelationId,
        request_id: &RequestId,
    ) -> Result<Response<Option<CustomAreaDatasetResult>>> {
        self.execute(
            READ_NON_PUBLIC_CUSTOM_AREA_RESULT,
            correlation_id,
            |writer| datasets::write_result_request(writer, request_id),
            datasets::decode_custom_area_result,
        )
        .await
    }

    async fn execute_dataset_submission(
        &self,
        operation: Operation,
        correlation_id: CorrelationId,
        files: &[InputFile],
        write_request: impl FnOnce(&mut Writer) -> soap::XmlResult,
    ) -> Result<Response<RequestId>> {
        let response = self
            .execute_submission(
                operation,
                correlation_id,
                files,
                write_request,
                datasets::decode_submission,
            )
            .await?;
        if response.metadata.state != ProcessingState::Accepted {
            return Err(Error::unexpected_submission_state(response));
        }
        Ok(response)
    }
}

fn evidence_files(file: Option<&InputFile>) -> &[InputFile] {
    match file {
        Some(file) => std::slice::from_ref(file),
        None => &[],
    }
}

#[cfg(test)]
mod tests {
    use geo_types::{LineString, Polygon, coord};
    use wiremock::matchers::{body_string, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;
    use crate::model::{
        Area, DatasetEvidence, DatasetEvidencePurpose, DatasetFormat, NonPublicDatasetContent,
        NonPublicRequesterStatus, PublicCustomAreaDatasetContent, SubjectId,
    };

    const REQUEST_UUID: &str = "ed8af7af-5b39-4dff-96ab-7561214336f1";
    const RESPONSE_UUID: &str = "c5f073e9-d3e9-4845-aae0-de3ef42357be";

    fn area() -> Area {
        Area::s_jtsk(Polygon::new(
            LineString::from(vec![
                coord! { x: 0.0, y: 0.0 },
                coord! { x: 100.0, y: 0.0 },
                coord! { x: 100.0, y: 100.0 },
                coord! { x: 0.0, y: 100.0 },
                coord! { x: 0.0, y: 0.0 },
            ]),
            Vec::new(),
        ))
        .unwrap()
    }

    fn response_envelope(operation: Operation, state: &str, data: Option<&str>) -> String {
        let data = data
            .map(|data| {
                if operation.response_data_namespace == soap::ISDMVS_MESSAGES_NS {
                    format!("<iMsg:Data>{data}</iMsg:Data>")
                } else {
                    format!("<r:Data>{data}</r:Data>")
                }
            })
            .unwrap_or_default();
        let code = if state == "Prijato" { "1010" } else { "1020" };
        format!(
            "<s:Envelope xmlns:s=\"{}\" xmlns:r=\"{}\" xmlns:iMsg=\"{}\" xmlns:msg=\"{}\"><s:Body><r:{}><msg:Hlavicka><msg:UidOdpovedi>{RESPONSE_UUID}</msg:UidOdpovedi><msg:Vysledek stav=\"{state}\"><msg:UidZadosti>{REQUEST_UUID}</msg:UidZadosti><msg:Hlaseni><msg:Hlaseni kod=\"{code}\" typ=\"Informace\"><msg:Zprava>Synthetic response</msg:Zprava></msg:Hlaseni></msg:Hlaseni></msg:Vysledek></msg:Hlavicka>{data}</r:{}></s:Body></s:Envelope>",
            soap::SOAP_11_NS,
            operation.service.namespace(),
            soap::ISDMVS_MESSAGES_NS,
            soap::MESSAGES_NS,
            operation.response,
            operation.response,
        )
    }

    fn public_request() -> PublicCustomAreaDatasetRequest {
        PublicCustomAreaDatasetRequest::new(
            "2026-01-02".parse().unwrap(),
            vec![PublicCustomAreaDatasetContent::Di],
            area(),
            DatasetFormat::Jvf,
        )
        .unwrap()
    }

    #[test]
    fn operation_descriptors_match_all_four_official_operations() {
        let descriptors = [
            (
                SUBMIT_PUBLIC_CUSTOM_AREA,
                "vyhotovVerejnouDatovouSadu",
                "VyhotovVerejnouDatovouSadu",
                "VyhotovVerejnouDatovouSaduOdpoved",
            ),
            (
                READ_PUBLIC_CUSTOM_AREA_RESULT,
                "ctiVysledekVyhotovVerejnouDatovouSadu",
                "CtiVysledekVyhotovVerejnouDatovouSadu",
                "CtiVysledekVyhotovVerejnouDatovouSaduOdpoved",
            ),
            (
                SUBMIT_NON_PUBLIC_CUSTOM_AREA,
                "vyhotovNeverejnouDatovouSadu",
                "VyhotovNeverejnouDatovouSadu",
                "VyhotovNeverejnouDatovouSaduOdpoved",
            ),
            (
                READ_NON_PUBLIC_CUSTOM_AREA_RESULT,
                "ctiVysledekVyhotovNeverejnouDatovouSadu",
                "CtiVysledekVyhotovNeverejnouDatovouSadu",
                "CtiVysledekVyhotovNeverejnouDatovouSaduOdpoved",
            ),
        ];
        for (operation, action, request, response) in descriptors {
            assert_eq!(operation.action, action);
            assert_eq!(operation.request, request);
            assert_eq!(operation.response, response);
            assert_eq!(operation.service.path(), "R19VyhotoveniDatovychSad");
        }
        for operation in [SUBMIT_PUBLIC_CUSTOM_AREA, SUBMIT_NON_PUBLIC_CUSTOM_AREA] {
            assert_eq!(operation.response_data_namespace, soap::ISDMVS_MESSAGES_NS);
        }
    }

    #[tokio::test]
    async fn executes_http_202_submission_and_independent_pending_result() {
        let server = MockServer::start().await;
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let request = public_request();
        let submit_body = soap::request(SUBMIT_PUBLIC_CUSTOM_AREA, correlation_id, |writer| {
            datasets::write_public_custom_area_request(
                writer,
                &SubjectId::new("requester-id").unwrap(),
                &request,
            )
        })
        .unwrap();
        Mock::given(method("POST"))
            .and(path("/R19VyhotoveniDatovychSad"))
            .and(header("SOAPAction", "\"vyhotovVerejnouDatovouSadu\""))
            .and(header("Content-Type", "text/xml; charset=utf-8"))
            .and(body_string(String::from_utf8(submit_body).unwrap()))
            .respond_with(ResponseTemplate::new(202).set_body_raw(
                response_envelope(
                    SUBMIT_PUBLIC_CUSTOM_AREA,
                    "Prijato",
                    Some("<msg:IdPozadavku>durable-request-id</msg:IdPozadavku>"),
                ),
                "text/xml; charset=utf-8",
            ))
            .expect(1)
            .mount(&server)
            .await;

        let client = Client::test_client(server.uri());
        let submission = client
            .submit_public_custom_area_dataset_with_correlation_id(correlation_id, &request)
            .await
            .unwrap();
        assert_eq!(submission.value.as_str(), "durable-request-id");
        assert_eq!(submission.metadata.state, ProcessingState::Accepted);

        let result_body = soap::request(READ_PUBLIC_CUSTOM_AREA_RESULT, correlation_id, |writer| {
            datasets::write_result_request(writer, &submission.value)
        })
        .unwrap();
        Mock::given(method("POST"))
            .and(path("/R19VyhotoveniDatovychSad"))
            .and(header(
                "SOAPAction",
                "\"ctiVysledekVyhotovVerejnouDatovouSadu\"",
            ))
            .and(header("Content-Type", "text/xml; charset=utf-8"))
            .and(body_string(String::from_utf8(result_body).unwrap()))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                response_envelope(READ_PUBLIC_CUSTOM_AREA_RESULT, "ProbihaZpracovani", None),
                "text/xml; charset=utf-8",
            ))
            .expect(1)
            .mount(&server)
            .await;
        let result = client
            .read_public_custom_area_dataset_result_at(correlation_id, &submission.value)
            .await
            .unwrap();
        assert!(result.value.is_none());
        assert_eq!(result.metadata.state, ProcessingState::InProgress);
        assert_eq!(result.metadata.request_id, correlation_id);
    }

    #[tokio::test]
    async fn evidence_submission_uses_exactly_one_mtom_attachment() {
        let server = MockServer::start().await;
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let evidence = DatasetEvidence::new(
            DatasetEvidencePurpose::Text("synthetic purpose".into()),
            InputFile::new("evidence.txt", b"synthetic evidence".as_slice()).unwrap(),
        );
        let request = NonPublicCustomAreaDatasetRequest::new(
            NonPublicRequesterStatus::ApplicantByApplication,
            Some(evidence),
            vec![NonPublicDatasetContent::Ti],
            "2026-01-02".parse().unwrap(),
            area(),
            DatasetFormat::Shp,
        )
        .unwrap();
        Mock::given(method("POST"))
            .and(path("/R19VyhotoveniDatovychSad"))
            .and(header("SOAPAction", "\"vyhotovNeverejnouDatovouSadu\""))
            .respond_with(ResponseTemplate::new(202).set_body_raw(
                response_envelope(
                    SUBMIT_NON_PUBLIC_CUSTOM_AREA,
                    "Prijato",
                    Some("<msg:IdPozadavku>durable-request-id</msg:IdPozadavku>"),
                ),
                "text/xml; charset=utf-8",
            ))
            .expect(1)
            .mount(&server)
            .await;

        let client = Client::test_client(server.uri());
        let response = client
            .submit_non_public_custom_area_dataset_with_correlation_id(correlation_id, &request)
            .await
            .unwrap();
        assert_eq!(response.value.as_str(), "durable-request-id");
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 1);
        let content_type = requests[0]
            .headers
            .get("Content-Type")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(content_type.starts_with("multipart/related;"));
        let body = String::from_utf8_lossy(&requests[0].body);
        assert!(body.contains("href=\"cid:attachment-0@dmvs.invalid\""));
        assert!(body.contains("Content-ID: <attachment-0@dmvs.invalid>"));
        assert!(body.contains("synthetic evidence"));
        assert!(
            body.contains(
                "<commonVydejDat:UcelTextem>synthetic purpose</commonVydejDat:UcelTextem>"
            )
        );
        assert!(body.contains("<commonSubjekty:Id>requester-id</commonSubjekty:Id>"));
        assert!(body.contains("<Obsah><Obsah>Ti</Obsah></Obsah>"));
        assert!(!body.contains("commonSoubory:Velikost"));
        assert_eq!(body.matches("cid:attachment-0@dmvs.invalid").count(), 1);
    }

    #[tokio::test]
    async fn non_prijato_submission_retains_redacted_recovery_without_retry() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/R19VyhotoveniDatovychSad"))
            .respond_with(ResponseTemplate::new(202).set_body_raw(
                response_envelope(
                    SUBMIT_PUBLIC_CUSTOM_AREA,
                    "ProbihaZpracovani",
                    Some("<msg:IdPozadavku>durable-request-id</msg:IdPozadavku>"),
                ),
                "text/xml; charset=utf-8",
            ))
            .expect(1)
            .mount(&server)
            .await;
        let client = Client::test_client(server.uri());
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let error = client
            .submit_public_custom_area_dataset_with_correlation_id(
                correlation_id,
                &public_request(),
            )
            .await
            .unwrap_err();

        assert!(matches!(
            error,
            Error::SubmissionUncertainWithRecovery { .. }
        ));
        assert!(error.submission_outcome_uncertain());
        let recovery = error.recovery().unwrap();
        assert_eq!(recovery.request_id().as_str(), "durable-request-id");
        assert_eq!(recovery.response().value.as_str(), "durable-request-id");
        assert_eq!(recovery.metadata().state, ProcessingState::InProgress);
        assert_eq!(recovery.metadata().request_id, correlation_id);
        assert_eq!(
            recovery.metadata().response_id,
            RESPONSE_UUID.parse().unwrap()
        );
        assert_eq!(recovery.metadata().messages[0].text, "Synthetic response");

        let rendered = format!("{error:?}");
        for sensitive in [
            "durable-request-id",
            REQUEST_UUID,
            RESPONSE_UUID,
            "Synthetic response",
        ] {
            assert!(!rendered.contains(sensitive));
        }
        assert!(!format!("{recovery:?}").contains("durable-request-id"));
        assert_eq!(server.received_requests().await.unwrap().len(), 1);
        server.verify().await;
    }
}