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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use crate::model::{
    CorrelationId, FilePayload, InfrastructureInquiryPart, InfrastructureManagerInquiryRequest,
    OverallResult, Page, PageRequest, ProcessingState, RequestId, Response, WaitOptions,
};
use crate::wire::inquiries;
use crate::wire::soap::{self, Operation, Service};
use crate::{Client, Error, Result};

const SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY: Operation = Operation::new(
    Service::R49,
    "zjistiUzemiSpravcuDti",
    "ZjistiUzemiSpravcuDti",
    "ZjistiUzemiSpravcuDtiOdpoved",
)
.with_response_data_namespace(soap::ISDMVS_MESSAGES_NS);
const READ_INFRASTRUCTURE_MANAGER_INQUIRY_RESULT: Operation = Operation::new(
    Service::R49,
    "ctiVysledekZjistiUzemiSpravcuDti",
    "CtiVysledekZjistiUzemiSpravcuDti",
    "CtiVysledekZjistiUzemiSpravcuDtiOdpoved",
);
const LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS: Operation = Operation::new(
    Service::R49,
    "ctiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
    "CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
    "CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDtiOdpoved",
);
const READ_INFRASTRUCTURE_MANAGER_INQUIRY_REPORT: Operation = Operation::new(
    Service::R49,
    "ctiVysledekZjistiUzemiSpravcuDtiReport",
    "CtiVysledekZjistiUzemiSpravcuDtiReport",
    "CtiVysledekZjistiUzemiSpravcuDtiReportOdpoved",
);

fn checked_page(page: PageRequest) -> Result<PageRequest> {
    Ok(PageRequest::new(page.offset, page.limit)?.with_total(page.include_total))
}

impl Client {
    /// Submits one R49 infrastructure-manager inquiry through `zjistiUzemiSpravcuDti`.
    ///
    /// The request contains either 1 through 400 RÚIAN parcel IDs or an S-JTSK
    /// area of at most 200 ha, according to its explicit selector. Exactly one
    /// submission is attempted, with no files and no automatic retries. The
    /// returned durable [`RequestId`] can be persisted and used with the three
    /// independent result operations.
    pub async fn submit_infrastructure_manager_inquiry(
        &self,
        request: &InfrastructureManagerInquiryRequest,
    ) -> Result<Response<RequestId>> {
        self.submit_infrastructure_manager_inquiry_with_correlation_id(
            CorrelationId::new(),
            request,
        )
        .await
    }

    /// Submits one R49 infrastructure-manager inquiry using an explicit SOAP correlation ID.
    ///
    /// Exactly one submission is attempted, with no files and no automatic retries. The
    /// correlation ID supports transport-level reconciliation; it is not the durable server-issued
    /// [`RequestId`]. The request selector is validated before dispatch.
    pub async fn submit_infrastructure_manager_inquiry_with_correlation_id(
        &self,
        correlation_id: CorrelationId,
        request: &InfrastructureManagerInquiryRequest,
    ) -> Result<Response<RequestId>> {
        request.selector.validate()?;
        let response = self
            .execute_submission(
                SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
                correlation_id,
                &[],
                |writer| inquiries::write_inquiry_request(writer, self.subject_id(), request),
                inquiries::decode_submission,
            )
            .await?;
        if response.metadata.state != ProcessingState::Accepted {
            return Err(Error::unexpected_submission_state(response));
        }
        Ok(response)
    }

    /// Reads the overall result through R49 `ctiVysledekZjistiUzemiSpravcuDti`.
    ///
    /// This performs exactly one request. Missing `Data` is returned as `None`;
    /// the common header state remains separate from parcel counts and the
    /// validation-completion flag. No part page or PDF report is retrieved.
    pub async fn read_infrastructure_manager_inquiry_result(
        &self,
        request_id: &RequestId,
    ) -> Result<Response<Option<OverallResult>>> {
        self.read_infrastructure_manager_inquiry_result_at(CorrelationId::new(), request_id)
            .await
    }

    async fn read_infrastructure_manager_inquiry_result_at(
        &self,
        correlation_id: CorrelationId,
        request_id: &RequestId,
    ) -> Result<Response<Option<OverallResult>>> {
        self.execute(
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_RESULT,
            correlation_id,
            |writer| inquiries::write_result_request(writer, request_id),
            inquiries::decode_overall_result,
        )
        .await
    }

    /// Reads one page of infrastructure parts through R49
    /// `ctiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti`.
    ///
    /// `only_valid` maps to optional `PouzeValidni`; `None` omits it. This method
    /// performs exactly one request without hidden pagination. Missing `Data`
    /// maps to an empty page at the requested offset. Valid and invalid parts,
    /// descriptions, shared registry people, and statement contacts are retained.
    ///
    /// R49 prose is inconsistent about whether a page may contain 250 records or
    /// must contain fewer than 250. The shared [`PageRequest`] currently permits
    /// 1 through 250; callers following the stricter wording should use at most
    /// 249.
    pub async fn list_infrastructure_manager_inquiry_parts(
        &self,
        request_id: &RequestId,
        only_valid: Option<bool>,
        page: PageRequest,
    ) -> Result<Response<Page<InfrastructureInquiryPart>>> {
        self.list_infrastructure_manager_inquiry_parts_at(
            CorrelationId::new(),
            request_id,
            only_valid,
            page,
        )
        .await
    }

    async fn list_infrastructure_manager_inquiry_parts_at(
        &self,
        correlation_id: CorrelationId,
        request_id: &RequestId,
        only_valid: Option<bool>,
        page: PageRequest,
    ) -> Result<Response<Page<InfrastructureInquiryPart>>> {
        let page = checked_page(page)?;
        self.execute(
            LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
            correlation_id,
            |writer| inquiries::write_parts_request(writer, request_id, only_valid, page),
            |data| inquiries::decode_parts(data, page.offset),
        )
        .await
    }

    /// Reads the PDF report through R49
    /// `ctiVysledekZjistiUzemiSpravcuDtiReport`.
    ///
    /// Exactly one request is performed. The report may be inline base64 or
    /// MTOM encoded and is returned as bounded original bytes plus file metadata.
    /// A bare 64-digit checksum remains algorithm-unspecified. No PDF structure
    /// or digital signature is parsed or verified. Missing `Data` returns `None`.
    pub async fn read_infrastructure_manager_inquiry_report(
        &self,
        request_id: &RequestId,
    ) -> Result<Response<Option<FilePayload>>> {
        self.read_infrastructure_manager_inquiry_report_at(CorrelationId::new(), request_id)
            .await
    }

    async fn read_infrastructure_manager_inquiry_report_at(
        &self,
        correlation_id: CorrelationId,
        request_id: &RequestId,
    ) -> Result<Response<Option<FilePayload>>> {
        self.execute_with_files(
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_REPORT,
            correlation_id,
            |writer| inquiries::write_result_request(writer, request_id),
            inquiries::decode_report,
        )
        .await
    }

    /// Polls only the R49 overall result until it is complete or the configured
    /// bounded wait ends.
    ///
    /// Polling uses [`WaitOptions`], including its minimum 60-second interval and
    /// total deadline that also bounds an in-flight request. Dropping the future
    /// cancels waiting; no background task is spawned. This helper never submits
    /// another inquiry and never retrieves part pages or the PDF report.
    pub async fn wait_for_infrastructure_manager_inquiry(
        &self,
        request_id: &RequestId,
        options: WaitOptions,
    ) -> Result<Response<OverallResult>> {
        super::lifecycle::wait_for_async(
            request_id,
            options,
            |_| false,
            || self.read_infrastructure_manager_inquiry_result(request_id),
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use wiremock::matchers::{body_string, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;
    use crate::model::InfrastructureManagerInquirySelector;

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

    fn request() -> InfrastructureManagerInquiryRequest {
        InfrastructureManagerInquiryRequest::new(
            InfrastructureManagerInquirySelector::parcels(vec![5_000_000_000]).unwrap(),
            "business-identification",
        )
        .unwrap()
    }

    fn response_envelope(
        operation: Operation,
        request_id: CorrelationId,
        state: &str,
        data: Option<&str>,
    ) -> String {
        let request_id = request_id.as_uuid();
        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 = match state {
            "Prijato" => "1010",
            "ProbihaZpracovani" => "1020",
            _ => "1030",
        };
        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_id}</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,
        )
    }

    async fn expect_exchange(
        server: &MockServer,
        operation: Operation,
        request: Vec<u8>,
        status: u16,
        response: String,
    ) {
        Mock::given(method("POST"))
            .and(path(format!("/{}", operation.service.path())))
            .and(header("SOAPAction", format!("\"{}\"", operation.action)))
            .and(header("Content-Type", "text/xml; charset=utf-8"))
            .and(body_string(String::from_utf8(request).unwrap()))
            .respond_with(
                ResponseTemplate::new(status).set_body_raw(response, "text/xml; charset=utf-8"),
            )
            .expect(1)
            .mount(server)
            .await;
    }

    #[test]
    fn operation_descriptors_match_all_four_official_r49_operations() {
        let descriptors = [
            (
                SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
                "zjistiUzemiSpravcuDti",
                "ZjistiUzemiSpravcuDti",
                "ZjistiUzemiSpravcuDtiOdpoved",
            ),
            (
                READ_INFRASTRUCTURE_MANAGER_INQUIRY_RESULT,
                "ctiVysledekZjistiUzemiSpravcuDti",
                "CtiVysledekZjistiUzemiSpravcuDti",
                "CtiVysledekZjistiUzemiSpravcuDtiOdpoved",
            ),
            (
                LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
                "ctiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
                "CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDti",
                "CtiVysledekZjistiUzemiSpravcuDtiSeznamCastiDtiOdpoved",
            ),
            (
                READ_INFRASTRUCTURE_MANAGER_INQUIRY_REPORT,
                "ctiVysledekZjistiUzemiSpravcuDtiReport",
                "CtiVysledekZjistiUzemiSpravcuDtiReport",
                "CtiVysledekZjistiUzemiSpravcuDtiReportOdpoved",
            ),
        ];
        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(), "R49ZjisteniUzemiSpravcuDti");
            assert_eq!(
                operation.service.namespace(),
                "urn:cz:isvs:dmvs:isdmvs:schemas:R49ZjisteniUzemiSpravcuDti:v1"
            );
        }
        assert_eq!(
            SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY.response_data_namespace,
            soap::ISDMVS_MESSAGES_NS
        );
        for operation in [
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_RESULT,
            LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_REPORT,
        ] {
            assert_eq!(operation.response_data_namespace, Service::R49.namespace());
        }
    }

    #[tokio::test]
    async fn accepted_http_202_submission_returns_id_after_exactly_one_request() {
        let server = MockServer::start().await;
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let request = request();
        let body = soap::request(
            SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
            correlation_id,
            |writer| {
                inquiries::write_inquiry_request(
                    writer,
                    &crate::SubjectId::new("requester-id").unwrap(),
                    &request,
                )
            },
        )
        .unwrap();
        expect_exchange(
            &server,
            SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
            body,
            202,
            response_envelope(
                SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
                correlation_id,
                "Prijato",
                Some("<msg:IdPozadavku>durable-request-id</msg:IdPozadavku>"),
            ),
        )
        .await;

        let client = Client::test_client(server.uri());
        let response = client
            .submit_infrastructure_manager_inquiry_with_correlation_id(correlation_id, &request)
            .await
            .unwrap();
        assert_eq!(response.value.as_str(), "durable-request-id");
        assert_eq!(response.metadata.state, ProcessingState::Accepted);
        assert_eq!(response.metadata.request_id, correlation_id);
        assert_eq!(server.received_requests().await.unwrap().len(), 1);
        server.verify().await;
    }

    #[tokio::test]
    async fn non_accepted_submission_recovers_response_without_an_automatic_retry() {
        let server = MockServer::start().await;
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        Mock::given(method("POST"))
            .and(path("/R49ZjisteniUzemiSpravcuDti"))
            .and(header("SOAPAction", "\"zjistiUzemiSpravcuDti\""))
            .respond_with(ResponseTemplate::new(202).set_body_raw(
                response_envelope(
                    SUBMIT_INFRASTRUCTURE_MANAGER_INQUIRY,
                    correlation_id,
                    "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 error = client
            .submit_infrastructure_manager_inquiry_with_correlation_id(correlation_id, &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;
    }

    #[tokio::test]
    async fn overall_parts_and_report_are_independent_exact_requests() {
        let server = MockServer::start().await;
        let correlation_id: CorrelationId = REQUEST_UUID.parse().unwrap();
        let request_id = RequestId::new("durable-request-id").unwrap();
        for operation in [
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_RESULT,
            READ_INFRASTRUCTURE_MANAGER_INQUIRY_REPORT,
        ] {
            let body = soap::request(operation, correlation_id, |writer| {
                inquiries::write_result_request(writer, &request_id)
            })
            .unwrap();
            let data = (operation.response == "CtiVysledekZjistiUzemiSpravcuDtiOdpoved").then_some(
                "<r:IdPodani>submission-id</r:IdPodani><r:Parcely/><r:PocetCastiDti>0</r:PocetCastiDti><r:ValidaceDokoncena>true</r:ValidaceDokoncena><r:PocetValidnichCastiDti>0</r:PocetValidnichCastiDti>",
            );
            expect_exchange(
                &server,
                operation,
                body,
                200,
                response_envelope(operation, correlation_id, "Zpracovano", data),
            )
            .await;
        }
        let page = PageRequest {
            offset: 5,
            limit: 25,
            include_total: false,
        };
        let body = soap::request(
            LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
            correlation_id,
            |writer| inquiries::write_parts_request(writer, &request_id, Some(false), page),
        )
        .unwrap();
        expect_exchange(
            &server,
            LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
            body,
            200,
            response_envelope(
                LIST_INFRASTRUCTURE_MANAGER_INQUIRY_PARTS,
                correlation_id,
                "ProbihaZpracovani",
                None,
            ),
        )
        .await;

        let client = Client::test_client(server.uri());
        let overall = client
            .read_infrastructure_manager_inquiry_result_at(correlation_id, &request_id)
            .await
            .unwrap();
        assert_eq!(overall.value.unwrap().infrastructure_part_count, 0);
        let parts = client
            .list_infrastructure_manager_inquiry_parts_at(
                correlation_id,
                &request_id,
                Some(false),
                page,
            )
            .await
            .unwrap();
        assert_eq!(parts.value.offset, 5);
        assert!(parts.value.items.is_empty());
        let report = client
            .read_infrastructure_manager_inquiry_report_at(correlation_id, &request_id)
            .await
            .unwrap();
        assert!(report.value.is_none());
        assert_eq!(server.received_requests().await.unwrap().len(), 3);
        server.verify().await;
    }

    #[tokio::test]
    async fn bounded_wait_rejects_fast_polling_before_any_transport() {
        let server = MockServer::start().await;
        let client = Client::test_client(server.uri());
        let options = WaitOptions {
            interval: Duration::from_secs(59),
            ..WaitOptions::default()
        };
        let error = client
            .wait_for_infrastructure_manager_inquiry(
                &RequestId::new("durable-request-id").unwrap(),
                options,
            )
            .await
            .unwrap_err();
        assert!(matches!(error, Error::InvalidInput { .. }));
        assert!(server.received_requests().await.unwrap().is_empty());
    }
}