delopay 0.2.1

Official Rust SDK for the DeloPay payments API
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
//! The [`Delopay`] client and its HTTP core.

use std::sync::Arc;
use std::time::Duration;

use serde::de::DeserializeOwned;

use crate::core::error::{DelopayError, Result};
use crate::http::hyper_backend::HyperTransport;
use crate::http::proxy::ProxyMode;
use crate::http::retry::{backoff, parse_retry_after};
use crate::http::transport::{HttpMethod, RawRequest, Transport, TransportErrorKind};
use crate::resources::cards::Cards;
use crate::resources::customers::Customers;
use crate::resources::disputes::Disputes;
use crate::resources::ephemeral_keys::EphemeralKeys;
use crate::resources::events::Events;
use crate::resources::export::Export;
use crate::resources::files::Files;
use crate::resources::forex::Forex;
use crate::resources::mandates::Mandates;
use crate::resources::payment_links::PaymentLinks;
use crate::resources::payment_methods::PaymentMethods;
use crate::resources::payments::Payments;
use crate::resources::payouts::Payouts;
use crate::resources::poll::Poll;
use crate::resources::refunds::Refunds;
use crate::resources::subscriptions::Subscriptions;
use crate::{PRODUCTION_URL, SANDBOX_URL};

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;

/// The DeloPay API client.
///
/// Construct once with your secret API key and reuse it — it holds a pooled
/// HTTP client internally and is cheap to [`clone`](Clone).
///
/// ```no_run
/// use delopay::Delopay;
/// let client = Delopay::new("prd_your_secret_key");        // production
/// let sandbox = Delopay::sandbox("snd_your_secret_key");   // sandbox
/// ```
#[derive(Debug, Clone)]
pub struct Delopay {
    pub(crate) inner: Arc<Inner>,
}

pub(crate) struct Inner {
    transport: Arc<dyn Transport>,
    base_url: String,
    checkout_base_url: String,
    api_key: String,
    max_retries: u32,
}

// Hand-written rather than derived: `api_key` is deliberately omitted so a
// secret key cannot leak into logs via `{:?}` on a `Delopay`.
impl std::fmt::Debug for Inner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Inner")
            .field("base_url", &self.base_url)
            .field("checkout_base_url", &self.checkout_base_url)
            .field("max_retries", &self.max_retries)
            .finish_non_exhaustive()
    }
}

impl Delopay {
    /// Create a production client with the given secret API key (`prd_...`).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::builder(api_key).build()
    }

    /// Create a sandbox client with the given sandbox API key (`snd_...`).
    pub fn sandbox(api_key: impl Into<String>) -> Self {
        Self::builder(api_key).sandbox(true).build()
    }

    /// Start building a client with custom options.
    pub fn builder(api_key: impl Into<String>) -> DelopayBuilder {
        DelopayBuilder::new(api_key)
    }

    /// The resolved API base URL used for all requests.
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// The `payments` resource.
    pub fn payments(&self) -> Payments {
        Payments::new(self.inner.clone())
    }

    /// The `refunds` resource.
    pub fn refunds(&self) -> Refunds {
        Refunds::new(self.inner.clone())
    }

    /// The `customers` resource.
    pub fn customers(&self) -> Customers {
        Customers::new(self.inner.clone())
    }

    /// The `payment_methods` resource.
    pub fn payment_methods(&self) -> PaymentMethods {
        PaymentMethods::new(self.inner.clone())
    }

    /// The `payouts` resource.
    pub fn payouts(&self) -> Payouts {
        Payouts::new(self.inner.clone())
    }

    /// The `disputes` resource.
    pub fn disputes(&self) -> Disputes {
        Disputes::new(self.inner.clone())
    }

    /// The `mandates` resource.
    pub fn mandates(&self) -> Mandates {
        Mandates::new(self.inner.clone())
    }

    /// The `events` resource.
    pub fn events(&self) -> Events {
        Events::new(self.inner.clone())
    }

    /// The `payment_links` resource.
    pub fn payment_links(&self) -> PaymentLinks {
        PaymentLinks::new(self.inner.clone())
    }

    /// The `ephemeral_keys` resource.
    pub fn ephemeral_keys(&self) -> EphemeralKeys {
        EphemeralKeys::new(self.inner.clone())
    }

    /// The `poll` resource.
    pub fn poll(&self) -> Poll {
        Poll::new(self.inner.clone())
    }

    /// The `subscriptions` resource. Subscription endpoints are
    /// profile-scoped — chain
    /// [`with_profile_id`](Subscriptions::with_profile_id) to set the shop.
    pub fn subscriptions(&self) -> Subscriptions {
        Subscriptions::new(self.inner.clone())
    }

    /// The `cards` resource.
    pub fn cards(&self) -> Cards {
        Cards::new(self.inner.clone())
    }

    /// The `forex` resource.
    pub fn forex(&self) -> Forex {
        Forex::new(self.inner.clone())
    }

    /// The `files` resource.
    pub fn files(&self) -> Files {
        Files::new(self.inner.clone())
    }

    /// The `export` resource.
    pub fn export(&self) -> Export {
        Export::new(self.inner.clone())
    }

    /// Build the shopper-facing hosted-checkout URL for a payment.
    ///
    /// `https://checkout.delopay.net/pay/{merchant_id}/{payment_id}`
    pub fn hosted_checkout_url(&self, merchant_id: &str, payment_id: &str) -> String {
        format!(
            "{}/pay/{}/{}",
            self.inner.checkout_base_url.trim_end_matches('/'),
            merchant_id,
            payment_id
        )
    }
}

impl Inner {
    /// Build an `Inner` over an arbitrary transport. Used by the builder and by
    /// tests that inject a mock backend.
    pub(crate) fn with_transport(
        transport: Arc<dyn Transport>,
        base_url: String,
        checkout_base_url: String,
        api_key: String,
        max_retries: u32,
    ) -> Self {
        Self {
            transport,
            base_url,
            checkout_base_url,
            api_key,
            max_retries,
        }
    }

    /// Perform a request with auth, timeout, retries and typed error handling.
    ///
    /// `body` is pre-serialized JSON (or `None`). Retries cover 429 always, and
    /// network/5xx only for idempotent calls (GET, or a POST carrying an
    /// idempotency key) so a create is never silently duplicated.
    ///
    /// Non-generic so the retry loop is compiled once, not per response type.
    pub(crate) async fn send_raw(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
        extra_headers: &[(&str, &str)],
    ) -> Result<Vec<u8>> {
        let url = format!("{}{}", self.base_url, path);
        let is_idempotent = method.is_inherently_idempotent() || idempotency_key.is_some();
        let mut attempt: u32 = 0;

        loop {
            let mut headers: Vec<(&str, &str)> =
                vec![("api-key", &self.api_key), ("accept", "application/json")];
            if let Some(key) = idempotency_key {
                headers.push(("idempotency-key", key));
            }
            headers.extend_from_slice(extra_headers);

            let req = RawRequest {
                method,
                url: &url,
                headers: &headers,
                query,
                body,
            };

            match self.transport.execute(req).await {
                Ok(resp) => {
                    if resp.is_success() {
                        return Ok(resp.body);
                    }

                    let too_many = resp.status == 429;
                    let retriable = too_many || resp.is_server_error();
                    let may_retry =
                        attempt < self.max_retries && retriable && (too_many || is_idempotent);

                    if may_retry {
                        attempt += 1;
                        let delay = parse_retry_after(resp.header("retry-after"))
                            .unwrap_or_else(|| backoff(attempt));
                        tokio::time::sleep(delay).await;
                        continue;
                    }

                    let request_id = resp.header("x-request-id").map(str::to_owned);
                    return Err(DelopayError::from_response(
                        resp.status,
                        request_id,
                        &resp.body,
                    ));
                }
                Err(err) => {
                    if err.is_retriable() && is_idempotent && attempt < self.max_retries {
                        attempt += 1;
                        tokio::time::sleep(backoff(attempt)).await;
                        continue;
                    }
                    if err.kind == TransportErrorKind::Timeout {
                        return Err(DelopayError::Timeout);
                    }
                    return Err(DelopayError::Transport(err.source));
                }
            }
        }
    }

    /// Thin generic wrapper — the only part monomorphized per response type.
    pub(crate) async fn request<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
    ) -> Result<T> {
        let bytes = self
            .send_raw(method, path, body, query, idempotency_key, &[])
            .await?;
        decode_success(&bytes)
    }

    /// [`request`](Self::request) with additional per-request headers, for the
    /// few endpoints that need one (e.g. the `x-profile-id` scoping header on
    /// subscriptions). Kept separate so the common path stays a five-argument
    /// call and existing call sites are untouched.
    pub(crate) async fn request_with_headers<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
        extra_headers: &[(&str, &str)],
    ) -> Result<T> {
        let bytes = self
            .send_raw(method, path, body, query, idempotency_key, extra_headers)
            .await?;
        decode_success(&bytes)
    }
}

fn decode_success<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    // Some endpoints return an empty 200/204 body; deserialize `null` so `T`
    // can be `()` or an `Option`.
    let slice: &[u8] = if bytes.is_empty() { b"null" } else { bytes };
    serde_json::from_slice(slice).map_err(|e| DelopayError::Decode(e.to_string()))
}

/// Builder for a [`Delopay`] client.
#[derive(Clone)]
pub struct DelopayBuilder {
    api_key: String,
    base_url: Option<String>,
    checkout_base_url: Option<String>,
    sandbox: bool,
    timeout: Duration,
    max_retries: u32,
    proxy: ProxyMode,
}

// Hand-written rather than derived: `api_key` is deliberately omitted so a
// secret key cannot leak into logs via `{:?}` on a `DelopayBuilder`. Mirrors
// `Inner`'s `Debug` impl above — this is the one *public* type that also
// holds the key. `proxy` is printed through `ProxyMode`'s own redacting
// `Debug`, which never renders a proxy URL's `user:pass@`.
impl std::fmt::Debug for DelopayBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DelopayBuilder")
            .field("base_url", &self.base_url)
            .field("checkout_base_url", &self.checkout_base_url)
            .field("sandbox", &self.sandbox)
            .field("timeout", &self.timeout)
            .field("max_retries", &self.max_retries)
            .field("proxy", &self.proxy)
            .finish_non_exhaustive()
    }
}

impl DelopayBuilder {
    fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: None,
            checkout_base_url: None,
            sandbox: false,
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
            proxy: ProxyMode::Env,
        }
    }

    /// Point the client at the sandbox environment (`sandbox.delopay.net`).
    pub fn sandbox(mut self, sandbox: bool) -> Self {
        self.sandbox = sandbox;
        self
    }

    /// Override the API base URL (e.g. a local dev server).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Override the hosted-checkout base URL.
    pub fn checkout_base_url(mut self, url: impl Into<String>) -> Self {
        self.checkout_base_url = Some(url.into());
        self
    }

    /// Per-request timeout (default 30s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Maximum automatic retries for idempotent requests (default 2).
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Send every request through this HTTP proxy, ignoring the environment.
    ///
    /// Accepts `http://host:port` or `http://user:password@host:port`. The
    /// connection is made with HTTP `CONNECT` tunnelling, so for an `https://`
    /// API base URL the proxy relays encrypted bytes and never sees plaintext;
    /// the TLS certificate is still validated against the API's hostname.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// let client = Delopay::builder("prd_your_secret_key")
    ///     .proxy("http://corp-egress.internal:3128")
    ///     .build();
    /// ```
    ///
    /// If the URL cannot be used — it is malformed, or names a scheme other
    /// than `http` (`https://` and `socks5://` proxies are not supported) —
    /// every request fails with [`DelopayError::Transport`]. It deliberately
    /// does **not** fall back to a direct connection: if you asked for a proxy,
    /// something is probably relying on the traffic going through it.
    pub fn proxy(mut self, url: impl Into<String>) -> Self {
        self.proxy = ProxyMode::Explicit(url.into());
        self
    }

    /// Never use a proxy, ignoring `HTTPS_PROXY` and friends in the
    /// environment.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// let client = Delopay::builder("prd_your_secret_key").no_proxy().build();
    /// ```
    pub fn no_proxy(mut self) -> Self {
        self.proxy = ProxyMode::Disabled;
        self
    }

    /// Finish building the client.
    ///
    /// Unless [`proxy`][Self::proxy] or [`no_proxy`][Self::no_proxy] was
    /// called, the proxy is taken from the environment here — `HTTPS_PROXY` /
    /// `https_proxy`, `HTTP_PROXY` / `http_proxy`, `ALL_PROXY` / `all_proxy`,
    /// filtered by `NO_PROXY` / `no_proxy` — and resolved once against the API
    /// base URL, which is where every request from this client goes.
    pub fn build(self) -> Delopay {
        let base_url = self.base_url.unwrap_or_else(|| {
            if self.sandbox {
                SANDBOX_URL
            } else {
                PRODUCTION_URL
            }
            .to_string()
        });
        let checkout_base_url = self
            .checkout_base_url
            .unwrap_or_else(|| crate::CHECKOUT_URL.to_string());

        // Resolved once, not per request: `send_raw` sends everything to
        // `base_url`'s host, so the decision cannot change between calls.
        let proxy = crate::http::proxy::resolve(&self.proxy, &base_url);

        let transport = Arc::new(HyperTransport::new(
            self.timeout,
            concat!("delopay-rust/", env!("CARGO_PKG_VERSION")),
            proxy,
        ));

        Delopay {
            inner: Arc::new(Inner::with_transport(
                transport,
                base_url,
                checkout_base_url,
                self.api_key,
                self.max_retries,
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::http::mock::{MockTransport, SeenRequest, Step};
    use crate::http::transport::TransportErrorKind;

    fn client_with(steps: Vec<Step>, max_retries: u32) -> (Delopay, Arc<MockTransport>) {
        let mock = Arc::new(MockTransport::new(steps));
        let inner = Inner::with_transport(
            mock.clone(),
            "https://api.test".to_string(),
            "https://checkout.test".to_string(),
            "prd_test".to_string(),
            max_retries,
        );
        (
            Delopay {
                inner: Arc::new(inner),
            },
            mock,
        )
    }

    #[tokio::test]
    async fn retries_429_even_for_non_idempotent_post() {
        let (client, mock) =
            client_with(vec![Step::status(429, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
    }

    #[tokio::test]
    async fn does_not_retry_5xx_for_post_without_idempotency_key() {
        let (client, mock) = client_with(vec![Step::status(500, "")], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Api(_)));
        assert_eq!(mock.call_count(), 1, "a bare POST must never be replayed");
    }

    #[tokio::test]
    async fn retries_5xx_for_post_with_idempotency_key() {
        let (client, mock) =
            client_with(vec![Step::status(500, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], Some("key-1"))
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
        assert!(
            mock.seen
                .lock()
                .unwrap()
                .iter()
                .all(SeenRequest::had_idempotency_key)
        );
    }

    #[tokio::test]
    async fn retries_5xx_for_get() {
        let (client, mock) =
            client_with(vec![Step::status(503, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();
        assert_eq!(mock.call_count(), 2);

        // Pin what the mock actually received. Without this, nothing in the
        // suite checks the method or URL, so a request sent to the wrong path
        // or with the wrong verb would still pass every retry test.
        let seen = mock.seen.lock().unwrap();
        for req in seen.iter() {
            assert_eq!(req.method, "GET");
            assert_eq!(req.url, "https://api.test/x");
        }
    }

    #[tokio::test]
    async fn stops_after_max_retries() {
        let (client, mock) = client_with(
            vec![
                Step::status(500, ""),
                Step::status(500, ""),
                Step::status(500, ""),
            ],
            2,
        );
        let _ = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 3, "initial attempt + 2 retries");
    }

    #[tokio::test]
    async fn timeout_maps_to_timeout_variant() {
        let (client, _) = client_with(vec![Step::Fail(TransportErrorKind::Timeout)], 0);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Timeout));
    }

    #[tokio::test]
    async fn connect_failure_maps_to_transport_variant() {
        let (client, _) = client_with(vec![Step::Fail(TransportErrorKind::Connect)], 0);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Transport(_)));
    }

    #[tokio::test]
    async fn maps_401_to_authentication_error() {
        let (client, _) = client_with(
            vec![Step::status(
                401,
                r#"{"error":{"code":"AUTH_01","type":"authentication_error","message":"bad key"}}"#,
            )],
            0,
        );
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        match err {
            DelopayError::Authentication(api) => assert_eq!(api.code, "AUTH_01"),
            other => panic!("expected Authentication, got {other:?}"),
        }
    }

    #[tokio::test(start_paused = true)]
    async fn honors_retry_after_header() {
        // Asserting only that a retry happened would pass even if `Retry-After`
        // were ignored entirely, because plain backoff also retries. The delay
        // itself is the behavior under test, so measure it. `start_paused`
        // gives tokio a virtual clock: sleeps complete instantly but advance
        // `Instant::now()` exactly, so this is deterministic, not timing-flaky.
        let (client, mock) = client_with(
            vec![
                Step::status_with_header(429, "retry-after", "5"),
                Step::ok(r#"{"ok":true}"#),
            ],
            2,
        );

        let started = tokio::time::Instant::now();
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();
        let waited = started.elapsed();

        assert_eq!(mock.call_count(), 2);
        assert_eq!(
            waited,
            Duration::from_secs(5),
            "must wait exactly the Retry-After value, not the {:?} backoff",
            backoff(1)
        );
    }

    #[tokio::test(start_paused = true)]
    async fn falls_back_to_backoff_when_retry_after_absent() {
        // The companion to the test above: with no `Retry-After` header the
        // delay must come from the backoff schedule instead.
        let (client, mock) =
            client_with(vec![Step::status(429, ""), Step::ok(r#"{"ok":true}"#)], 2);

        let started = tokio::time::Instant::now();
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();

        assert_eq!(mock.call_count(), 2);
        assert_eq!(started.elapsed(), backoff(1));
    }

    #[tokio::test]
    async fn post_without_idempotency_key_is_never_replayed_on_network_failure() {
        // Duplicate-charge guard: a bare POST (no idempotency key) whose
        // connection times out mid-flight must NOT be retried, because the
        // server may already have taken the charge before the timeout. A
        // retry here would mean silently double-charging the customer.
        // Mutation coverage: deleting `&& is_idempotent` from the transport-
        // error retry branch in `send_raw` makes this test fail (call_count
        // becomes 2 and the transport error is swallowed by a successful
        // second attempt).
        let (client, mock) = client_with(vec![Step::Fail(TransportErrorKind::Timeout)], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Timeout));
        assert_eq!(
            mock.call_count(),
            1,
            "a bare POST must never be replayed after a network failure — the \
             original attempt may already have taken effect server-side"
        );
    }

    #[tokio::test]
    async fn post_with_idempotency_key_is_retried_on_network_failure() {
        // Mirror image of the test above: once the caller has supplied an
        // idempotency key, a network-level failure IS safe to retry, because
        // the server can deduplicate the replay using that key.
        let (client, mock) = client_with(
            vec![
                Step::Fail(TransportErrorKind::Timeout),
                Step::ok(r#"{"ok":true}"#),
            ],
            2,
        );
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], Some("key-1"))
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
    }

    #[tokio::test]
    async fn extra_headers_reach_the_transport() {
        // Mutation coverage: deleting `headers.extend_from_slice(extra_headers)`
        // in `send_raw` makes this fail — the scoping header silently vanishes
        // from every subscriptions call.
        let (client, mock) = client_with(vec![Step::ok(r#"{"ok":true}"#)], 0);
        let _: serde_json::Value = client
            .inner
            .request_with_headers(
                HttpMethod::Post,
                "/x",
                None,
                &[],
                None,
                &[("x-profile-id", "pro_1")],
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
        assert_eq!(
            seen[0].header("api-key"),
            Some("prd_test"),
            "extra headers must be appended, not replace the built-in set"
        );
    }

    #[tokio::test]
    async fn put_without_idempotency_key_is_not_retried_on_5xx() {
        // PUT is deliberately not inherently idempotent (see `HttpMethod`).
        // Mutation coverage: making `is_inherently_idempotent` return true for
        // `Put` turns this into two calls and a swallowed error.
        let (client, mock) = client_with(vec![Step::status(500, "")], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Put, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Api(_)));
        assert_eq!(
            mock.call_count(),
            1,
            "a bare PUT must never be replayed — this API uses PUT for \
             state transitions, where a blind replay is not provably safe"
        );
    }

    #[test]
    fn delopay_builder_debug_redacts_api_key() {
        let builder = Delopay::builder("prd_super_secret_key_for_debug_test");
        let formatted = format!("{builder:?}");
        assert!(
            !formatted.contains("prd_super_secret_key_for_debug_test"),
            "DelopayBuilder's Debug output must not contain the secret api key: {formatted}"
        );
    }

    #[test]
    fn delopay_builder_debug_redacts_proxy_credentials() {
        // A proxy URL is a second secret this public type can hold. `.proxy()`
        // returns the builder, so `{:?}` on it is just as reachable as it is
        // for the API key.
        let builder =
            Delopay::builder("prd_x").proxy("http://alice:hunter2@corp-egress.internal:3128");
        let formatted = format!("{builder:?}");
        assert!(
            !formatted.contains("hunter2") && !formatted.contains("alice"),
            "DelopayBuilder's Debug output must not contain proxy credentials: {formatted}"
        );
    }

    #[test]
    fn inner_debug_redacts_api_key() {
        let mock = Arc::new(MockTransport::new(vec![]));
        let inner = Inner::with_transport(
            mock,
            "https://api.test".to_string(),
            "https://checkout.test".to_string(),
            "prd_super_secret_key_for_inner_debug_test".to_string(),
            2,
        );
        let formatted = format!("{inner:?}");
        assert!(
            !formatted.contains("prd_super_secret_key_for_inner_debug_test"),
            "Inner's Debug output must not contain the secret api key: {formatted}"
        );
    }

    #[tokio::test]
    async fn body_read_failure_is_not_retried_through_send_raw() {
        // `TransportErrorKind::Body` represents a failed body read after a
        // successful (2xx) response and must never trigger a retry — even
        // for an idempotent GET with retry budget to spare — because
        // retrying would re-issue a request whose original attempt may
        // already have taken effect server-side. `transport.rs` already
        // covers `is_retriable()` in isolation; this exercises the same
        // classification through the full `send_raw` retry loop so a
        // regression that wired `Body` into the retry branch would be
        // caught here too.
        let (client, mock) = client_with(vec![Step::Fail(TransportErrorKind::Body)], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Transport(_)));
        assert_eq!(
            mock.call_count(),
            1,
            "a Body read failure must never be retried"
        );
    }
}