grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
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
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! HTTP transport with retries, timeouts, cancellation, hooks and error mapping (SPEC §2.3).

use std::collections::BTreeMap;
use std::fmt;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Once, RwLock};
use std::time::{Duration, SystemTime};

use bytes::Bytes;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use tokio::time::Instant;
use url::Url;

pub use reqwest::Method;
pub use tokio_util::sync::CancellationToken;

use super::config::{CommonConfig, TlsConfig};
use super::error::{Error, ErrorCode, Result};
use super::hooks::{guarded, ErrorInfo, RequestInfo, ResponseInfo};
use super::redact::{redact_headers, redact_text, redact_url, truncate};
use super::retry::parse_retry_after;
use super::secret::Secret;

/// Catalog key of this SDK.
pub const SDK_KEY: &str = "graylog";
/// Package version.
pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Response headers that carry a vendor request id, checked in order.
pub const REQUEST_ID_HEADERS: &[&str] = &[
    "x-request-id",
    "x-amzn-requestid",
    "x-amz-request-id",
    "x-datadog-request-id",
    "request-id",
    "x-correlation-id",
];
/// Longest vendor error text kept in messages.
pub const MAX_VENDOR_MESSAGE: usize = 300;

const LOG_TARGET: &str = "grow_graylog::transport";

/// Standard User-Agent: `grow-codes-<key>/<version> (rust)`.
pub fn default_user_agent() -> String {
    format!("grow-codes-{SDK_KEY}/{SDK_VERSION} (rust)")
}

static INSECURE_WARNING: Once = Once::new();

/// One HTTP client per SDK client. Cheap to share by reference; see [`HttpTransport::request`].
pub struct HttpTransport {
    client: reqwest::Client,
    config: CommonConfig,
    user_agent: String,
    known_secrets: RwLock<Vec<Secret>>,
    closed: AtomicBool,
    close_token: CancellationToken,
    retry_after_hook: Option<RetryAfterHook>,
    error_mapper: Option<ErrorMapper<'static>>,
}

/// Reads a retry delay from the status and headers of an error response.
type RetryAfterHook = Box<dyn Fn(u16, &HeaderMap) -> Option<Duration> + Send + Sync>;

/// Rewrites the error built for an HTTP error response; see [`HttpTransport::with_error_mapper`].
type ErrorMapper<'a> = Box<dyn Fn(&ErrorResponse<'_>) -> Option<Error> + Send + Sync + 'a>;

/// An HTTP error response (a status that is neither 2xx/3xx nor accepted with
/// [`RequestBuilder::ok_status`]), handed to an error mapper
/// ([`HttpTransport::with_error_mapper`], [`RequestBuilder::map_error`]) before the transport
/// decides about a retry and calls [`Hooks::on_error`](super::hooks::Hooks::on_error).
#[derive(Debug)]
#[non_exhaustive]
pub struct ErrorResponse<'a> {
    /// Operation name used in error messages (for example `"GET /v1/x"`).
    pub operation: &'a str,
    /// HTTP method.
    pub method: &'a Method,
    /// HTTP status.
    pub status: u16,
    /// Response headers.
    pub headers: &'a HeaderMap,
    /// Raw response body.
    pub body: &'a [u8],
    /// Vendor request id from the response headers.
    pub request_id: Option<&'a str>,
    /// 1-based attempt number.
    pub attempt: u32,
    /// The canonical error the transport built (code from the status, vendor text, request id).
    pub default_error: &'a Error,
}

impl ErrorResponse<'_> {
    /// The body as UTF-8 text (`None` when not UTF-8).
    pub fn text(&self) -> Option<&str> {
        std::str::from_utf8(self.body).ok()
    }

    /// The body decoded as JSON (`None` when it is not valid JSON for `T`).
    pub fn json<T: DeserializeOwned>(&self) -> Option<T> {
        serde_json::from_slice(self.body).ok()
    }

    /// The short vendor error text the default error uses (JSON `message`/`error`/... field or
    /// the first line of a plain-text body), not yet redacted or truncated.
    pub fn vendor_text(&self) -> Option<String> {
        vendor_message(self.body)
    }
}

/// A `reqwest` client builder with the TLS (CA, client certificate, `insecure_skip_verify`),
/// proxy (environment proxies ignored) and connect-timeout settings of `config`; for SDK parts
/// that need their own HTTP client (vendor SDKs, streaming).
pub fn reqwest_client_builder(config: &CommonConfig) -> Result<reqwest::ClientBuilder> {
    let builder = reqwest::Client::builder()
        .no_proxy()
        .connect_timeout(config.connect_timeout());
    let mut builder = apply_tls(builder, config.tls())?;
    if let Some(proxy) = config.proxy() {
        let proxy = reqwest::Proxy::all(proxy)
            .map_err(|e| Error::config("proxy is not a valid URL").with_source(e.without_url()))?;
        builder = builder.proxy(proxy);
    }
    Ok(builder)
}

/// The `reqwest` client [`HttpTransport`] uses, built from `config` (see
/// [`reqwest_client_builder`]).
pub fn build_reqwest_client(config: &CommonConfig) -> Result<reqwest::Client> {
    reqwest_client_builder(config)?
        .build()
        .map_err(|e| Error::config("cannot build the HTTP client").with_source(e.without_url()))
}

/// The User-Agent for `config`: [`default_user_agent`] plus the configured suffix.
pub fn user_agent_for(config: &CommonConfig) -> String {
    match config.user_agent_suffix() {
        Some(suffix) if !suffix.is_empty() => format!("{} {suffix}", default_user_agent()),
        _ => default_user_agent(),
    }
}

/// Applies rustls, extra CA certificates, the client identity and `insecure_skip_verify`.
pub(crate) fn apply_tls(
    mut builder: reqwest::ClientBuilder,
    tls: &TlsConfig,
) -> Result<reqwest::ClientBuilder> {
    builder = builder.use_rustls_tls();
    if tls.insecure_skip_verify {
        INSECURE_WARNING.call_once(|| {
            ::tracing::warn!(
                target: LOG_TARGET,
                "TLS certificate verification is disabled (insecure_skip_verify); use only in tests"
            );
        });
        builder = builder.danger_accept_invalid_certs(true);
    }
    let mut ca_pem = Vec::new();
    if let Some(path) = &tls.ca_cert_path {
        ca_pem.extend(read_file(path, "CA certificate")?);
        ca_pem.push(b'\n');
    }
    if let Some(pem) = &tls.ca_cert_pem {
        ca_pem.extend_from_slice(pem.as_bytes());
    }
    if !ca_pem.is_empty() {
        let certs = reqwest::Certificate::from_pem_bundle(&ca_pem)
            .map_err(|e| Error::config("CA certificate is not valid PEM").with_source(e))?;
        if certs.is_empty() {
            return Err(Error::config("CA certificate contains no certificate"));
        }
        for cert in certs {
            builder = builder.add_root_certificate(cert);
        }
    }
    if let (Some(cert), Some(key)) = (&tls.client_cert_path, &tls.client_key_path) {
        let mut pem = read_file(cert, "client certificate")?;
        pem.push(b'\n');
        pem.extend(read_file(key, "client key")?);
        let identity = reqwest::Identity::from_pem(&pem).map_err(|e| {
            Error::config("client certificate or key is not valid PEM").with_source(e)
        })?;
        builder = builder.identity(identity);
    }
    Ok(builder)
}

impl fmt::Debug for HttpTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpTransport")
            .field("base_url", &redact_url(self.config.url().as_str()))
            .field("user_agent", &self.user_agent)
            .field("closed", &self.is_closed())
            .finish_non_exhaustive()
    }
}

impl HttpTransport {
    /// Builds the transport (TLS, proxy, timeouts) from a validated config.
    pub fn new(config: &CommonConfig) -> Result<Self> {
        let client = build_reqwest_client(config)?;
        Ok(HttpTransport {
            client,
            config: config.clone(),
            user_agent: user_agent_for(config),
            known_secrets: RwLock::new(Vec::new()),
            closed: AtomicBool::new(false),
            close_token: CancellationToken::new(),
            retry_after_hook: None,
            error_mapper: None,
        })
    }

    /// Installs the service's error mapper: it receives every HTTP error response
    /// ([`ErrorResponse`], with the canonical error the transport built) and returns the error
    /// to use instead, or `None` to keep the canonical one (for example a vendor error code in
    /// the body that means `CONFLICT`). It runs after a per-request
    /// [`RequestBuilder::map_error`] that returned `None`, and before the retry decision and
    /// [`Hooks::on_error`](super::hooks::Hooks::on_error), so hooks and the caller see the
    /// mapped error. A mapped error is retried only while it [is retryable](Error::is_retryable)
    /// and the HTTP status is retryable; it gets the response's status and request id when it
    /// has none, and known secrets are redacted from its message. A panicking mapper counts as
    /// `None`.
    pub fn with_error_mapper<F>(mut self, mapper: F) -> Self
    where
        F: Fn(&ErrorResponse<'_>) -> Option<Error> + Send + Sync + 'static,
    {
        self.error_mapper = Some(Box::new(mapper));
        self
    }

    /// Installs a hook that reads a retry delay from vendor headers (for example
    /// `X-RateLimit-Reset`) of every error response. When it returns `Some`, that delay is used
    /// instead of `Retry-After` (it is still capped by `max_retry_after` and the total timeout).
    pub fn with_retry_after_hook<F>(mut self, hook: F) -> Self
    where
        F: Fn(u16, &HeaderMap) -> Option<Duration> + Send + Sync + 'static,
    {
        self.retry_after_hook = Some(Box::new(hook));
        self
    }

    /// The underlying `reqwest` client (same TLS, proxy and connect timeout), for streaming
    /// or server-sent-event calls the buffered [`request`](Self::request) API cannot serve.
    /// Requests sent with it bypass retries, hooks, redaction and [`close`](Self::close);
    /// add [`user_agent`](Self::user_agent) and the config headers yourself.
    pub fn reqwest_client(&self) -> &reqwest::Client {
        &self.client
    }

    /// The URL a request for `path` goes to (`path` may also be an absolute URL).
    pub fn url_for(&self, path: &str) -> Result<Url> {
        self.join(path, &[])
    }

    /// `CANCELLED` ("client is closed") once [`close`](Self::close) was called; for service
    /// methods that do not send a request.
    pub fn ensure_open(&self, operation: &str) -> Result<()> {
        if self.is_closed() {
            return Err(Error::cancelled(format!("{operation}: client is closed")));
        }
        Ok(())
    }

    /// The configuration in use.
    pub fn config(&self) -> &CommonConfig {
        &self.config
    }

    /// The User-Agent sent with every request.
    pub fn user_agent(&self) -> &str {
        &self.user_agent
    }

    /// Registers a credential whose value must never appear in errors, hooks or logs.
    pub fn add_known_secret(&self, secret: &Secret) {
        if secret.expose_secret().chars().count() >= 4 {
            self.known_secrets
                .write()
                .unwrap_or_else(|e| e.into_inner())
                .push(secret.clone());
        }
    }

    /// Replaces every known secret in `text` with `[REDACTED]`.
    pub fn redact(&self, text: &str) -> String {
        let secrets = self.known_secrets.read().unwrap_or_else(|e| e.into_inner());
        let values: Vec<&str> = secrets.iter().map(Secret::expose_secret).collect();
        redact_text(text, &values)
    }

    /// Starts a request; `path` is joined to the base URL (it may also be an absolute URL).
    pub fn request(&self, method: Method, path: &str) -> RequestBuilder<'_> {
        RequestBuilder {
            transport: self,
            method,
            path: path.to_owned(),
            query: Vec::new(),
            headers: Vec::new(),
            body: None,
            idempotent: None,
            operation: None,
            cancel: None,
            ok_statuses: Vec::new(),
            secrets: Vec::new(),
            error: None,
            no_retry: false,
            error_mapper: None,
        }
    }

    /// `GET` request.
    pub fn get(&self, path: &str) -> RequestBuilder<'_> {
        self.request(Method::GET, path)
    }
    /// `POST` request.
    pub fn post(&self, path: &str) -> RequestBuilder<'_> {
        self.request(Method::POST, path)
    }
    /// `PUT` request.
    pub fn put(&self, path: &str) -> RequestBuilder<'_> {
        self.request(Method::PUT, path)
    }
    /// `DELETE` request.
    pub fn delete(&self, path: &str) -> RequestBuilder<'_> {
        self.request(Method::DELETE, path)
    }

    /// Cancels in-flight requests and rejects new ones with `CANCELLED`. Idempotent.
    pub fn close(&self) {
        if !self.closed.swap(true, Ordering::SeqCst) {
            self.close_token.cancel();
        }
    }

    /// Whether [`HttpTransport::close`] was called.
    pub fn is_closed(&self) -> bool {
        self.closed.load(Ordering::SeqCst)
    }

    fn join(&self, path: &str, query: &[(String, String)]) -> Result<Url> {
        let mut url = if path.starts_with("http://") || path.starts_with("https://") {
            Url::parse(path).map_err(|_| Error::validation("request URL is not valid"))?
        } else {
            let mut url = self.config.url().clone();
            let (p, q) = match path.split_once('?') {
                Some((p, q)) => (p, Some(q)),
                None => (path, None),
            };
            let base = url.path().trim_end_matches('/').to_owned();
            url.set_path(&format!("{base}/{}", p.trim_start_matches('/')));
            url.set_query(q);
            url
        };
        if !query.is_empty() {
            url.query_pairs_mut().extend_pairs(query);
        }
        Ok(url)
    }

    fn header_map(&self, req: &RequestBuilder<'_>) -> Result<HeaderMap> {
        let mut map = HeaderMap::new();
        let mut put = |name: &str, value: &str| -> Result<()> {
            let n = HeaderName::from_bytes(name.as_bytes())
                .map_err(|_| Error::validation(format!("invalid header name {name:?}")))?;
            let v = HeaderValue::from_str(value)
                .map_err(|_| Error::validation(format!("invalid value for header {name:?}")))?;
            map.insert(n, v);
            Ok(())
        };
        put("user-agent", &self.user_agent)?;
        put("accept", "application/json")?;
        for (k, v) in self.config.headers() {
            put(k, v)?;
        }
        if let Some((_, content_type)) = &req.body {
            put("content-type", content_type)?;
        }
        for (k, v) in &req.headers {
            put(k, v.expose_secret())?;
        }
        Ok(map)
    }

    async fn execute(&self, req: RequestBuilder<'_>) -> Result<Response> {
        let operation = req.operation.clone().unwrap_or_else(|| {
            format!(
                "{} {}",
                req.method,
                req.path.split('?').next().unwrap_or("")
            )
        });
        if let Some(err) = req.error.clone() {
            return Err(err.with_message(format!("{operation}: invalid request body")));
        }
        if self.is_closed() {
            return Err(Error::cancelled(format!("{operation}: client is closed")));
        }
        for s in &req.secrets {
            self.add_known_secret(s);
        }
        let url = self.join(&req.path, &req.query)?;
        let headers = self.header_map(&req)?;
        let redacted_url = self.redact(&redact_url(url.as_str()));
        let redacted_headers: BTreeMap<String, String> = redact_headers(
            headers
                .iter()
                .map(|(k, v)| (k.as_str(), v.to_str().unwrap_or("[binary]"))),
        )
        .into_iter()
        .map(|(k, v)| (k, self.redact(&v)))
        .collect();
        let method = req.method.clone();
        let idempotent = req.idempotent.unwrap_or(matches!(
            method,
            Method::GET | Method::HEAD | Method::OPTIONS | Method::PUT | Method::DELETE
        ));
        let mut policy = self.config.retry().clone();
        if req.no_retry {
            policy.max_retries = 0;
        }
        let request_timeout = self.config.request_timeout();
        let deadline = Instant::now() + self.config.total_timeout();
        let hooks = self.config.hooks().cloned();
        let mut attempt: u32 = 0;

        loop {
            attempt += 1;
            let retry_index = attempt - 1;
            if let Some(h) = &hooks {
                let info = RequestInfo {
                    method: method.to_string(),
                    url: redacted_url.clone(),
                    headers: redacted_headers.clone(),
                    attempt,
                };
                guarded(|| h.on_request(&info));
            }
            ::tracing::debug!(target: LOG_TARGET, method = %method, url = %redacted_url, attempt, "request");

            let remaining = deadline.saturating_duration_since(Instant::now());
            let total_limited = remaining < request_timeout;
            let attempt_timeout = request_timeout.min(remaining);
            let mut builder = self
                .client
                .request(method.clone(), url.clone())
                .headers(headers.clone());
            if let Some((body, _)) = &req.body {
                builder = builder.body(body.clone());
            }
            let started = Instant::now();
            let fut = async move {
                let resp = builder.send().await?;
                let status = resp.status().as_u16();
                let headers = resp.headers().clone();
                let body = resp.bytes().await?;
                Ok::<_, reqwest::Error>((status, headers, body))
            };
            let outcome = tokio::select! {
                biased;
                _ = wait_cancel(req.cancel.as_ref()) => None,
                _ = self.close_token.cancelled() => None,
                r = tokio::time::timeout(attempt_timeout, fut) => Some(r),
            };
            let Some(outcome) = outcome else {
                let err = Error::cancelled(format!("{operation}: cancelled"));
                self.emit_error(&hooks, &method, &redacted_url, &err, attempt, None);
                return Err(err);
            };

            let mut retry_after = None;
            let (err, may_retry) = match outcome {
                Err(_elapsed) => {
                    let err = if total_limited {
                        Error::timeout(format!(
                            "{operation}: total timeout of {} ms exceeded",
                            self.config.total_timeout().as_millis()
                        ))
                    } else {
                        Error::timeout(format!(
                            "{operation}: request timed out after {} ms",
                            request_timeout.as_millis()
                        ))
                    };
                    (err, idempotent && !total_limited)
                }
                Ok(Err(e)) => self.network_error(&operation, e, idempotent),
                Ok(Ok((status, resp_headers, body))) => {
                    let request_id = request_id(&resp_headers);
                    if let Some(h) = &hooks {
                        let info = ResponseInfo {
                            method: method.to_string(),
                            url: redacted_url.clone(),
                            status,
                            duration: started.elapsed(),
                            attempt,
                            request_id: request_id.clone(),
                        };
                        guarded(|| h.on_response(&info));
                    }
                    ::tracing::debug!(target: LOG_TARGET, method = %method, url = %redacted_url, status, attempt, "response");
                    if (200..400).contains(&status) || req.ok_statuses.contains(&status) {
                        return Ok(Response {
                            status,
                            headers: resp_headers,
                            body,
                            request_id,
                        });
                    }
                    if let Some(hook) = &self.retry_after_hook {
                        retry_after =
                            catch_unwind(AssertUnwindSafe(|| hook(status, &resp_headers)))
                                .ok()
                                .flatten();
                    }
                    if retry_after.is_none() && matches!(status, 429 | 503) {
                        retry_after = resp_headers
                            .get("retry-after")
                            .and_then(|v| v.to_str().ok())
                            .and_then(|v| parse_retry_after(v, SystemTime::now()));
                    }
                    let err = self.status_error(&operation, status, &body, request_id.clone());
                    let retryable = match status {
                        429 => true,
                        408 | 502 | 503 | 504 => idempotent,
                        500 => idempotent,
                        _ => false,
                    };
                    let response = ErrorResponse {
                        operation: &operation,
                        method: &method,
                        status,
                        headers: &resp_headers,
                        body: &body,
                        request_id: request_id.as_deref(),
                        attempt,
                        default_error: &err,
                    };
                    match self.map_error(&req, &response) {
                        Some(mapped) => {
                            let retryable = retryable && mapped.is_retryable();
                            (mapped, retryable)
                        }
                        None => (err, retryable),
                    }
                }
            };
            let err = match retry_after {
                Some(ra) => err.with_retry_after(ra),
                None => err,
            };

            if !may_retry || retry_index >= policy.max_retries {
                self.emit_error(&hooks, &method, &redacted_url, &err, attempt, None);
                return Err(err);
            }
            let mut delay = policy.backoff(retry_index);
            if let Some(ra) = retry_after {
                if ra > policy.max_retry_after {
                    self.emit_error(&hooks, &method, &redacted_url, &err, attempt, None);
                    return Err(err);
                }
                delay = delay.max(ra);
            }
            if Instant::now() + delay >= deadline {
                self.emit_error(&hooks, &method, &redacted_url, &err, attempt, None);
                if retry_after.is_some() {
                    return Err(err);
                }
                return Err(Error::timeout(format!(
                    "{operation}: total timeout of {} ms exhausted after {attempt} attempts",
                    self.config.total_timeout().as_millis()
                ))
                .with_source(err));
            }
            self.emit_error(&hooks, &method, &redacted_url, &err, attempt, Some(delay));
            let cancelled = tokio::select! {
                biased;
                _ = wait_cancel(req.cancel.as_ref()) => true,
                _ = self.close_token.cancelled() => true,
                _ = tokio::time::sleep(delay) => false,
            };
            if cancelled {
                return Err(Error::cancelled(format!(
                    "{operation}: cancelled during retry backoff"
                )));
            }
        }
    }

    /// Applies the per-request mapper, then the transport's; the first `Some` wins.
    fn map_error(&self, req: &RequestBuilder<'_>, response: &ErrorResponse<'_>) -> Option<Error> {
        let mapped = [req.error_mapper.as_ref(), self.error_mapper.as_ref()]
            .into_iter()
            .flatten()
            .find_map(|m| {
                catch_unwind(AssertUnwindSafe(|| m(response)))
                    .ok()
                    .flatten()
            })?;
        let message = self.redact(mapped.message());
        let mut mapped = mapped.with_message(message);
        if mapped.http_status().is_none() {
            mapped = mapped.with_status(response.status);
        }
        if let (None, Some(id)) = (mapped.request_id(), response.request_id) {
            mapped = mapped.with_request_id(id);
        }
        Some(mapped)
    }

    fn emit_error(
        &self,
        hooks: &Option<std::sync::Arc<dyn super::hooks::Hooks>>,
        method: &Method,
        url: &str,
        err: &Error,
        attempt: u32,
        retry_delay: Option<Duration>,
    ) {
        ::tracing::debug!(
            target: LOG_TARGET,
            method = %method,
            url = %url,
            attempt,
            code = %err.code(),
            error = %err,
            will_retry = retry_delay.is_some(),
            "request failed"
        );
        if let Some(h) = hooks {
            let info = ErrorInfo {
                method: method.to_string(),
                url: url.to_owned(),
                error: err.clone(),
                attempt,
                will_retry: retry_delay.is_some(),
                retry_delay,
            };
            guarded(|| h.on_error(&info));
        }
    }

    fn network_error(&self, operation: &str, e: reqwest::Error, idempotent: bool) -> (Error, bool) {
        let before_send = e.is_connect();
        let err = if e.is_timeout() {
            Error::timeout(format!("{operation}: connection timed out"))
        } else if before_send {
            Error::unavailable(format!("{operation}: connection failed"))
        } else if e.is_decode() || e.is_body() {
            Error::unavailable(format!("{operation}: response could not be read"))
        } else {
            Error::unavailable(format!("{operation}: request failed"))
        };
        (err.with_source(e.without_url()), before_send || idempotent)
    }

    fn status_error(
        &self,
        operation: &str,
        status: u16,
        body: &[u8],
        request_id: Option<String>,
    ) -> Error {
        let code = ErrorCode::from_http_status(status).unwrap_or(ErrorCode::Unavailable);
        let reason = match vendor_message(body) {
            Some(text) => {
                let text = truncate(&self.redact(&text), MAX_VENDOR_MESSAGE);
                format!("{}: {text}", code.reason())
            }
            None => code.reason().to_owned(),
        };
        let err = Error::from_status(status, format!("{operation}: {reason} (HTTP {status})"));
        match request_id {
            Some(id) => err.with_request_id(id),
            None => err,
        }
    }
}

impl Drop for HttpTransport {
    fn drop(&mut self) {
        self.close_token.cancel();
    }
}

fn read_file(path: &std::path::Path, what: &str) -> Result<Vec<u8>> {
    std::fs::read(path).map_err(|e| {
        Error::config(format!("{what} file {} cannot be read", path.display())).with_source(e)
    })
}

async fn wait_cancel(token: Option<&CancellationToken>) {
    match token {
        Some(t) => t.cancelled().await,
        None => std::future::pending().await,
    }
}

fn request_id(headers: &HeaderMap) -> Option<String> {
    REQUEST_ID_HEADERS
        .iter()
        .find_map(|h| headers.get(*h).and_then(|v| v.to_str().ok()))
        .filter(|v| !v.is_empty())
        .map(str::to_owned)
}

/// Extracts a short vendor error text from a JSON or plain-text body.
fn vendor_message(body: &[u8]) -> Option<String> {
    if body.is_empty() {
        return None;
    }
    if let Ok(value) = serde_json::from_slice::<Value>(body) {
        return json_message(&value);
    }
    let text = std::str::from_utf8(body).ok()?.trim();
    if text.is_empty() || text.starts_with('<') {
        return None;
    }
    text.lines().next().map(|line| line.trim().to_owned())
}

fn json_message(value: &Value) -> Option<String> {
    match value {
        Value::String(s) if !s.trim().is_empty() => Some(s.trim().to_owned()),
        Value::Array(items) => items.iter().find_map(json_message),
        Value::Object(map) => [
            "message",
            "error_description",
            "error",
            "errors",
            "detail",
            "title",
            "msg",
            "reason",
        ]
        .iter()
        .find_map(|k| map.get(*k).and_then(json_message)),
        _ => None,
    }
}

/// A request being built; finish with [`RequestBuilder::send`].
#[must_use = "a request does nothing until `send` is awaited"]
pub struct RequestBuilder<'a> {
    transport: &'a HttpTransport,
    method: Method,
    path: String,
    query: Vec<(String, String)>,
    headers: Vec<(String, Secret)>,
    body: Option<(Bytes, String)>,
    idempotent: Option<bool>,
    operation: Option<String>,
    cancel: Option<CancellationToken>,
    ok_statuses: Vec<u16>,
    secrets: Vec<Secret>,
    error: Option<Error>,
    no_retry: bool,
    error_mapper: Option<ErrorMapper<'a>>,
}

impl fmt::Debug for RequestBuilder<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestBuilder")
            .field("method", &self.method)
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

impl<'a> RequestBuilder<'a> {
    /// Adds a query parameter.
    pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.push((name.into(), value.into()));
        self
    }
    /// Adds a request header.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), Secret::new(value)));
        self
    }
    /// Adds a header whose value is a credential (redacted everywhere).
    pub fn secret_header(mut self, name: impl Into<String>, value: &Secret) -> Self {
        self.secrets.push(value.clone());
        self.headers.push((name.into(), value.clone()));
        self
    }
    /// Adds `Authorization: Bearer <token>`.
    pub fn bearer(self, token: &Secret) -> Self {
        let header = Secret::new(format!("Bearer {}", token.expose_secret()));
        let mut this = self.secret_header("authorization", &header);
        this.secrets.push(token.clone());
        this
    }
    /// Sets a JSON body.
    pub fn json<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
        match serde_json::to_vec(body) {
            Ok(bytes) => self.body = Some((Bytes::from(bytes), "application/json".to_owned())),
            Err(e) => self.error = Some(Error::from(e)),
        }
        self
    }
    /// Sets a raw body with its content type.
    pub fn body(mut self, body: impl Into<Bytes>, content_type: impl Into<String>) -> Self {
        self.body = Some((body.into(), content_type.into()));
        self
    }
    /// Marks the request as safe (or unsafe) to replay after an uncertain send.
    pub fn idempotent(mut self, idempotent: bool) -> Self {
        self.idempotent = Some(idempotent);
        self
    }
    /// Operation name used in error messages, e.g. `"kv.read secret/app"`.
    pub fn operation(mut self, operation: impl Into<String>) -> Self {
        self.operation = Some(operation.into());
        self
    }
    /// Cancels the request (and its retries) when the token is cancelled.
    pub fn cancel_token(mut self, token: CancellationToken) -> Self {
        self.cancel = Some(token);
        self
    }
    /// Sends this request once: no retry whatever the status or error (the per-attempt and
    /// total timeouts still apply).
    pub fn no_retry(mut self) -> Self {
        self.no_retry = true;
        self
    }
    /// Maps this request's HTTP error responses (see [`HttpTransport::with_error_mapper`]);
    /// runs before the transport's mapper, which only sees responses this one returned `None`
    /// for.
    pub fn map_error<F>(mut self, mapper: F) -> Self
    where
        F: Fn(&ErrorResponse<'_>) -> Option<Error> + Send + Sync + 'a,
    {
        self.error_mapper = Some(Box::new(mapper));
        self
    }
    /// Treats this non-2xx status as a normal response instead of an error.
    pub fn ok_status(mut self, status: u16) -> Self {
        self.ok_statuses.push(status);
        self
    }
    /// Sends the request with retries; non-success statuses become [`Error`]s.
    pub async fn send(self) -> Result<Response> {
        let transport = self.transport;
        transport.execute(self).await
    }
}

/// A fully read HTTP response.
#[derive(Debug, Clone)]
pub struct Response {
    status: u16,
    headers: HeaderMap,
    body: Bytes,
    request_id: Option<String>,
}

impl Response {
    /// HTTP status.
    pub fn status(&self) -> u16 {
        self.status
    }
    /// Response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    /// A header value as text.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }
    /// Vendor request id.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }
    /// Raw body.
    pub fn bytes(&self) -> &Bytes {
        &self.body
    }
    /// Body as UTF-8 text (`VALIDATION` when not UTF-8).
    pub fn text(&self) -> Result<String> {
        String::from_utf8(self.body.to_vec())
            .map_err(|_| Error::validation("response body is not valid UTF-8"))
    }
    /// Body decoded as JSON (`VALIDATION` when malformed).
    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
        Ok(serde_json::from_slice(&self.body)?)
    }
}