glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Calling other services over HTTP, as Jumpstart's API clients do: a
//! client per service with its base URL and credentials, JSON in and out,
//! timeouts, retries, and errors for answers that aren't a success.
//!
//! ```ignore
//! pub struct ConvertKit(Client);
//!
//! impl ConvertKit {
//!     pub fn new(api_key: &str) -> Self {
//!         Self(Client::new("https://api.convertkit.com/v3").query_auth("api_key", api_key))
//!     }
//!
//!     pub async fn subscribe(&self, form_id: i64, email: &str) -> Result<Json> {
//!         self.0
//!             .post(&format!("forms/{form_id}/subscribe"))
//!             .json(&json!({ "email": email }))
//!             .send()
//!             .await?
//!             .json()
//!     }
//! }
//! ```
//!
//! Requests are traced (method, host and path, status, time) but bodies
//! and query strings never logged, as they carry tokens. In a
//! `#[glacier::test]` no request leaves the process: each must match a
//! stub (`glacier::testing::stub_request`), and is recorded for
//! `glacier::testing::requests()`.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;

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

/// A service's client: its base URL, credentials and defaults. Cheap to
/// clone; clones share connections.
#[derive(Clone)]
pub struct Client {
    base: String,
    headers: HeaderMap,
    query: Vec<(String, String)>,
    timeout: Duration,
    retries: u32,
    public_only: bool,
    inner: reqwest::Client,
}

/// Connections are shared by every client in the process.
fn shared() -> reqwest::Client {
    static SHARED: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
    SHARED
        .get_or_init(|| {
            reqwest::Client::builder()
                .connect_timeout(Duration::from_secs(5))
                .user_agent(concat!("Glacier/", env!("CARGO_PKG_VERSION")))
                .build()
                .unwrap_or_default()
        })
        .clone()
}

impl Client {
    /// A client for the service at `base` (`https://api.example.com/v1`);
    /// request paths are relative to it. 30-second timeout, no retries.
    pub fn new(base: &str) -> Self {
        Self {
            base: base.trim_end_matches('/').to_owned(),
            headers: HeaderMap::new(),
            query: Vec::new(),
            timeout: Duration::from_secs(30),
            retries: 0,
            public_only: false,
            inner: shared(),
        }
    }

    /// Sends `Authorization: Bearer <token>` with every request.
    #[must_use]
    pub fn bearer(self, token: &str) -> Self {
        self.header("authorization", &format!("Bearer {token}"))
    }

    /// HTTP basic authentication with every request.
    #[must_use]
    pub fn basic(self, username: &str, password: &str) -> Self {
        use base64::Engine as _;
        let encoded =
            base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
        self.header("authorization", &format!("Basic {encoded}"))
    }

    /// A header sent with every request: `.header("x-api-key", key)`.
    ///
    /// # Panics
    ///
    /// If the name or value isn't valid in a header.
    #[must_use]
    pub fn header(mut self, name: &str, value: &str) -> Self {
        let name = HeaderName::try_from(name).expect("invalid header name");
        let mut value = HeaderValue::try_from(value).expect("invalid header value");
        value.set_sensitive(name == http::header::AUTHORIZATION);
        self.headers.insert(name, value);
        self
    }

    /// A query parameter sent with every request, for services that take
    /// their key there: `.query_auth("api_key", key)`.
    #[must_use]
    pub fn query_auth(mut self, name: &str, value: &str) -> Self {
        self.query.push((name.to_owned(), value.to_owned()));
        self
    }

    /// How long a request may take, start to finish (default 30s).
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Tries a failed request again, up to `retries` times, with backoff:
    /// when it couldn't connect or timed out, or the service answered
    /// 429, 502, 503 or 504. Only requests safe to repeat are retried:
    /// GET, HEAD, PUT, DELETE, OPTIONS, and others with an idempotency key.
    /// Refuses requests to private addresses (loopback, the local network,
    /// link-local, cloud metadata at 169.254.169.254), checked after DNS,
    /// and doesn't follow redirects: for URLs a user gave, such as a
    /// webhook endpoint, against server-side request forgery.
    #[must_use]
    pub fn public_only(mut self) -> Self {
        static NO_REDIRECTS: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
        self.public_only = true;
        // A redirect could lead anywhere, so it isn't followed.
        self.inner = NO_REDIRECTS
            .get_or_init(|| {
                reqwest::Client::builder()
                    .connect_timeout(Duration::from_secs(5))
                    .redirect(reqwest::redirect::Policy::none())
                    .user_agent(concat!("Glacier/", env!("CARGO_PKG_VERSION")))
                    .build()
                    .unwrap_or_default()
            })
            .clone();
        self
    }

    #[must_use]
    pub fn retries(mut self, retries: u32) -> Self {
        self.retries = retries;
        self
    }

    pub fn get(&self, path: impl AsRef<str>) -> Request {
        self.request(Method::GET, path)
    }

    pub fn post(&self, path: impl AsRef<str>) -> Request {
        self.request(Method::POST, path)
    }

    pub fn put(&self, path: impl AsRef<str>) -> Request {
        self.request(Method::PUT, path)
    }

    pub fn patch(&self, path: impl AsRef<str>) -> Request {
        self.request(Method::PATCH, path)
    }

    pub fn delete(&self, path: impl AsRef<str>) -> Request {
        self.request(Method::DELETE, path)
    }

    /// A request to `path`, relative to the base URL, or a full URL.
    pub fn request(&self, method: Method, path: impl AsRef<str>) -> Request {
        let path = path.as_ref();
        let url = if path.starts_with("http://")
            || path.starts_with("https://")
            || self.base.is_empty()
        {
            path.to_owned()
        } else {
            format!("{}/{}", self.base, path.trim_start_matches('/'))
        };
        Request {
            client: self.clone(),
            method,
            url,
            headers: self.headers.clone(),
            query: self.query.clone(),
            body: None,
            idempotent: false,
            fail_on_error: true,
        }
    }
}

/// A request a client is about to send.
pub struct Request {
    client: Client,
    method: Method,
    url: String,
    headers: HeaderMap,
    query: Vec<(String, String)>,
    body: Option<Bytes>,
    idempotent: bool,
    fail_on_error: bool,
}

impl Request {
    /// Adds query parameters: `.query(&[("page", "2")])`, or a struct.
    ///
    /// # Panics
    ///
    /// If `params` doesn't serialize as a flat list of name/value pairs.
    #[must_use]
    pub fn query<T: Serialize + ?Sized>(mut self, params: &T) -> Self {
        let encoded =
            serde_urlencoded::to_string(params).expect("query parameters must be name/value pairs");
        self.query.extend(
            serde_urlencoded::from_str::<Vec<(String, String)>>(&encoded).unwrap_or_default(),
        );
        self
    }

    /// # Panics
    ///
    /// If the name or value isn't valid in a header.
    #[must_use]
    pub fn header(mut self, name: &str, value: impl AsRef<str>) -> Self {
        let value = value.as_ref();
        let name = HeaderName::try_from(name).expect("invalid header name");
        self.headers.insert(
            name,
            HeaderValue::try_from(value).expect("invalid header value"),
        );
        self
    }

    /// A JSON body.
    ///
    /// # Panics
    ///
    /// If `body` can't be serialized as JSON.
    #[must_use]
    pub fn json<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
        self.body = Some(serde_json::to_vec(body).expect("a JSON body").into());
        self.headers.insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        self
    }

    /// A form-encoded body.
    ///
    /// # Panics
    ///
    /// If `body` doesn't serialize as name/value pairs.
    #[must_use]
    pub fn form<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
        self.body = Some(
            serde_urlencoded::to_string(body)
                .expect("form fields")
                .into(),
        );
        self.headers.insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/x-www-form-urlencoded"),
        );
        self
    }

    /// A body as it is, with its content type.
    #[must_use]
    pub fn body(mut self, body: impl Into<Bytes>, content_type: &str) -> Self {
        self.body = Some(body.into());
        if let Ok(value) = HeaderValue::try_from(content_type) {
            self.headers.insert(http::header::CONTENT_TYPE, value);
        }
        self
    }

    /// Sends `Idempotency-Key: key`, so the service does the work once
    /// however often it's sent, and lets a POST be retried.
    #[must_use]
    pub fn idempotency_key(mut self, key: impl AsRef<str>) -> Self {
        let key = key.as_ref();
        self = self.header("idempotency-key", key);
        self.idempotent = true;
        self
    }

    /// Answers that aren't a success come back as a [`Response`] to look
    /// at, rather than an error.
    #[must_use]
    pub fn allow_errors(mut self) -> Self {
        self.fail_on_error = false;
        self
    }

    /// Sends it and reads the JSON answer into `T`: `get("prices").fetch()`.
    ///
    /// # Errors
    ///
    /// As [`send`](Self::send), or when the answer doesn't parse as `T`.
    pub async fn fetch<T: DeserializeOwned>(self) -> Result<T> {
        self.send().await?.json()
    }

    /// Sends it and returns the answer as text.
    ///
    /// # Errors
    ///
    /// As [`send`](Self::send).
    pub async fn fetch_text(self) -> Result<String> {
        Ok(self.send().await?.text())
    }

    /// Sends it, retrying as the client allows.
    ///
    /// # Errors
    ///
    /// When it can't be sent, or (unless `allow_errors`) the answer isn't
    /// a success: a [`ClientError`], which says which.
    pub async fn send(self) -> Result<Response> {
        let url = self.full_url();
        let target = loggable(&url);
        let span = tracing::info_span!(
            target: "glacier::client",
            "glacier.http.client",
            otel.name = %format!("{} {}", self.method, target),
            otel.kind = "client",
            http.request.method = %self.method,
            url.full = %target,
            http.response.status_code = tracing::field::Empty,
        );
        let retryable = self.idempotent
            || matches!(
                self.method,
                Method::GET | Method::HEAD | Method::PUT | Method::DELETE | Method::OPTIONS
            );
        let attempts = if retryable {
            self.client.retries + 1
        } else {
            1
        };
        let run = async {
            let mut attempt = 0;
            loop {
                attempt += 1;
                let started = std::time::Instant::now();
                let outcome = self.send_once(&url).await;
                let retry = match &outcome {
                    Ok(res) => matches!(res.status.as_u16(), 429 | 502 | 503 | 504),
                    Err(err) => matches!(err.kind, ErrorKind::Timeout | ErrorKind::Connect),
                };
                if let Ok(res) = &outcome {
                    tracing::Span::current()
                        .record("http.response.status_code", i64::from(res.status.as_u16()));
                }
                tracing::debug!(
                    target: "glacier::client",
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    attempt,
                    "{} {target}",
                    self.method
                );
                if retry && attempt < attempts {
                    let wait = match &outcome {
                        Ok(res) => res.retry_after(),
                        Err(_) => None,
                    }
                    .unwrap_or_else(|| backoff(attempt));
                    tracing::warn!(target: "glacier::client", "{} {target}: retrying in {wait:?}", self.method);
                    tokio::time::sleep(wait).await;
                    continue;
                }
                return match outcome {
                    Ok(res) if self.fail_on_error && !res.status.is_success() => {
                        Err(ClientError::from_response(&self.method, &target, &res).into_error())
                    }
                    Ok(res) => Ok(res),
                    Err(err) => Err(err.into_error()),
                };
            }
        };
        tracing::Instrument::instrument(run, span).await
    }

    fn full_url(&self) -> String {
        if self.query.is_empty() {
            return self.url.clone();
        }
        let encoded = serde_urlencoded::to_string(&self.query).unwrap_or_default();
        let joiner = if self.url.contains('?') { '&' } else { '?' };
        format!("{}{joiner}{encoded}", self.url)
    }

    async fn send_once(&self, url: &str) -> std::result::Result<Response, ClientError> {
        if let Some(fake) = fake() {
            return fake.answer(self, url);
        }
        if self.client.public_only {
            refuse_private(&self.method, url).await?;
        }
        let mut builder = self
            .client
            .inner
            .request(self.method.clone(), url)
            .headers(self.headers.clone())
            .timeout(self.client.timeout);
        if let Some(body) = &self.body {
            builder = builder.body(body.clone());
        }
        let target = loggable(url);
        let res = builder
            .send()
            .await
            .map_err(|e| ClientError::transport(&self.method, &target, &e))?;
        let status = res.status();
        let headers = res.headers().clone();
        let body = res
            .bytes()
            .await
            .map_err(|e| ClientError::transport(&self.method, &target, &e))?;
        Ok(Response {
            status,
            headers,
            body,
        })
    }
}

/// Whether `ip` is one a public-only client mustn't reach.
fn is_private(ip: std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(v4) => {
            let [a, b, ..] = v4.octets();
            v4.is_private()
                || v4.is_loopback()
                || v4.is_link_local()
                || v4.is_unspecified()
                || v4.is_broadcast()
                || v4.is_multicast()
                // 100.64.0.0/10, carrier-grade NAT.
                || (a == 100 && (64..128).contains(&b))
        }
        std::net::IpAddr::V6(v6) => {
            let first = v6.segments()[0];
            v6.is_loopback()
                || v6.is_unspecified()
                || v6.is_multicast()
                || (first & 0xfe00) == 0xfc00
                || (first & 0xffc0) == 0xfe80
                || v6
                    .to_ipv4_mapped()
                    .is_some_and(|v4| is_private(std::net::IpAddr::V4(v4)))
        }
    }
}

/// Fails if `url`'s host is, or resolves to, a private address.
async fn refuse_private(method: &Method, url: &str) -> std::result::Result<(), ClientError> {
    let blocked = |why: String| ClientError {
        kind: ErrorKind::Blocked,
        status: None,
        retry_after: None,
        body: String::new(),
        message: format!("{method} {}: {why}", loggable(url)),
    };
    let parsed = reqwest::Url::parse(url).map_err(|e| blocked(format!("not a URL ({e})")))?;
    let host = parsed
        .host_str()
        .ok_or_else(|| blocked("no host".to_owned()))?;
    let port = parsed.port_or_known_default().unwrap_or(443);
    let host = host.trim_start_matches('[').trim_end_matches(']');
    let addresses: Vec<std::net::IpAddr> = match host.parse::<std::net::IpAddr>() {
        Ok(ip) => vec![ip],
        Err(_) => tokio::net::lookup_host((host, port))
            .await
            .map_err(|e| blocked(format!("can't resolve it ({e})")))?
            .map(|addr| addr.ip())
            .collect(),
    };
    match addresses.into_iter().find(|ip| is_private(*ip)) {
        Some(ip) => Err(blocked(format!("{ip} is a private address"))),
        None => Ok(()),
    }
}

/// The URL as logs show it: no query string, which may hold a key.
fn loggable(url: &str) -> String {
    url.split('?').next().unwrap_or(url).to_owned()
}

/// 0.5s, 1s, 2s, 4s… between attempts.
fn backoff(attempt: u32) -> Duration {
    Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(6)))
}

/// A service's answer.
#[derive(Debug, Clone)]
pub struct Response {
    pub status: StatusCode,
    pub headers: HeaderMap,
    pub body: Bytes,
}

impl Response {
    /// The body decoded from JSON, into a type or `Json` for any value.
    ///
    /// # Errors
    ///
    /// When it isn't JSON of that shape.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_slice(&self.body)
            .map_err(|e| Error::new(StatusCode::BAD_GATEWAY, format!("the service's JSON: {e}")))
    }

    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }

    /// `Retry-After`, in seconds, when the service sent one.
    pub fn retry_after(&self) -> Option<Duration> {
        self.header("retry-after")?
            .trim()
            .parse()
            .ok()
            .map(Duration::from_secs)
    }
}

/// Why a request failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
    /// It took longer than the client's timeout.
    Timeout,
    /// It couldn't connect.
    Connect,
    /// 400, or another client error without a kind of its own.
    BadRequest,
    /// 401: the credentials are missing or wrong.
    Unauthorized,
    /// 403.
    Forbidden,
    /// 404.
    NotFound,
    /// 409 or 422: the service refused what was sent.
    Rejected,
    /// 429: too many requests; `retry_after` says when to try again.
    RateLimited,
    /// 5xx: the service failed.
    ServerError,
    /// In a test, no stub matched.
    NotStubbed,
    /// To a private address, from a `public_only` client.
    Blocked,
}

/// A failed request: what went wrong, and what the service said (its
/// first 500 characters; never logged).
#[derive(Debug, Clone)]
pub struct ClientError {
    pub kind: ErrorKind,
    pub status: Option<StatusCode>,
    pub retry_after: Option<Duration>,
    pub body: String,
    message: String,
}

impl ClientError {
    fn from_response(method: &Method, target: &str, res: &Response) -> Self {
        let kind = match res.status.as_u16() {
            401 => ErrorKind::Unauthorized,
            403 => ErrorKind::Forbidden,
            404 => ErrorKind::NotFound,
            409 | 422 => ErrorKind::Rejected,
            429 => ErrorKind::RateLimited,
            500..=599 => ErrorKind::ServerError,
            _ => ErrorKind::BadRequest,
        };
        Self {
            kind,
            status: Some(res.status),
            retry_after: res.retry_after(),
            body: res.text().chars().take(500).collect(),
            message: format!("{method} {target} answered {}", res.status),
        }
    }

    fn transport(method: &Method, target: &str, err: &reqwest::Error) -> Self {
        let kind = if err.is_timeout() {
            ErrorKind::Timeout
        } else {
            ErrorKind::Connect
        };
        Self {
            kind,
            status: None,
            retry_after: None,
            body: String::new(),
            message: format!("{method} {target}: {err}"),
        }
    }
}

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

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

impl ClientError {
    /// As a `glacier::Error`: a 502 (or 504 for a timeout) for the app's
    /// own caller, since the fault was upstream; the `ClientError` stays
    /// its source, for `err.downcast_ref::<ClientError>()`.
    fn into_error(self) -> Error {
        let status = match self.kind {
            ErrorKind::Timeout => StatusCode::GATEWAY_TIMEOUT,
            _ => StatusCode::BAD_GATEWAY,
        };
        Error::with_source(status, self.message.clone(), self)
    }
}

// The test fake.

/// What a test stubs: a method (or any), a URL pattern, and the answer.
struct Stub {
    method: Option<Method>,
    pattern: String,
    status: StatusCode,
    headers: HeaderMap,
    body: Bytes,
}

/// A request a test made.
#[derive(Debug, Clone)]
pub struct Requested {
    pub method: Method,
    /// The full URL, with its query string.
    pub url: String,
    pub headers: HeaderMap,
    pub body: Bytes,
}

impl Requested {
    /// The body decoded from JSON.
    pub fn json(&self) -> serde_json::Value {
        serde_json::from_slice(&self.body).unwrap_or_default()
    }
}

#[derive(Default)]
pub(crate) struct Fake {
    stubs: Mutex<Vec<Stub>>,
    requests: Mutex<Vec<Requested>>,
}

impl Fake {
    fn answer(&self, req: &Request, url: &str) -> std::result::Result<Response, ClientError> {
        self.requests
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(Requested {
                method: req.method.clone(),
                url: url.to_owned(),
                headers: req.headers.clone(),
                body: req.body.clone().unwrap_or_default(),
            });
        let stubs = self.stubs.lock().unwrap_or_else(|e| e.into_inner());
        // The latest matching stub wins, so a test can override an earlier one.
        let stub = stubs.iter().rev().find(|stub| {
            stub.method.as_ref().is_none_or(|m| *m == req.method)
                && matches_pattern(&stub.pattern, url)
        });
        match stub {
            Some(stub) => Ok(Response {
                status: stub.status,
                headers: stub.headers.clone(),
                body: stub.body.clone(),
            }),
            None => Err(ClientError {
                kind: ErrorKind::NotStubbed,
                status: None,
                retry_after: None,
                body: String::new(),
                message: format!(
                    "{} {url}: tests make no real requests; stub it with \
                     `stub_request(\"{}\", \"{}\", …)`",
                    req.method,
                    req.method,
                    loggable(url)
                ),
            }),
        }
    }
}

/// `*` matches any run of characters; a pattern without a query string
/// matches the URL whatever its query.
fn matches_pattern(pattern: &str, url: &str) -> bool {
    let url = if pattern.contains('?') {
        url
    } else {
        url.split('?').next().unwrap_or(url)
    };
    let parts: Vec<&str> = pattern.split('*').collect();
    let mut rest = url;
    for (i, part) in parts.iter().enumerate() {
        if i == 0 {
            match rest.strip_prefix(part) {
                Some(after) => rest = after,
                None => return false,
            }
        } else if i == parts.len() - 1 {
            return rest.ends_with(part);
        } else {
            match rest.find(part) {
                Some(at) => rest = &rest[at + part.len()..],
                None => return false,
            }
        }
    }
    rest.is_empty()
}

tokio::task_local! {
    static FAKE: Arc<Fake>;
}

fn fake() -> Option<Arc<Fake>> {
    FAKE.try_with(Arc::clone).ok()
}

/// Runs `fut` with no network: requests answer from stubs. `#[glacier::test]`
/// does this.
#[doc(hidden)]
pub async fn with_fake<F: std::future::Future>(fut: F) -> F::Output {
    FAKE.scope(Arc::default(), fut).await
}

pub(crate) fn stub(
    method: Option<Method>,
    pattern: &str,
    status: StatusCode,
    body: Bytes,
    content_type: &str,
) {
    let fake = fake().expect("stub_request works inside a #[glacier::test]");
    let mut headers = HeaderMap::new();
    if let Ok(value) = HeaderValue::try_from(content_type) {
        headers.insert(http::header::CONTENT_TYPE, value);
    }
    fake.stubs
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push(Stub {
            method,
            pattern: pattern.to_owned(),
            status,
            headers,
            body,
        });
}

pub(crate) fn requested() -> Vec<Requested> {
    fake()
        .map(|fake| {
            fake.requests
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .clone()
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn patterns() {
        assert!(matches_pattern(
            "https://api.x.com/v1/forms/*/subscribe",
            "https://api.x.com/v1/forms/12/subscribe?api_key=k"
        ));
        assert!(matches_pattern(
            "https://api.x.com/*",
            "https://api.x.com/a/b"
        ));
        assert!(!matches_pattern(
            "https://api.x.com/v1/users",
            "https://api.x.com/v1/users/1"
        ));
        assert!(matches_pattern(
            "https://api.x.com/v1/users?page=2",
            "https://api.x.com/v1/users?page=2"
        ));
        assert!(!matches_pattern(
            "https://api.x.com/v1/users?page=2",
            "https://api.x.com/v1/users?page=3"
        ));
    }

    #[test]
    fn urls_join_and_logs_drop_queries() {
        let client = Client::new("https://api.x.com/v1/").query_auth("api_key", "secret");
        let req = client.get("/forms").query(&[("page", "2")]);
        assert_eq!(
            req.full_url(),
            "https://api.x.com/v1/forms?api_key=secret&page=2"
        );
        assert_eq!(loggable(&req.full_url()), "https://api.x.com/v1/forms");
        assert_eq!(client.get("https://other.com/x").url, "https://other.com/x");
    }

    #[test]
    fn private_addresses() {
        for ip in [
            "127.0.0.1",
            "10.1.2.3",
            "192.168.0.9",
            "172.16.5.4",
            "169.254.169.254",
            "100.64.0.1",
            "::1",
            "fd00::1",
            "fe80::1",
            "::ffff:127.0.0.1",
            "0.0.0.0",
        ] {
            assert!(is_private(ip.parse().unwrap()), "{ip}");
        }
        for ip in ["8.8.8.8", "1.1.1.1", "2606:4700::1111"] {
            assert!(!is_private(ip.parse().unwrap()), "{ip}");
        }
    }

    #[tokio::test]
    async fn public_only_clients_refuse_private_hosts() {
        let client = Client::new("http://127.0.0.1:9").public_only();
        let err = client.get("x").send().await.unwrap_err();
        assert_eq!(
            err.downcast_ref::<ClientError>().unwrap().kind,
            ErrorKind::Blocked
        );
        let err = Client::new("http://localhost:9")
            .public_only()
            .get("x")
            .send()
            .await
            .unwrap_err();
        assert_eq!(
            err.downcast_ref::<ClientError>().unwrap().kind,
            ErrorKind::Blocked,
            "after DNS"
        );
    }

    #[test]
    fn backs_off_exponentially() {
        assert_eq!(backoff(1), Duration::from_millis(500));
        assert_eq!(backoff(3), Duration::from_secs(2));
    }
}