fhir 2.0.0

Fast Healthcare Interoperability Resources (FHIR) data model for Rust: the complete FHIR R5, R4, and R3 resources, datatypes, and code systems as serde-serializable types, plus a spec-driven code generator.
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! An async FHIR REST client (feature `client`).
//!
//! [`Client`] wraps a [`reqwest`] client and speaks the FHIR RESTful API:
//! `read`, `vread`, `create`, `update`, `delete`, `search`, and `capabilities`.
//! Non-success responses are surfaced as [`ClientError`], parsing the server's
//! `OperationOutcome` when present.
//!
//! ```no_run
//! # async fn demo() -> Result<(), fhir::client::ClientError> {
//! use fhir::client::Client;
//!
//! let client = Client::new("https://hapi.fhir.org/baseR5");
//! let patient = client.read("Patient", "example").await?;
//! println!("{patient:?}");
//! # Ok(()) }
//! ```
//!
//! # Choosing a release
//!
//! The wire protocol is the same for every FHIR release; only the resource
//! types differ. [`ReleaseClient<R>`] is therefore generic over a
//! [`Release`](crate::release::Release), and each release module exposes an
//! alias for it: [`Client`] here (and [`r5::client::Client`](crate::r5::client))
//! for R5, [`r4::client::Client`](crate::r4::client) for R4.
//!
//! ```no_run
//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
//! let r4 = fhir::r4::client::Client::new("https://hapi.fhir.org/baseR4");
//! let bundle = r4.search("Patient", &[("name", "chalmers")]).await?;
//! # Ok(()) }
//! ```

use ::serde::Serialize;

use crate::release::Release;

/// FHIR JSON media type.
const FHIR_JSON: &str = "application/fhir+json";

/// Whether a failure is worth retrying: transport trouble, or a server that
/// said it could not answer *this time*. A 4xx is the client's fault and will
/// fail identically on a second attempt.
fn is_retryable<R: Release>(e: &ReleaseClientError<R>) -> bool {
    match e {
        ReleaseClientError::Http(e) => e.is_timeout() || e.is_connect() || e.is_request(),
        ReleaseClientError::Outcome { status, .. } | ReleaseClientError::Status { status, .. } => {
            *status >= 500 || *status == 429
        }
        ReleaseClientError::Url(_) | ReleaseClientError::BodyTooLarge { .. } => false,
    }
}

/// An error from a FHIR REST interaction with release `R`.
///
/// Most code wants the release-specific alias — [`ClientError`] for R5, or
/// [`r4::client::ClientError`](crate::r4::client) for R4.
pub enum ReleaseClientError<R: Release> {
    /// A transport or (de)serialization error from `reqwest`.
    Http(reqwest::Error),
    /// The server returned an error status with an `OperationOutcome` body.
    Outcome {
        /// HTTP status code.
        status: u16,
        /// The parsed outcome.
        outcome: Box<R::OperationOutcome>,
    },
    /// The server returned an error status without a parseable `OperationOutcome`.
    Status {
        /// HTTP status code.
        status: u16,
        /// The response body, truncated. **May contain PHI** — a server that
        /// failed to produce an `OperationOutcome` may have echoed the
        /// resource instead, so do not log this at large (spec R13.10).
        body: String,
    },
    /// The resource type or id could not be made into a URL.
    Url(String),
    /// The response exceeded the configured body cap (spec R13.5).
    BodyTooLarge {
        /// The cap that was exceeded, in bytes.
        limit: usize,
    },
}

// Written by hand rather than derived: `#[derive(Debug)]` would demand
// `R: Debug` of the release marker, which says nothing about whether the error
// can be printed.
// `body` is omitted from `Debug` deliberately: it can hold a resource, and
// `Debug` output reaches logs and panic messages (spec R13.10).
#[allow(clippy::missing_fields_in_debug)]
impl<R: Release> std::fmt::Debug for ReleaseClientError<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReleaseClientError::Http(e) => f.debug_tuple("Http").field(e).finish(),
            ReleaseClientError::Outcome { status, outcome } => f
                .debug_struct("Outcome")
                .field("status", status)
                .field("outcome", outcome)
                .finish(),
            // The body is deliberately not printed: `Debug` output ends up in
            // logs and panic messages, and this field may hold a resource
            // (spec R13.10).
            ReleaseClientError::Status { status, body } => f
                .debug_struct("Status")
                .field("status", status)
                .field("body_len", &body.len())
                .finish_non_exhaustive(),
            ReleaseClientError::Url(msg) => f.debug_tuple("Url").field(msg).finish(),
            ReleaseClientError::BodyTooLarge { limit } => f
                .debug_struct("BodyTooLarge")
                .field("limit", limit)
                .finish(),
        }
    }
}

impl<R: Release> std::fmt::Display for ReleaseClientError<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReleaseClientError::Http(e) => write!(f, "HTTP error: {e}"),
            ReleaseClientError::Outcome { status, .. } => {
                write!(f, "FHIR error status {status} (OperationOutcome)")
            }
            ReleaseClientError::Status { status, .. } => write!(f, "error status {status}"),
            ReleaseClientError::Url(msg) => write!(f, "cannot build request URL: {msg}"),
            ReleaseClientError::BodyTooLarge { limit } => {
                write!(f, "response body exceeds {limit} bytes")
            }
        }
    }
}

impl<R: Release> std::error::Error for ReleaseClientError<R> {}

impl<R: Release> From<reqwest::Error> for ReleaseClientError<R> {
    fn from(e: reqwest::Error) -> Self {
        ReleaseClientError::Http(e)
    }
}

/// An async FHIR REST client for a single service base URL, speaking release `R`.
///
/// Most code wants the release-specific alias — [`Client`] for R5, or
/// [`r4::client::Client`](crate::r4::client) for R4.
/// Defaults chosen so that a client built with [`ReleaseClient::new`] is safe
/// to point at a network you do not control (spec R13.5).
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// 64 MiB: larger than any single resource has business being, smaller than
/// an amount of memory a hostile or broken peer should be able to make us
/// allocate.
const DEFAULT_MAX_BODY: usize = 64 * 1024 * 1024;

/// How many times an idempotent request is retried, and how long it waits.
///
/// Only `GET`, `PUT`, and `DELETE` are retried: FHIR `POST` creates a new
/// resource each time, so retrying one after a timeout is how a patient ends
/// up in the chart twice (spec R13.8).
#[derive(Debug, Clone, Copy)]
pub struct RetryPolicy {
    /// Additional attempts after the first. Zero disables retrying.
    pub attempts: u32,
    /// Delay before the first retry; doubled each time.
    pub backoff: std::time::Duration,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            attempts: 0,
            backoff: std::time::Duration::from_millis(200),
        }
    }
}

/// Supplies a bearer token per request, so credentials are not baked into a
/// hand-built `reqwest::Client` and can be refreshed (spec R13.9).
type TokenSource = std::sync::Arc<dyn Fn() -> Option<String> + Send + Sync>;

#[derive(Clone)]
pub struct ReleaseClient<R: Release> {
    base_url: String,
    http: reqwest::Client,
    auth: Option<TokenSource>,
    retry: RetryPolicy,
    max_body: usize,
    release: std::marker::PhantomData<R>,
}

// As with the error type, deriving would impose a needless `R: Debug`.
impl<R: Release> std::fmt::Debug for ReleaseClient<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReleaseClient")
            .field("base_url", &self.base_url)
            .field("http", &self.http)
            .field("release", &R::LABEL)
            // Whether a token supplier is configured, never what it returns:
            // this is a debug dump, and a bearer token is a credential.
            .field("auth", &self.auth.as_ref().map(|_| "<token supplier>"))
            .field("retry", &self.retry)
            .field("max_body", &self.max_body)
            .finish()
    }
}

impl<R: Release> ReleaseClient<R> {
    /// A client for the given service base URL (e.g. `https://.../baseR5`).
    /// A client for the given service base URL (e.g. `https://.../baseR5`),
    /// with request and connect timeouts already set.
    ///
    /// `reqwest::Client::new()` has *no* timeout, so a client built on it
    /// waits forever on a server that accepts the connection and then stops
    /// talking — which is what a stalled FHIR server looks like from the
    /// outside (spec R13.5).
    #[must_use]
    pub fn new(base_url: impl Into<String>) -> Self {
        let http = reqwest::Client::builder()
            .timeout(DEFAULT_TIMEOUT)
            .connect_timeout(DEFAULT_CONNECT_TIMEOUT)
            .build()
            .unwrap_or_default();
        Self::with_http(base_url, http)
    }

    /// A client using a caller-provided `reqwest::Client` (for custom TLS,
    /// timeouts, proxies, …).
    ///
    /// The caller owns the timeout policy here: nothing is added to a client
    /// you built yourself.
    #[must_use]
    pub fn with_http(base_url: impl Into<String>, http: reqwest::Client) -> Self {
        let base_url = base_url.into().trim_end_matches('/').to_string();
        Self {
            base_url,
            http,
            auth: None,
            retry: RetryPolicy::default(),
            max_body: DEFAULT_MAX_BODY,
            release: std::marker::PhantomData,
        }
    }

    /// Attach a bearer-token supplier, called once per request so a token can
    /// be refreshed without rebuilding the client.
    #[must_use]
    pub fn with_bearer_token<F>(mut self, source: F) -> Self
    where
        F: Fn() -> Option<String> + Send + Sync + 'static,
    {
        self.auth = Some(std::sync::Arc::new(source));
        self
    }

    /// Retry idempotent requests (`GET`, `PUT`, `DELETE`) on transport
    /// failure or 5xx, with exponential backoff.
    #[must_use]
    pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
        self.retry = retry;
        self
    }

    /// Cap the response body this client will buffer.
    #[must_use]
    pub fn with_max_body(mut self, bytes: usize) -> Self {
        self.max_body = bytes;
        self
    }

    /// Build a request URL, percent-encoding each path segment.
    ///
    /// Interpolating an id straight into a URL lets `../Patient/other` — or
    /// anything containing `?` or `#` — address a different interaction than
    /// the caller asked for (spec R13.6).
    fn url(&self, segments: &[&str]) -> Result<reqwest::Url, ReleaseClientError<R>> {
        let mut url = reqwest::Url::parse(&self.base_url)
            .map_err(|e| ReleaseClientError::Url(format!("{}: {e}", self.base_url)))?;
        {
            let mut path = url.path_segments_mut().map_err(|()| {
                ReleaseClientError::Url("base URL cannot have path segments".into())
            })?;
            for s in segments {
                path.push(s);
            }
        }
        Ok(url)
    }

    /// Send a request: attach auth and `Accept`, retry when the policy allows
    /// it, and turn a non-success status into a [`ReleaseClientError`]
    /// (parsing an `OperationOutcome` from the body when possible).
    async fn send(
        &self,
        req: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, ReleaseClientError<R>> {
        let idempotent = req
            .try_clone()
            .and_then(|r| r.build().ok())
            .is_some_and(|r| {
                matches!(
                    *r.method(),
                    reqwest::Method::GET | reqwest::Method::PUT | reqwest::Method::DELETE
                )
            });
        let mut delay = self.retry.backoff;
        let tries = if idempotent { self.retry.attempts } else { 0 };
        for attempt in 0..=tries {
            let Some(this) = req.try_clone() else {
                // A streaming body cannot be replayed; send once.
                return self.send_once(req).await;
            };
            match self.send_once(this).await {
                Ok(resp) => return Ok(resp),
                Err(e) if attempt < tries && is_retryable(&e) => {
                    tokio::time::sleep(delay).await;
                    delay *= 2;
                }
                Err(e) => return Err(e),
            }
        }
        self.send_once(req).await
    }

    async fn send_once(
        &self,
        req: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, ReleaseClientError<R>> {
        let mut req = req.header(reqwest::header::ACCEPT, FHIR_JSON);
        if let Some(source) = &self.auth
            && let Some(token) = source()
        {
            req = req.bearer_auth(token);
        }
        let resp = req.send().await?;
        if resp.status().is_success() {
            return Ok(resp);
        }
        let status = resp.status().as_u16();
        let body = self.body_capped(resp).await?;
        match ::serde_json::from_str::<R::OperationOutcome>(&body) {
            Ok(outcome) => Err(ReleaseClientError::Outcome {
                status,
                outcome: Box::new(outcome),
            }),
            Err(_) => Err(ReleaseClientError::Status {
                status,
                // Truncated: an error body from a non-conformant server may
                // be the resource itself (spec R13.10).
                body: body.chars().take(2048).collect(),
            }),
        }
    }

    /// Buffer a response body, refusing to grow past the configured cap.
    ///
    /// `resp.text()` would happily allocate whatever a peer sends.
    async fn body_capped(
        &self,
        mut resp: reqwest::Response,
    ) -> Result<String, ReleaseClientError<R>> {
        if resp
            .content_length()
            .is_some_and(|n| n > self.max_body as u64)
        {
            return Err(ReleaseClientError::BodyTooLarge {
                limit: self.max_body,
            });
        }
        let mut buf: Vec<u8> = Vec::new();
        while let Some(chunk) = resp.chunk().await? {
            if buf.len() + chunk.len() > self.max_body {
                return Err(ReleaseClientError::BodyTooLarge {
                    limit: self.max_body,
                });
            }
            buf.extend_from_slice(&chunk);
        }
        String::from_utf8(buf).map_err(|e| ReleaseClientError::Url(e.to_string()))
    }

    /// Deserialize a success response, honoring the body cap.
    async fn json<T: ::serde::de::DeserializeOwned>(
        &self,
        resp: reqwest::Response,
    ) -> Result<T, ReleaseClientError<R>> {
        let body = self.body_capped(resp).await?;
        ::serde_json::from_str(&body).map_err(|e| ReleaseClientError::Status {
            status: 200,
            body: format!("malformed FHIR JSON: {e}"),
        })
    }

    /// `GET [base]/[type]/[id]` — read the current version of a resource.
    pub async fn read(
        &self,
        resource_type: &str,
        id: &str,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        Ok(self.read_with_etag(resource_type, id).await?.0)
    }

    /// `read`, also returning the response `ETag`.
    ///
    /// The ETag is what a later `update_if_match` needs, so a read-then-write
    /// cycle can be safe against a concurrent writer (spec R13.7). Without
    /// it, every update is last-write-wins.
    pub async fn read_with_etag(
        &self,
        resource_type: &str,
        id: &str,
    ) -> Result<(R::Resource, Option<String>), ReleaseClientError<R>> {
        let url = self.url(&[resource_type, id])?;
        let resp = self.send(self.http.get(url)).await?;
        let etag = resp
            .headers()
            .get(reqwest::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        Ok((self.json(resp).await?, etag))
    }

    /// `GET [base]/[type]/[id]/_history/[vid]` — read a specific version.
    pub async fn vread(
        &self,
        resource_type: &str,
        id: &str,
        version_id: &str,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        let url = self.url(&[resource_type, id, "_history", version_id])?;
        let resp = self.send(self.http.get(url)).await?;
        self.json(resp).await
    }

    /// `POST [base]/[type]` — create a resource; returns the server's copy.
    pub async fn create<T: Serialize>(
        &self,
        resource_type: &str,
        resource: &T,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        let url = self.url(&[resource_type])?;
        let resp = self.send(self.http.post(url).json(resource)).await?;
        self.json(resp).await
    }

    /// `POST [base]/[type]` with `If-None-Exist` — create only if the search
    /// criteria match nothing.
    ///
    /// The server answers 201 with the new resource, or 200 with the existing
    /// one. This is how a client avoids creating a duplicate patient when a
    /// previous attempt's response was lost (spec R13.7).
    pub async fn create_conditional<T: Serialize>(
        &self,
        resource_type: &str,
        resource: &T,
        if_none_exist: &str,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        let url = self.url(&[resource_type])?;
        let resp = self
            .send(
                self.http
                    .post(url)
                    .header("If-None-Exist", if_none_exist)
                    .json(resource),
            )
            .await?;
        self.json(resp).await
    }

    /// `PUT [base]/[type]/[id]` — update (or create) a resource at a known id.
    pub async fn update<T: Serialize>(
        &self,
        resource_type: &str,
        id: &str,
        resource: &T,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        self.put(resource_type, id, resource, None).await
    }

    /// `update`, but only if the server's current version still matches
    /// `etag` — otherwise the server answers 412 and nothing is overwritten.
    pub async fn update_if_match<T: Serialize>(
        &self,
        resource_type: &str,
        id: &str,
        resource: &T,
        etag: &str,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        self.put(resource_type, id, resource, Some(etag)).await
    }

    async fn put<T: Serialize>(
        &self,
        resource_type: &str,
        id: &str,
        resource: &T,
        etag: Option<&str>,
    ) -> Result<R::Resource, ReleaseClientError<R>> {
        let url = self.url(&[resource_type, id])?;
        let mut req = self.http.put(url).json(resource);
        if let Some(etag) = etag {
            req = req.header(reqwest::header::IF_MATCH, etag);
        }
        let resp = self.send(req).await?;
        self.json(resp).await
    }

    /// `DELETE [base]/[type]/[id]`.
    pub async fn delete(&self, resource_type: &str, id: &str) -> Result<(), ReleaseClientError<R>> {
        let url = self.url(&[resource_type, id])?;
        self.send(self.http.delete(url)).await?;
        Ok(())
    }

    /// `delete`, but only if the server's current version still matches.
    pub async fn delete_if_match(
        &self,
        resource_type: &str,
        id: &str,
        etag: &str,
    ) -> Result<(), ReleaseClientError<R>> {
        let url = self.url(&[resource_type, id])?;
        self.send(
            self.http
                .delete(url)
                .header(reqwest::header::IF_MATCH, etag),
        )
        .await?;
        Ok(())
    }

    /// `GET [base]/[type]?[params]` — search, returning the first page.
    pub async fn search(
        &self,
        resource_type: &str,
        params: &[(&str, &str)],
    ) -> Result<R::Bundle, ReleaseClientError<R>> {
        let url = self.url(&[resource_type])?;
        let resp = self.send(self.http.get(url).query(params)).await?;
        self.json(resp).await
    }

    /// Follow a searchset's `next` link, if it has one.
    ///
    /// Returns `None` at the last page, so a caller can loop without parsing
    /// links itself.
    pub async fn next_page(
        &self,
        bundle: &R::Bundle,
    ) -> Result<Option<R::Bundle>, ReleaseClientError<R>> {
        let Some(next) = R::next_link(bundle) else {
            return Ok(None);
        };
        // The link is a server-supplied absolute URL; it is used as given.
        let resp = self.send(self.http.get(next)).await?;
        Ok(Some(self.json(resp).await?))
    }

    /// Search and follow `next` links, collecting up to `max_pages` bundles.
    ///
    /// Bounded on purpose: a server whose paging never terminates should cost
    /// a caller a known number of requests, not an unbounded loop.
    pub async fn search_all(
        &self,
        resource_type: &str,
        params: &[(&str, &str)],
        max_pages: usize,
    ) -> Result<Vec<R::Bundle>, ReleaseClientError<R>> {
        let mut pages = Vec::new();
        let mut current = self.search(resource_type, params).await?;
        loop {
            let next = self.next_page(&current).await?;
            pages.push(current);
            match next {
                Some(b) if pages.len() < max_pages => current = b,
                _ => return Ok(pages),
            }
        }
    }

    /// `GET [base]/metadata` — the server's `CapabilityStatement`.
    pub async fn capabilities(&self) -> Result<R::CapabilityStatement, ReleaseClientError<R>> {
        let url = self.url(&["metadata"])?;
        let resp = self.send(self.http.get(url)).await?;
        self.json(resp).await
    }
}

/// An async FHIR R5 REST client.
#[cfg(feature = "r5")]
pub type Client = ReleaseClient<crate::r5::R5>;

/// An error from a FHIR R5 REST interaction.
#[cfg(feature = "r5")]
pub type ClientError = ReleaseClientError<crate::r5::R5>;

#[cfg(test)]
#[cfg(feature = "r5")]
mod tests {
    use super::*;
    use crate::r5::resources::Resource;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn read_returns_resource() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/Patient/pat-1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(::serde_json::json!({
                    "resourceType": "Patient", "id": "pat-1", "active": true
                })),
            )
            .mount(&server)
            .await;

        let client = Client::new(server.uri());
        let resource = client.read("Patient", "pat-1").await.unwrap();
        match resource {
            Resource::Patient(p) => assert_eq!(p.id.unwrap().0, "pat-1"),
            other => panic!("expected Patient, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn search_returns_bundle() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/Patient"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(::serde_json::json!({
                    "resourceType": "Bundle", "type": "searchset",
                    "entry": [{ "resource": { "resourceType": "Patient", "id": "a" } }]
                })),
            )
            .mount(&server)
            .await;

        let client = Client::new(server.uri());
        let bundle = client
            .search("Patient", &[("name", "chalmers")])
            .await
            .unwrap();
        assert_eq!(bundle.iter_resources().count(), 1);
    }

    /// Spec 13 acceptance 5: an id is data, not a path.
    #[tokio::test]
    async fn a_hostile_id_cannot_retarget_the_request() {
        let server = MockServer::start().await;
        // The *encoded* path is what the server must see. If `id` were
        // interpolated raw, this would read `/Patient/other` instead.
        Mock::given(method("GET"))
            .and(path("/Patient/..%2FPatient%2Fother"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(::serde_json::json!({
                    "resourceType": "Patient", "id": "safe"
                })),
            )
            .mount(&server)
            .await;

        let client = Client::new(server.uri());
        let resource = client
            .read("Patient", "../Patient/other")
            .await
            .expect("the encoded path is the one requested");
        match resource {
            Resource::Patient(p) => assert_eq!(p.id.unwrap().0, "safe"),
            other => panic!("expected Patient, got {other:?}"),
        }
    }

    /// Spec 13 acceptance 4: a server that accepts the connection and then
    /// stops talking must produce a timeout, not a hang.
    #[tokio::test]
    async fn a_stalled_server_times_out() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/Patient/slow"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_delay(std::time::Duration::from_secs(30))
                    .set_body_json(::serde_json::json!({"resourceType": "Patient"})),
            )
            .mount(&server)
            .await;

        let http = reqwest::Client::builder()
            .timeout(std::time::Duration::from_millis(150))
            .build()
            .expect("client");
        let client = Client::with_http(server.uri(), http);
        let err = client
            .read("Patient", "slow")
            .await
            .expect_err("should time out");
        match err {
            ClientError::Http(e) => assert!(e.is_timeout(), "expected a timeout, got {e}"),
            other => panic!("expected a transport timeout, got {other:?}"),
        }
    }

    /// The body cap is a ceiling on what a peer can make us allocate.
    #[tokio::test]
    async fn an_oversized_body_is_refused() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/Patient/big"))
            .respond_with(ResponseTemplate::new(200).set_body_string("x".repeat(4096)))
            .mount(&server)
            .await;

        let client = Client::new(server.uri()).with_max_body(1024);
        match client.read("Patient", "big").await {
            Err(ClientError::BodyTooLarge { limit }) => assert_eq!(limit, 1024),
            other => panic!("expected BodyTooLarge, got {other:?}"),
        }
    }

    /// `Debug` output reaches logs and panic messages, so it must not carry
    /// a resource (spec R13.10).
    #[test]
    fn debug_output_does_not_leak_the_body() {
        let err: ClientError = ReleaseClientError::Status {
            status: 500,
            body: "{\"resourceType\":\"Patient\",\"name\":[{\"family\":\"Sensitive\"}]}"
                .to_string(),
        };
        let rendered = format!("{err:?}");
        assert!(!rendered.contains("Sensitive"), "leaked: {rendered}");
        assert!(rendered.contains("body_len"));
    }

    #[tokio::test]
    async fn error_status_parses_operation_outcome() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/Patient/missing"))
            .respond_with(
                ResponseTemplate::new(404).set_body_json(::serde_json::json!({
                    "resourceType": "OperationOutcome",
                    "issue": [{ "severity": "error", "code": "not-found",
                                "diagnostics": "no such Patient" }]
                })),
            )
            .mount(&server)
            .await;

        let client = Client::new(server.uri());
        let err = client.read("Patient", "missing").await.unwrap_err();
        match err {
            ClientError::Outcome { status, outcome } => {
                assert_eq!(status, 404);
                assert_eq!(outcome.issue.len(), 1);
            }
            other => panic!("expected Outcome, got {other:?}"),
        }
    }
}