churchtools-api 0.1.0

Synchronous client for the ChurchTools REST API, generated from its OpenAPI description
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use reqwest::blocking::RequestBuilder;
use serde::Deserialize;
use serde::de::DeserializeOwned;

use crate::error::{ApiError, Error, Result};

/// Query parameters as sent on the wire; array parameters appear once per value
/// (`ids[]=1&ids[]=2`).
pub type Query = Vec<(String, String)>;

/// Default for [`ClientBuilder::max_response_size`]: 256 MiB.
pub const DEFAULT_MAX_RESPONSE_SIZE: u64 = 256 * 1024 * 1024;

const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// How often a request answered with a retryable status is repeated.
const MAX_RETRIES: u32 = 3;
/// Statuses after which an idempotent request is repeated: the gateway or
/// the server was briefly unavailable. `429` is repeated for every method.
const RETRY_STATUSES: [u16; 3] = [502, 503, 504];
/// Wait before repeating a request whose connection could not be established.
const CONNECT_RETRY_WAIT: Duration = Duration::from_secs(1);
/// Upper bound for waiting on a `Retry-After` header.
const MAX_RETRY_WAIT: Duration = Duration::from_secs(60);

/// HTTP method of a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Method {
    Get,
    Post,
    Put,
    Patch,
    Delete,
}

impl Method {
    /// The method name as sent on the wire, e.g. `GET`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Patch => "PATCH",
            Self::Delete => "DELETE",
        }
    }

    /// Whether a request may be repeated after the server was briefly
    /// unavailable: all but POST and PATCH.
    fn is_idempotent(self) -> bool {
        !matches!(self, Self::Post | Self::Patch)
    }

    fn to_reqwest(self) -> reqwest::Method {
        match self {
            Self::Get => reqwest::Method::GET,
            Self::Post => reqwest::Method::POST,
            Self::Put => reqwest::Method::PUT,
            Self::Patch => reqwest::Method::PATCH,
            Self::Delete => reqwest::Method::DELETE,
        }
    }
}

impl std::fmt::Display for Method {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Error of [`Method::from_str`](std::str::FromStr): not one of the supported methods.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidMethod(pub String);

impl std::fmt::Display for InvalidMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid HTTP method: {}", self.0)
    }
}

impl std::error::Error for InvalidMethod {}

impl std::str::FromStr for Method {
    type Err = InvalidMethod;

    /// Parses the method name, case-insensitively.
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "GET" => Ok(Self::Get),
            "POST" => Ok(Self::Post),
            "PUT" => Ok(Self::Put),
            "PATCH" => Ok(Self::Patch),
            "DELETE" => Ok(Self::Delete),
            _ => Err(InvalidMethod(s.to_owned())),
        }
    }
}

/// Synchronous ChurchTools API client.
///
/// Cloning is cheap: the connection pool and the rate limit are shared.
///
/// The client blocks (it uses `reqwest::blocking`) and panics when created,
/// used or dropped inside an async runtime such as Tokio. From async code,
/// call it in `tokio::task::spawn_blocking`.
#[derive(Clone)]
pub struct Client {
    http: reqwest::blocking::Client,
    api_url: String,
    token: Option<String>,
    timeout: Duration,
    connect_timeout: Duration,
    max_response_size: u64,
    throttle: Option<Arc<Throttle>>,
}

impl std::fmt::Debug for Client {
    // Hand-written so the token never ends up in logs.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("api_url", &self.api_url)
            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
            .field("timeout", &self.timeout)
            .field("connect_timeout", &self.connect_timeout)
            .field("max_response_size", &self.max_response_size)
            .field("throttle", &self.throttle)
            .finish_non_exhaustive()
    }
}

/// A file for an upload endpoint.
///
/// The content is shared: cloning an `Upload` or retrying the request does
/// not copy it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upload {
    pub filename: String,
    pub content: Arc<[u8]>,
    /// MIME type, e.g. `application/pdf`.
    pub content_type: String,
}

impl Upload {
    pub fn new(filename: impl Into<String>, content: impl Into<Arc<[u8]>>, content_type: impl Into<String>) -> Self {
        Self {
            filename: filename.into(),
            content: content.into(),
            content_type: content_type.into(),
        }
    }

    /// Reads a file; the MIME type is guessed from the extension.
    pub fn from_path(path: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
        let path = path.as_ref();
        let filename = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        let content_type = guess_content_type(&filename);
        Ok(Self::new(filename, std::fs::read(path)?, content_type))
    }
}

fn guess_content_type(filename: &str) -> &'static str {
    let ext = filename.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    match ext.as_str() {
        "pdf" => "application/pdf",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "txt" => "text/plain",
        "csv" => "text/csv",
        "xml" => "application/xml",
        "json" => "application/json",
        _ => "application/octet-stream",
    }
}

/// Options for a [`Client`], created with [`Client::builder`].
#[derive(Clone)]
pub struct ClientBuilder {
    base_url: String,
    token: Option<String>,
    timeout: Duration,
    connect_timeout: Option<Duration>,
    max_response_size: u64,
    allow_insecure_http: bool,
}

impl ClientBuilder {
    /// Reads the instance URL from `CT_URL` and the login token from `CT_TOKEN`,
    /// leaving the other options to be set before [`build`](Self::build).
    pub fn from_env() -> Result<Self> {
        let url = std::env::var("CT_URL").map_err(|_| Error::InvalidBaseUrl("CT_URL is not set".into()))?;
        Ok(Client::builder(&url).token(std::env::var("CT_TOKEN").ok()))
    }

    /// The login token, sent as `Authorization: Login <token>`.
    pub fn token(mut self, token: impl Into<Option<String>>) -> Self {
        self.token = token.into();
        self
    }

    /// Timeout for a whole request including reading the body (default 30 s).
    ///
    /// Raise it for large downloads, uploads or slow exports.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Timeout for establishing the connection (default 10 s, at most
    /// [`timeout`](Self::timeout)), so an unreachable host fails fast even
    /// with a long request timeout.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Largest response body that is read (default
    /// [`DEFAULT_MAX_RESPONSE_SIZE`]); larger ones fail with
    /// [`Error::ResponseTooLarge`] instead of filling the memory.
    pub fn max_response_size(mut self, bytes: u64) -> Self {
        self.max_response_size = bytes;
        self
    }

    /// Allows `http://` for hosts other than `localhost` and loopback addresses.
    ///
    /// The token then travels unencrypted; only for instances in a trusted network.
    pub fn allow_insecure_http(mut self, allow: bool) -> Self {
        self.allow_insecure_http = allow;
        self
    }

    pub fn build(self) -> Result<Client> {
        let connect_timeout = self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT).min(self.timeout);
        let http = http_client()
            .timeout(self.timeout)
            .connect_timeout(connect_timeout)
            .build()
            .map_err(Error::transport)?;
        Ok(Client {
            http,
            api_url: normalize_base_url(&self.base_url, self.allow_insecure_http)?,
            token: self.token,
            timeout: self.timeout,
            connect_timeout,
            max_response_size: self.max_response_size,
            throttle: None,
        })
    }
}

/// The common settings of every HTTP client this crate creates.
fn http_client() -> reqwest::blocking::ClientBuilder {
    // reqwest is built without a default crypto provider (`rustls-no-provider`),
    // so rustls does not pull in aws-lc-rs; `ring` is installed here instead,
    // unless the application has already chosen a provider.
    if rustls::crypto::CryptoProvider::get_default().is_none() {
        let _ = rustls::crypto::ring::default_provider().install_default();
    }
    reqwest::blocking::Client::builder()
        .user_agent(USER_AGENT)
        .redirect(redirect_policy())
}

/// Follows only redirects that keep method and body (307, 308).
///
/// On 301/302/303 reqwest would repeat a POST/PUT/DELETE as GET and drop the
/// body, so a write would look successful without having happened. Those are
/// reported as [`Error::Redirect`] instead.
fn redirect_policy() -> reqwest::redirect::Policy {
    reqwest::redirect::Policy::custom(|attempt| {
        if attempt.previous().len() >= 10 {
            attempt.error("too many redirects")
        } else if matches!(attempt.status().as_u16(), 307 | 308) {
            attempt.follow()
        } else {
            attempt.stop()
        }
    })
}

const USER_AGENT: &str = concat!("churchtools-api/", env!("CARGO_PKG_VERSION"));

/// Spaces requests at least `interval` apart, across all clones of a client.
#[derive(Debug)]
struct Throttle {
    interval: Duration,
    next: Mutex<Instant>,
}

impl Throttle {
    fn wait(&self) {
        let now = Instant::now();
        let start = {
            let mut next = self.next.lock().unwrap_or_else(|e| e.into_inner());
            let start = (*next).max(now);
            *next = start + self.interval;
            start
        };
        std::thread::sleep(start - now);
    }
}

impl Client {
    /// Creates a client for `base_url`, e.g. `https://meinegemeinde.church.tools`.
    ///
    /// A trailing `/api` is optional. See [`Client::builder`] for more options.
    pub fn new(base_url: &str, token: Option<String>) -> Result<Self> {
        Self::builder(base_url).token(token).build()
    }

    /// Starts configuring a client for `base_url`.
    pub fn builder(base_url: &str) -> ClientBuilder {
        ClientBuilder {
            base_url: base_url.to_owned(),
            token: None,
            timeout: Duration::from_secs(30),
            connect_timeout: None,
            max_response_size: DEFAULT_MAX_RESPONSE_SIZE,
            allow_insecure_http: false,
        }
    }

    /// Limits this client (and its clones) to one request per `min_interval`.
    ///
    /// Useful for bulk jobs and tests, so the instance is not flooded. Independent
    /// of this, a `429 Too Many Requests` answer is retried after the time the
    /// server asks for (`Retry-After`, at most 60 s, up to 3 times); so are
    /// `502`/`503`/`504` for idempotent methods (GET, HEAD, PUT, DELETE,
    /// OPTIONS). A failed connection is retried once after 1 s.
    pub fn with_min_interval(mut self, min_interval: Duration) -> Self {
        self.throttle = Some(Arc::new(Throttle {
            interval: min_interval,
            next: Mutex::new(Instant::now()),
        }));
        self
    }

    /// Logs in with username (or email) and password and returns a client that
    /// uses the login token of that person.
    ///
    /// Keeps the rate limit of `self`. Prefer a stored token for scripts; this is
    /// meant for tests and interactive tools.
    ///
    /// The token is the person's persistent login token: ChurchTools creates one
    /// if there is none, and it stays valid after this client is dropped, until
    /// it is revoked with `client.persons().delete_login_token(person_id)`. The
    /// password session used to fetch it is not reused; the API has no logout,
    /// so it ends when the server expires it.
    pub fn login_with_password(&self, username: &str, password: &str) -> Result<Self> {
        // The password login answers with a session cookie, which is only needed
        // to fetch the token.
        let session = Self {
            http: http_client()
                .timeout(self.timeout)
                .connect_timeout(self.connect_timeout)
                .cookie_store(true)
                .build()
                .map_err(Error::transport)?,
            token: None,
            ..self.clone()
        };
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct LoginData {
            person_id: i64,
        }
        let body = serde_json::json!({ "username": username, "password": password, "rememberMe": false });
        let login: LoginData = session.request_data(Method::Post, "/login", &[], Some(&body))?;
        let token: String = session.request_data(
            Method::Get,
            &format!("/persons/{}/logintoken", login.person_id),
            &[],
            None,
        )?;
        Ok(Self {
            token: Some(token),
            ..self.clone()
        })
    }

    /// Reads the instance URL from `CT_URL` and the login token from `CT_TOKEN`.
    ///
    /// For other options use [`ClientBuilder::from_env`].
    pub fn from_env() -> Result<Self> {
        ClientBuilder::from_env()?.build()
    }

    /// The API root, always ending in `/api`.
    pub fn api_url(&self) -> &str {
        &self.api_url
    }

    /// Sends a request and returns the raw body of a successful response.
    ///
    /// `path` starts with `/` and is relative to the API root; path parameters
    /// must already be encoded (see [`encode_path_segment`]).
    pub fn request(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        body: Option<&serde_json::Value>,
    ) -> Result<Vec<u8>> {
        self.send(method, path, query, |builder| match body {
            Some(body) => Ok(builder.json(body)),
            None => Ok(builder),
        })
    }

    /// Like [`request`](Self::request), with a body that is already encoded
    /// JSON; it is sent as is, without parsing it again.
    pub fn request_json_bytes(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        body: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        self.send(method, path, query, |builder| match body {
            Some(body) => Ok(builder
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(body.to_vec())),
            None => Ok(builder),
        })
    }

    /// Sends a `multipart/form-data` request: the text fields of `form` plus one
    /// part named `file_field` (e.g. `files[]`) per file.
    pub fn request_multipart(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        form: &[(String, String)],
        file_field: &str,
        files: &[Upload],
    ) -> Result<Vec<u8>> {
        self.send(method, path, query, |builder| {
            // Sending consumes a form, so it is rebuilt for every attempt.
            let mut multipart = reqwest::blocking::multipart::Form::new();
            for (key, value) in form {
                multipart = multipart.text(key.clone(), value.clone());
            }
            for file in files {
                // A reader over the shared content: no copy per attempt.
                let reader = std::io::Cursor::new(file.content.clone());
                let part = reqwest::blocking::multipart::Part::reader_with_length(reader, file.content.len() as u64)
                    .file_name(file.filename.clone())
                    .mime_str(&file.content_type)
                    .map_err(Error::transport)?;
                multipart = multipart.part(file_field.to_owned(), part);
            }
            Ok(builder.multipart(multipart))
        })
    }

    /// Common part of all requests: rate limit, auth, retries, error mapping.
    fn send(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        with_body: impl Fn(RequestBuilder) -> Result<RequestBuilder>,
    ) -> Result<Vec<u8>> {
        check_path(path)?;
        let mut attempt = 0;
        let mut connect_retried = false;
        loop {
            if let Some(throttle) = &self.throttle {
                throttle.wait();
            }
            let mut builder = self
                .http
                .request(method.to_reqwest(), format!("{}{}", self.api_url, path))
                .header("Accept", "application/json")
                .query(query);
            if let Some(token) = &self.token {
                let mut value = reqwest::header::HeaderValue::try_from(format!("Login {token}"))
                    .map_err(|_| Error::InvalidToken)?;
                // Keeps the token out of reqwest's own debug output.
                value.set_sensitive(true);
                builder = builder.header(reqwest::header::AUTHORIZATION, value);
            }
            let response = match with_body(builder)?.send() {
                Ok(response) => response,
                // Not connected means the request did not reach the server, so
                // repeating it is safe for every method.
                Err(err) if err.is_connect() && !connect_retried => {
                    connect_retried = true;
                    std::thread::sleep(CONNECT_RETRY_WAIT);
                    continue;
                }
                Err(err) => return Err(Error::transport(err)),
            };
            let status = response.status().as_u16();
            let retryable = status == 429 || (RETRY_STATUSES.contains(&status) && method.is_idempotent());
            if retryable && attempt < MAX_RETRIES {
                attempt += 1;
                std::thread::sleep(retry_after(response.headers(), attempt));
                continue;
            }
            if response.status().is_redirection() {
                let location = response.headers().get(reqwest::header::LOCATION);
                return Err(Error::Redirect {
                    status,
                    location: location.and_then(|v| v.to_str().ok()).map(str::to_owned),
                });
            }
            let bytes = read_body(response, self.max_response_size)?;
            if !(200..300).contains(&status) {
                return Err(ApiError::from_response(status, bytes).into());
            }
            return Ok(bytes);
        }
    }

    /// Sends a request and decodes the `data` field of the response envelope.
    pub fn request_data<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        body: Option<&serde_json::Value>,
    ) -> Result<T> {
        decode_data(&self.request(method, path, query, body)?)
    }

    /// Sends a request and decodes the whole response body.
    pub fn request_json<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        body: Option<&serde_json::Value>,
    ) -> Result<T> {
        decode(&self.request(method, path, query, body)?)
    }

    /// Iterates over the raw bodies of all pages of a paginated GET endpoint.
    ///
    /// Any `page` entry in `query` is replaced. Iteration stops after the page
    /// whose `meta.pagination.current` reaches `lastPage`, after an empty page,
    /// or after the first page if the response carries no pagination info.
    ///
    /// Pages are fetched one by one with offsets: if entries are added or
    /// removed meanwhile, an entry can show up twice or be skipped. From the
    /// second page on, the next page is requested in a background thread while
    /// the current one is being used, see [`Pages::prefetch`].
    pub fn pages(&self, path: &str, query: Query) -> Pages {
        Pages { fetcher: PageFetcher::new(self, path, query) }
    }

    /// Fetches all pages and concatenates their `data` arrays.
    pub fn collect_pages<T: DeserializeOwned>(&self, path: &str, query: Query) -> Result<Vec<T>> {
        self.items(path, query).collect()
    }

    /// Iterates over the items of all pages, fetching each page only when the
    /// previous one is used up. Stopping early saves the remaining requests.
    ///
    /// Ends after the first error; the same rules as for [`Client::pages`] apply.
    pub fn items<T: DeserializeOwned>(&self, path: &str, query: Query) -> Items<T> {
        Items { fetcher: PageFetcher::new(self, path, query), buffer: Vec::new().into_iter() }
    }
}

/// Requests the pages of a paginated GET endpoint one after another; the
/// shared part of [`Pages`] and [`Items`].
struct PageFetcher {
    client: Client,
    path: String,
    query: Query,
    /// The page to hand out next, or `None` after the last page.
    pending: Option<Pending>,
    /// Pages handed out so far.
    handed_out: u64,
    prefetch: bool,
}

enum Pending {
    /// Not requested yet.
    Page(u64),
    /// Being requested in a background thread.
    Spawned(u64, JoinHandle<Result<Vec<u8>>>),
}

impl PageFetcher {
    fn new(client: &Client, path: &str, query: Query) -> Self {
        Self {
            client: client.clone(),
            path: path.to_owned(),
            query: query.into_iter().filter(|(k, _)| k != "page").collect(),
            pending: Some(Pending::Page(1)),
            handed_out: 0,
            prefetch: true,
        }
    }

    /// Number and body of the next page, or `None` after the last one. The
    /// caller decides with [`PageFetcher::advance`] which page follows.
    fn fetch(&mut self) -> Option<(u64, Result<Vec<u8>>)> {
        let (page, result) = match self.pending.take()? {
            Pending::Page(page) => (page, request_page(&self.client, &self.path, &self.query, page)),
            Pending::Spawned(page, handle) => {
                (page, handle.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)))
            }
        };
        self.handed_out += 1;
        Some((page, result))
    }

    /// Sets the page that follows. From the second page on it is requested
    /// right away in a background thread, so that the network wait overlaps
    /// with the use of the current page. After the first page it is not, so
    /// that taking only the first page costs a single request.
    fn advance(&mut self, next: Option<u64>) {
        self.pending = next.map(|page| {
            if !self.prefetch || self.handed_out < 2 {
                return Pending::Page(page);
            }
            let (client, path, query) = (self.client.clone(), self.path.clone(), self.query.clone());
            let thread = std::thread::Builder::new().name("churchtools-api prefetch".into());
            match thread.spawn(move || request_page(&client, &path, &query, page)) {
                Ok(handle) => Pending::Spawned(page, handle),
                // Without a thread the page is simply requested when it is needed.
                Err(_) => Pending::Page(page),
            }
        });
    }
}

fn request_page(client: &Client, path: &str, query: &Query, page: u64) -> Result<Vec<u8>> {
    let mut query = query.clone();
    query.push(("page".into(), page.to_string()));
    client.request(Method::Get, path, &query, None)
}

/// Iterator returned by [`Client::items`] and the generated `…_iter` methods.
pub struct Items<T> {
    fetcher: PageFetcher,
    buffer: std::vec::IntoIter<T>,
}

impl<T> Items<T> {
    /// Whether the next page is requested in the background while the current
    /// one is being used (the default); see [`Pages::prefetch`].
    pub fn prefetch(mut self, enabled: bool) -> Self {
        self.fetcher.prefetch = enabled;
        self
    }
}

impl<T: DeserializeOwned> Iterator for Items<T> {
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        #[derive(Deserialize)]
        struct Page<T> {
            data: Vec<T>,
            // Kept loose: an unexpected `meta` only ends the pagination.
            meta: Option<serde_json::Value>,
        }
        loop {
            if let Some(item) = self.buffer.next() {
                return Some(Ok(item));
            }
            let (page, result) = self.fetcher.fetch()?;
            // One pass over the body for both the items and the page info.
            match result.and_then(|bytes| decode::<Page<T>>(&bytes)) {
                Ok(body) => {
                    let meta = body.meta.and_then(|m| serde_json::from_value(m).ok());
                    self.fetcher.advance(next_page(meta, !body.data.is_empty(), page));
                    self.buffer = body.data.into_iter();
                }
                // Nothing is pending any more: the iteration ends after an error.
                Err(e) => return Some(Err(e)),
            }
        }
    }
}

/// Iterator returned by [`Client::pages`].
pub struct Pages {
    fetcher: PageFetcher,
}

impl Pages {
    /// Whether the next page is requested in a background thread while the
    /// current one is being used (the default), so that the network wait
    /// overlaps with decoding and processing.
    ///
    /// The first page is always requested on its own, so that taking only the
    /// first page costs a single request. From the second page on, stopping
    /// early can leave one more request in flight; it finishes in the
    /// background and its response is discarded. With `false`, every page is
    /// requested only when it is needed.
    pub fn prefetch(mut self, enabled: bool) -> Self {
        self.fetcher.prefetch = enabled;
        self
    }
}

impl Iterator for Pages {
    type Item = Result<Vec<u8>>;

    fn next(&mut self) -> Option<Self::Item> {
        let (page, result) = self.fetcher.fetch()?;
        if let Ok(bytes) = &result {
            self.fetcher.advance(next_page_number(bytes, page));
        }
        Some(result)
    }
}

/// Reads the whole body, but at most `limit` bytes.
fn read_body(response: reqwest::blocking::Response, limit: u64) -> Result<Vec<u8>> {
    use std::io::Read;

    let too_large = || Error::ResponseTooLarge { limit };
    if response.content_length().is_some_and(|len| len > limit) {
        return Err(too_large());
    }
    // Reserve what the server announces, but not more than 1 MiB up front.
    let mut bytes = Vec::with_capacity(response.content_length().unwrap_or(0).min(1 << 20) as usize);
    response.take(limit.saturating_add(1)).read_to_end(&mut bytes).map_err(Error::Read)?;
    if bytes.len() as u64 > limit {
        return Err(too_large());
    }
    Ok(bytes)
}

#[derive(Deserialize)]
struct Meta {
    pagination: Option<Pagination>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Pagination {
    current: u64,
    last_page: u64,
}

/// Page number after `requested`, or `None` on the last page.
fn next_page(meta: Option<Meta>, has_items: bool, requested: u64) -> Option<u64> {
    let pagination = meta?.pagination?;
    // Guard against servers that echo a page number we did not ask for, and
    // against a `lastPage` that never comes (an empty page ends the list).
    (has_items && pagination.current == requested && pagination.current < pagination.last_page)
        .then_some(requested + 1)
}

/// [`next_page`] for a raw body; skips over `data` without decoding it.
fn next_page_number(body: &[u8], requested: u64) -> Option<u64> {
    #[derive(Deserialize)]
    struct Body {
        meta: Option<Meta>,
        #[serde(default)]
        data: HasItems,
    }
    let body = serde_json::from_slice::<Body>(body).ok()?;
    next_page(body.meta, body.data.0, requested)
}

/// Whether `data` is anything but an empty list, without keeping its items.
struct HasItems(bool);

impl Default for HasItems {
    fn default() -> Self {
        Self(true)
    }
}

impl<'de> Deserialize<'de> for HasItems {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        use serde::de::{IgnoredAny, SeqAccess, Visitor};

        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = HasItems;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("any JSON value")
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<HasItems, A::Error> {
                let first = seq.next_element::<IgnoredAny>()?;
                while seq.next_element::<IgnoredAny>()?.is_some() {}
                Ok(HasItems(first.is_some()))
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> std::result::Result<HasItems, A::Error> {
                IgnoredAny.visit_map(map).map(|_| HasItems(true))
            }
            fn visit_unit<E>(self) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
            fn visit_bool<E>(self, _: bool) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
            fn visit_i64<E>(self, _: i64) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
            fn visit_u64<E>(self, _: u64) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
            fn visit_f64<E>(self, _: f64) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
            fn visit_str<E>(self, _: &str) -> std::result::Result<HasItems, E> {
                Ok(HasItems(true))
            }
        }
        d.deserialize_any(V)
    }
}

/// Wait time before a retry: the server's `Retry-After` (seconds or an HTTP
/// date), or an exponential backoff (2, 4, 8 s) when the header is missing.
fn retry_after(headers: &reqwest::header::HeaderMap, attempt: u32) -> Duration {
    headers
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| parse_retry_after(v.trim(), chrono::Utc::now()))
        .unwrap_or(Duration::from_secs(1 << attempt))
        .min(MAX_RETRY_WAIT)
}

fn parse_retry_after(value: &str, now: chrono::DateTime<chrono::Utc>) -> Option<Duration> {
    if let Ok(seconds) = value.parse::<u64>() {
        return Some(Duration::from_secs(seconds));
    }
    // `Wed, 21 Oct 2026 07:28:00 GMT`; a date in the past means no wait.
    let at = chrono::DateTime::parse_from_rfc2822(value).ok()?;
    Some((at.to_utc() - now).to_std().unwrap_or_default())
}

/// Decodes the `data` field of a response envelope.
pub fn decode_data<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    if bytes.trim_ascii().is_empty() {
        return decode(bytes); // no envelope without a body
    }
    decode::<Envelope<T>>(bytes).map(|e| e.data).or_else(|err| {
        // PHP encodes an empty associative array as `[]`; retry as `{}` for map results.
        match serde_json::from_slice::<Envelope<serde_json::Value>>(bytes) {
            Ok(Envelope { data: serde_json::Value::Array(a) }) if a.is_empty() => {
                serde_json::from_value(serde_json::json!({})).map_err(|_| err)
            }
            _ => Err(err),
        }
    })
}

#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

/// Decodes a whole response body.
pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    if bytes.trim_ascii().is_empty() {
        // 204 No Content: only an `Option` result (or `()`) accepts this.
        return serde_json::from_value(serde_json::Value::Null).map_err(|source| Error::Decode {
            source,
            body: String::new(),
        });
    }
    serde_json::from_slice(bytes).map_err(|source| Error::Decode {
        source,
        body: String::from_utf8_lossy(bytes).into_owned(),
    })
}

/// Parses the instance URL and returns the API root ending in `/api`.
///
/// Accepts a path prefix (`https://example.org/ct` becomes
/// `https://example.org/ct/api`) and an existing `/api` suffix.
fn normalize_base_url(base_url: &str, allow_insecure_http: bool) -> Result<String> {
    let invalid = |why: &str| Error::InvalidBaseUrl(format!("{base_url}: {why}"));
    let mut url = reqwest::Url::parse(base_url.trim()).map_err(|e| invalid(&e.to_string()))?;
    match url.scheme() {
        "https" => {}
        "http" if allow_insecure_http || is_loopback(&url) => {}
        "http" => {
            return Err(invalid(
                "http:// would send the token unencrypted; use https:// \
                 (or allow_insecure_http for a trusted network)",
            ));
        }
        _ => return Err(invalid("expected https://")),
    }
    if url.host_str().is_none_or(str::is_empty) {
        return Err(invalid("no host"));
    }
    if url.query().is_some() || url.fragment().is_some() {
        return Err(invalid("must not contain `?` or `#`"));
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(invalid("must not contain user name or password; pass a token instead"));
    }
    let path = url.path().trim_end_matches('/');
    let path = path.strip_suffix("/api").unwrap_or(path).to_owned();
    url.set_path(&format!("{path}/api"));
    Ok(url.into())
}

/// Rejects paths the URL parser would rewrite or that address a different
/// endpoint: `.` and `..` segments (also percent-encoded, which the parser
/// resolves as well) and empty segments, e.g. from an ID `".."` or `""`.
fn check_path(path: &str) -> Result<()> {
    let valid = path.strip_prefix('/').is_some_and(|rest| {
        rest.split('/').all(|segment| {
            let decoded = percent_decode_str(segment).decode_utf8_lossy();
            !segment.is_empty() && decoded != "." && decoded != ".."
        })
    });
    if valid { Ok(()) } else { Err(Error::InvalidPath(path.to_owned())) }
}

fn is_loopback(url: &reqwest::Url) -> bool {
    let host = url.host_str().unwrap_or_default();
    host == "localhost"
        || host
            .trim_start_matches('[')
            .trim_end_matches(']')
            .parse::<std::net::IpAddr>()
            .is_ok_and(|ip| ip.is_loopback())
}

const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'~');

/// Percent-encodes a value for use as a single path segment.
pub fn encode_path_segment(value: impl std::fmt::Display) -> String {
    utf8_percent_encode(&value.to_string(), PATH_SEGMENT).to_string()
}

#[cfg(test)]
mod tests {
    use std::io::{BufRead, BufReader, Read, Write};

    use super::*;

    /// Answers each connection with the next of `responses` (raw HTTP) and
    /// records method and path of each request, e.g. `"POST /api/x"`.
    fn serve(responses: Vec<String>) -> (String, Arc<Mutex<Vec<String>>>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let seen = Arc::new(Mutex::new(Vec::new()));
        let log = seen.clone();
        std::thread::spawn(move || {
            for (stream, response) in listener.incoming().zip(responses) {
                let mut stream = stream.unwrap();
                let mut reader = BufReader::new(stream.try_clone().unwrap());
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                let request: Vec<&str> = line.split_whitespace().take(2).collect();
                log.lock().unwrap().push(request.join(" "));
                let mut length = 0;
                loop {
                    let mut header = String::new();
                    if reader.read_line(&mut header).unwrap() == 0 || header == "\r\n" {
                        break;
                    }
                    if let Some((name, value)) = header.split_once(':')
                        && name.eq_ignore_ascii_case("content-length")
                    {
                        length = value.trim().parse().unwrap();
                    }
                }
                reader.read_exact(&mut vec![0; length]).unwrap();
                stream.write_all(response.as_bytes()).unwrap();
            }
        });
        (url, seen)
    }

    fn reply(status: &str, headers: &str, body: &str) -> String {
        format!(
            "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        )
    }

    #[test]
    fn connect_timeout_defaults_to_10s_but_not_above_timeout() {
        let client = Client::new("https://x.church.tools", None).unwrap();
        assert_eq!(client.connect_timeout, Duration::from_secs(10));
        let short = Client::builder("https://x.church.tools").timeout(Duration::from_secs(3)).build().unwrap();
        assert_eq!(short.connect_timeout, Duration::from_secs(3));
        let custom = Client::builder("https://x.church.tools")
            .timeout(Duration::from_secs(600))
            .connect_timeout(Duration::from_millis(200))
            .build()
            .unwrap();
        assert_eq!((custom.timeout, custom.connect_timeout), (Duration::from_secs(600), Duration::from_millis(200)));
        // A blackholed address fails after the connect timeout, not after 600 s.
        let start = Instant::now();
        let blackhole = Client::builder("http://10.255.255.1").allow_insecure_http(true);
        let blackhole = blackhole.timeout(Duration::from_secs(600)).connect_timeout(Duration::from_millis(200));
        assert!(blackhole.build().unwrap().request(Method::Get, "/x", &[], None).is_err());
        assert!(start.elapsed() < Duration::from_secs(5));
    }

    #[test]
    fn responses_above_the_size_limit_are_rejected() {
        let declared = reply("200 OK", "", r#"{"data":"0123456789"}"#);
        // Without Content-Length the body ends when the connection closes.
        let undeclared = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{\"data\":\"0123456789\"}".to_owned();
        let small = reply("200 OK", "", r#"{"data":1}"#);
        let (url, _) = serve(vec![declared, undeclared, small]);
        let client = Client::builder(&url).max_response_size(12).build().unwrap();
        for _ in 0..2 {
            let err = client.request(Method::Get, "/x", &[], None).unwrap_err();
            assert!(matches!(err, Error::ResponseTooLarge { limit: 12 }), "{err}");
        }
        assert_eq!(client.request(Method::Get, "/x", &[], None).unwrap(), br#"{"data":1}"#);
    }

    #[test]
    fn redirects_that_would_turn_a_write_into_a_get_are_errors() {
        let (url, seen) = serve(vec![reply("302 Found", "Location: /api/elsewhere\r\n", "")]);
        let client = Client::new(&url, None).unwrap();
        let body = serde_json::json!({"name": "x"});
        let err = client.request(Method::Post, "/groups", &[], Some(&body)).unwrap_err();
        let Error::Redirect { status, location } = err else { panic!("{err}") };
        assert_eq!((status, location.as_deref()), (302, Some("/api/elsewhere")));
        assert_eq!(*seen.lock().unwrap(), ["POST /api/groups"]); // no GET afterwards
    }

    #[test]
    fn method_preserving_redirects_are_followed() {
        let (url, seen) = serve(vec![
            reply("307 Temporary Redirect", "Location: /api/moved\r\n", ""),
            reply("200 OK", "", r#"{"data":1}"#),
        ]);
        let client = Client::new(&url, None).unwrap();
        let body = serde_json::json!({"name": "x"});
        let data: i64 = client.request_data(Method::Post, "/groups", &[], Some(&body)).unwrap();
        assert_eq!(data, 1);
        assert_eq!(*seen.lock().unwrap(), ["POST /api/groups", "POST /api/moved"]);
    }

    #[test]
    fn base_url_gets_api_suffix_once() {
        for input in [
            "https://x.church.tools",
            "https://x.church.tools/",
            "https://x.church.tools/api",
            "https://x.church.tools/api/",
        ] {
            assert_eq!(normalize_base_url(input, false).unwrap(), "https://x.church.tools/api");
        }
        assert!(normalize_base_url("x.church.tools", false).is_err());
        assert_eq!(normalize_base_url(" https://X.Church.Tools ", false).unwrap(), "https://x.church.tools/api");
        assert_eq!(normalize_base_url("https://example.org/ct/", false).unwrap(), "https://example.org/ct/api");
        assert_eq!(normalize_base_url("https://example.org:8443/ct/api", false).unwrap(), "https://example.org:8443/ct/api");
        for bad in [
            "https://x.church.tools?a=b",
            "https://x.church.tools/#top",
            "https://user:pw@x.church.tools",
            "ftp://x.church.tools",
            "https://",
        ] {
            assert!(normalize_base_url(bad, false).is_err(), "{bad}");
        }
    }

    #[test]
    fn plain_http_only_for_loopback_or_when_allowed() {
        for local in ["http://localhost:8080", "http://127.0.0.1:1", "http://[::1]:80", "http://LOCALHOST"] {
            assert!(normalize_base_url(local, false).is_ok(), "{local}");
        }
        let err = normalize_base_url("http://x.church.tools", false).unwrap_err();
        assert!(err.to_string().contains("unencrypted"), "{err}");
        assert!(normalize_base_url("http://localhost.evil.org", false).is_err());
        assert_eq!(
            normalize_base_url("http://ct.intern", true).unwrap(),
            "http://ct.intern/api"
        );
        let client = Client::builder("http://ct.intern").allow_insecure_http(true).build().unwrap();
        assert_eq!(client.api_url(), "http://ct.intern/api");
    }

    #[test]
    fn pagination_stops_on_last_page_or_missing_meta() {
        let page = |c: u64, l: u64| {
            format!(r#"{{"data":[{{"id":1}}],"meta":{{"pagination":{{"current":{c},"lastPage":{l}}}}}}}"#)
        };
        assert_eq!(next_page_number(page(1, 3).as_bytes(), 1), Some(2));
        assert_eq!(next_page_number(page(3, 3).as_bytes(), 3), None);
        assert_eq!(next_page_number(page(1, 3).as_bytes(), 2), None);
        assert_eq!(next_page_number(br#"{"data":[1],"meta":{"count":3}}"#, 1), None);
        // An empty page ends the list even if `lastPage` says otherwise.
        let empty = br#"{"data":[],"meta":{"pagination":{"current":1,"lastPage":1000000}}}"#;
        assert_eq!(next_page_number(empty, 1), None);
        let map = br#"{"data":{"a":1},"meta":{"pagination":{"current":1,"lastPage":2}}}"#;
        assert_eq!(next_page_number(map, 1), Some(2));
    }

    #[test]
    fn collect_pages_decodes_each_page_once_and_follows_meta() {
        let page = |c: u64, items: &str| {
            reply("200 OK", "", &format!(r#"{{"data":[{items}],"meta":{{"pagination":{{"current":{c},"lastPage":3}}}}}}"#))
        };
        let (url, seen) = serve(vec![page(1, "1,2"), page(2, "3"), page(3, "4")]);
        let client = Client::new(&url, None).unwrap();
        let query = vec![("limit".into(), "2".into()), ("page".into(), "9".into())];
        let items: Vec<i64> = client.collect_pages("/x", query).unwrap();
        assert_eq!(items, [1, 2, 3, 4]);
        assert_eq!(seen.lock().unwrap().len(), 3);
        // `meta` that is not an object only ends the pagination.
        let (url, _) = serve(vec![reply("200 OK", "", r#"{"data":[1],"meta":[]}"#)]);
        let items: Vec<i64> = Client::new(&url, None).unwrap().collect_pages("/x", vec![]).unwrap();
        assert_eq!(items, [1]);
    }

    #[test]
    fn items_fetch_pages_only_when_needed() {
        let page = |c: u64, items: &str| {
            reply("200 OK", "", &format!(r#"{{"data":[{items}],"meta":{{"pagination":{{"current":{c},"lastPage":3}}}}}}"#))
        };
        let (url, seen) = serve(vec![page(1, "1,2"), page(2, "3"), page(3, "4")]);
        let client = Client::new(&url, None).unwrap();
        let items = client.items("/x", vec![]).prefetch(false);
        let first: Vec<i64> = items.take(3).collect::<Result<_>>().unwrap();
        assert_eq!(first, [1, 2, 3]);
        assert_eq!(*seen.lock().unwrap(), ["GET /api/x?page=1", "GET /api/x?page=2"]);
        // An error ends the iteration.
        let (url, _) = serve(vec![reply("404 Not Found", "", "{}")]);
        let mut items = Client::new(&url, None).unwrap().items::<i64>("/x", vec![]);
        assert!(matches!(items.next(), Some(Err(Error::Api(_)))));
        assert!(items.next().is_none());
    }

    #[test]
    fn prefetch_starts_after_the_second_page() {
        let page = |c: u64, items: &str| {
            reply("200 OK", "", &format!(r#"{{"data":[{items}],"meta":{{"pagination":{{"current":{c},"lastPage":4}}}}}}"#))
        };
        // Only the first page is used: nothing else is requested.
        let (url, seen) = serve(vec![page(1, "1,2"), page(2, "3")]);
        let client = Client::new(&url, None).unwrap();
        let mut pages = client.pages("/x", vec![]);
        assert!(pages.next().unwrap().is_ok());
        drop(pages);
        std::thread::sleep(Duration::from_millis(50));
        assert_eq!(*seen.lock().unwrap(), ["GET /api/x?page=1"]);
        // Page 3 is requested in the background once page 2 is handed out, and
        // an error there shows up in its place.
        let (url, seen) = serve(vec![page(1, "1,2"), page(2, "3"), reply("404 Not Found", "", "{}")]);
        let client = Client::new(&url, None).unwrap();
        let mut items = client.items::<i64>("/x", vec![]);
        assert_eq!(items.by_ref().take(3).collect::<Result<Vec<_>>>().unwrap(), [1, 2, 3]);
        let deadline = Instant::now() + Duration::from_secs(5);
        while seen.lock().unwrap().len() < 3 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        assert_eq!(seen.lock().unwrap().len(), 3);
        assert!(matches!(items.next(), Some(Err(Error::Api(_)))));
        assert!(items.next().is_none());
    }

    #[test]
    fn uploads_are_sent_with_content_and_retried() {
        let (url, seen) = serve(vec![
            reply("429 Too Many Requests", "Retry-After: 0\r\n", ""),
            reply("200 OK", "", r#"{"data":[]}"#),
        ]);
        let client = Client::new(&url, None).unwrap();
        let file = Upload::new("brief.txt", b"Hallo Gemeinde".as_slice(), "text/plain");
        let copy = file.clone();
        assert!(Arc::ptr_eq(&file.content, &copy.content)); // cloning shares the bytes
        let form = [("sortKey".to_owned(), "3".to_owned())];
        client.request_multipart(Method::Post, "/files/person/7", &[], &form, "files[]", &[file]).unwrap();
        assert_eq!(seen.lock().unwrap().len(), 2);
    }

    #[test]
    fn json_bytes_are_sent_unchanged() {
        let (url, _) = serve(vec![reply("200 OK", "", r#"{"data":1}"#)]);
        let client = Client::new(&url, None).unwrap();
        let body = br#"{"firstName": "Ben"}"#;
        assert_eq!(client.request_json_bytes(Method::Post, "/x", &[], Some(body)).unwrap(), br#"{"data":1}"#);
    }

    #[test]
    fn empty_body_is_none_for_optional_results() {
        assert_eq!(decode::<Option<i64>>(b"").unwrap(), None);
        assert_eq!(decode::<Option<i64>>(b"7").unwrap(), Some(7));
        assert!(decode::<i64>(b" ").is_err());
    }

    #[test]
    fn retry_after_uses_header_or_backoff() {
        let mut headers = reqwest::header::HeaderMap::new();
        assert_eq!(retry_after(&headers, 1), Duration::from_secs(2));
        assert_eq!(retry_after(&headers, 3), Duration::from_secs(8));
        headers.insert(reqwest::header::RETRY_AFTER, "5".parse().unwrap());
        assert_eq!(retry_after(&headers, 1), Duration::from_secs(5));
        headers.insert(reqwest::header::RETRY_AFTER, "3600".parse().unwrap());
        assert_eq!(retry_after(&headers, 1), MAX_RETRY_WAIT);
        headers.insert(reqwest::header::RETRY_AFTER, "soon".parse().unwrap());
        assert_eq!(retry_after(&headers, 2), Duration::from_secs(4));

        let now = "2026-10-21T07:28:00Z".parse().unwrap();
        assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:28:10 GMT", now), Some(Duration::from_secs(10)));
        assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:27:00 GMT", now), Some(Duration::ZERO));
    }

    #[test]
    fn unavailable_server_is_retried_for_idempotent_methods_only() {
        let unavailable = || reply("503 Service Unavailable", "Retry-After: 0\r\n", "");
        let (url, seen) = serve(vec![unavailable(), reply("200 OK", "", r#"{"data":1}"#), unavailable()]);
        let client = Client::new(&url, None).unwrap();
        assert_eq!(client.request(Method::Get, "/x", &[], None).unwrap(), br#"{"data":1}"#);
        let err = client.request(Method::Post, "/x", &[], None).unwrap_err();
        assert!(matches!(&err, Error::Api(api) if api.status == 503), "{err}");
        assert_eq!(*seen.lock().unwrap(), ["GET /api/x", "GET /api/x", "POST /api/x"]);
    }

    #[test]
    fn refused_connection_is_retried_once() {
        // Nothing listens on the port: both attempts are refused, after one wait.
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
        let client = Client::new(&format!("http://127.0.0.1:{port}"), None).unwrap();
        let start = Instant::now();
        let err = client.request(Method::Post, "/x", &[], None).unwrap_err();
        assert!(matches!(&err, Error::Transport(e) if e.is_connect()), "{err}");
        assert!(start.elapsed() >= CONNECT_RETRY_WAIT);
    }

    #[test]
    fn throttle_spaces_requests() {
        let throttle = Throttle {
            interval: Duration::from_millis(30),
            next: Mutex::new(Instant::now()),
        };
        let start = Instant::now();
        for _ in 0..4 {
            throttle.wait();
        }
        // First call is immediate, the next three wait one interval each.
        assert!(start.elapsed() >= Duration::from_millis(90));
    }

    #[test]
    fn debug_output_hides_the_token() {
        let client = Client::new("https://x.church.tools", Some("geheim123".into())).unwrap();
        let debug = format!("{client:?}");
        assert!(!debug.contains("geheim123"), "{debug}");
        assert!(debug.contains("<redacted>") && debug.contains("https://x.church.tools/api"));
    }

    #[test]
    fn dot_and_empty_segments_are_rejected() {
        let client = Client::new("http://127.0.0.1:9", None).unwrap();
        for id in ["..", ".", ""] {
            let path = format!("/groups/7/members/{}", encode_path_segment(id));
            let err = client.request(Method::Delete, &path, &[], None).unwrap_err();
            assert!(matches!(err, Error::InvalidPath(_)), "{id:?}: {err}");
        }
        // Raw paths: the URL parser treats percent-encoded dots as dots, too.
        assert!(check_path("/groups/7/members/%2e%2E").is_err());
        assert!(check_path("/groups/7/members/.%2e").is_err());
        assert!(check_path("persons").is_err());
        assert!(check_path("/persons/").is_err());
        assert!(check_path("/persons/a.b/..x").is_ok());
        // An ID `%2e%2e` is encoded to `%252e%252e` and reaches the server literally.
        assert_eq!(encode_path_segment("%2e%2e"), "%252e%252e");
        assert!(check_path("/files/%252e%252e").is_ok());
    }

    #[test]
    fn path_segments_are_encoded() {
        assert_eq!(encode_path_segment("a b/c"), "a%20b%2Fc");
        assert_eq!(encode_path_segment(42), "42");
    }
}