delopay 0.20.0

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
//! The `risk` resource: stored shop risk indexes, per connector.
//!
//! Both reads return snapshots and never score on demand, so `computed_at` is
//! the age of the answer rather than the time of the call. The caller's own
//! scope bounds the answer: a shop-scoped role, or an API key pinned to one
//! shop, gets that shop from both endpoints and cannot read a sibling's.
//!
//! The tuning methods read and change the merchant's own, adjusted risk
//! assessment at one scope: the merchant, a project or a shop. Every save and
//! reset names the `revision` it read; one made on top of a newer revision is
//! refused with `IR_16` (HTTP 400), so a concurrent edit is never
//! overwritten. Read the tuning again and decide.

use std::sync::Arc;

use serde::Serialize;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::risk::{
    MerchantRiskResponse, RiskAdjustments, RiskTuningPreviewResponse, RiskTuningResponse,
    ShopRiskResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `risk` resource, obtained via [`crate::Delopay::risk`].
#[derive(Debug, Clone)]
pub struct Risk {
    inner: Arc<Inner>,
}

impl Risk {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Every shop's stored risk for the caller's merchant, with the worst band
    /// across them. `GET /risk`
    pub async fn retrieve(&self) -> Result<MerchantRiskResponse> {
        self.inner
            .request(HttpMethod::Get, "/risk", None, &[], None)
            .await
    }

    /// One shop's stored risk index per connector.
    /// `GET /risk/shops/{profile_id}`
    pub async fn retrieve_shop(&self, profile_id: &str) -> Result<ShopRiskResponse> {
        let path = format!("/risk/shops/{}", encode_segment(profile_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// One scope's tuning: what it sets, what applies there and where each
    /// part comes from, and DeloPay's reference beside it. Needs the
    /// `RiskTuning` area's `Read` at that scope.
    ///
    /// `GET /risk/tuning`, `GET /risk/tuning/{projects|shops}/{id}`
    pub async fn retrieve_tuning(&self, target: &RiskTuningTarget) -> Result<RiskTuningResponse> {
        self.inner
            .request(HttpMethod::Get, &target.path(), None, &[], None)
            .await
    }

    /// Replace one scope's tuning. Every part left out inherits from the next
    /// scope up. A shop or project needs the area's `Edit`, the merchant-wide
    /// tuning its `Write`.
    ///
    /// A save on top of a newer revision than `expected_revision` is refused
    /// with `IR_16` (HTTP 400); a tuning that would leave a shop it reaches
    /// with nothing to score with is refused with `IR_06` (HTTP 422). Not
    /// retried after a network error or `5xx`.
    ///
    /// `PUT /risk/tuning`, `PUT /risk/tuning/{projects|shops}/{id}`
    pub async fn update_tuning(
        &self,
        target: &RiskTuningTarget,
        params: &RiskTuningUpdateRequest,
    ) -> Result<RiskTuningResponse> {
        params.adjustments.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Put, &target.path(), Some(&body), None)
            .await
    }

    /// Hand every part of one scope's tuning back to what it inherits. Refused
    /// with `IR_16` (HTTP 400) when the tuning moved past `expected_revision`.
    ///
    /// `DELETE /risk/tuning?expected_revision=…`,
    /// `DELETE /risk/tuning/{projects|shops}/{id}?expected_revision=…`
    pub async fn reset_tuning(
        &self,
        target: &RiskTuningTarget,
        expected_revision: i64,
    ) -> Result<RiskTuningResponse> {
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Delete,
                &target.path(),
                None,
                &[("expected_revision", expected_revision.to_string())],
                None,
            )
            .await
    }

    /// Estimate what a change would do to every shop it reaches, from the
    /// evidence stored up to today. Stores, scores and sends nothing; a pair
    /// with no usable evidence says why rather than showing a band.
    ///
    /// `POST /risk/tuning/preview`, `POST /risk/tuning/{projects|shops}/{id}/preview`
    pub async fn preview_tuning(
        &self,
        target: &RiskTuningTarget,
        adjustments: &RiskAdjustments,
    ) -> Result<RiskTuningPreviewResponse> {
        adjustments.validate()?;
        let path = format!("{}/preview", target.path());
        let body = to_json_vec(&PreviewBody { adjustments })?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }
}

/// The scope a risk tuning call reads or changes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RiskTuningTarget {
    /// The merchant-wide tuning.
    Merchant,
    /// One project's tuning, by project id.
    Project(String),
    /// One shop's tuning, by shop (business profile) id.
    Shop(String),
}

impl RiskTuningTarget {
    /// The tuning path this target names, with the id percent-encoded.
    fn path(&self) -> String {
        match self {
            Self::Merchant => "/risk/tuning".to_string(),
            Self::Project(id) => format!("/risk/tuning/projects/{}", encode_segment(id)),
            Self::Shop(id) => format!("/risk/tuning/shops/{}", encode_segment(id)),
        }
    }
}

/// Parameters for [`Risk::update_tuning`].
///
/// The API refuses a field it does not know here, so this request carries no
/// `extra` map.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RiskTuningUpdateRequest {
    /// The complete tuning of the scope. A part left out inherits.
    pub adjustments: RiskAdjustments,
    /// The `revision` of the last read.
    pub expected_revision: i64,
}

impl RiskTuningUpdateRequest {
    /// Replace the scope's tuning with `adjustments`, on top of
    /// `expected_revision`.
    pub fn new(adjustments: RiskAdjustments, expected_revision: i64) -> Self {
        Self {
            adjustments,
            expected_revision,
        }
    }
}

/// The `{"adjustments": …}` body of a preview.
#[derive(Serialize)]
struct PreviewBody<'a> {
    adjustments: &'a RiskAdjustments,
}

/// Names of `RiskAdjustments`'s fields as they appear on the wire (`extra`
/// excluded).
const RISK_ADJUSTMENTS_NAMED: &[&str] = &["deciding_window", "bands", "min_volume", "components"];

impl ValidateRequest for RiskAdjustments {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if RISK_ADJUSTMENTS_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on RiskAdjustments"
                )));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::models::risk::{RiskBands, RiskComponentAdjustment, RiskWindowBandOverrides};
    use crate::http::mock::{Step, client_with, client_with_retries};
    use serde_json::json;

    const SHOP_JSON: &str = r#"{
        "shop_id": "pro_1", "computed_at": "2026-01-01T00:00:00Z",
        "connectors": [{
            "connector": "stripe", "band": "watch", "index": 42, "trend": "up",
            "model_version": 3, "computed_at": "2026-01-01T00:00:00Z",
            "components": [{"name": "dispute_rate", "weight": 0.4}],
            "assessment": "reference",
            "adjusted_unavailable": {"reason": "window_unavailable", "adjustment_revision": 0},
            "card_testing_incidents": [{
                "started_at": "2026-01-01T00:00:00Z", "ended_at": "2026-01-01T00:10:00Z",
                "window_minutes": 10, "attempts": 120, "refusals": 100,
                "distinct_cards": 90, "thresholds": {"min_refusals": 10, "min_refusal_share": 0.5},
                "model_version": 3, "first_detected_at": "2026-01-01T00:05:00Z",
                "last_detected_at": "2026-01-01T00:10:00Z"
            }],
            "connector_surprise": 1
        }],
        "shop_surprise": 2
    }"#;

    #[tokio::test]
    async fn retrieve_gets_the_merchant_roll_up() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"merchant_id":"mer_1","worst_band":"watch","shops":[{SHOP_JSON}],"x":1}}"#
        ))]);
        let risk = client.risk().retrieve().await.unwrap();
        assert_eq!(risk.merchant_id, "mer_1");
        assert_eq!(risk.worst_band.as_deref(), Some("watch"));
        assert_eq!(risk.shops[0].connectors[0].index, Some(42));
        assert_eq!(risk.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/risk");
    }

    #[tokio::test]
    async fn retrieve_shop_encodes_the_profile_id() {
        let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
        let shop = client.risk().retrieve_shop("pro/1").await.unwrap();
        let connector = &shop.connectors[0];
        assert_eq!(connector.band, "watch");
        assert_eq!(connector.model_version, 3);
        assert_eq!(connector.components[0]["name"], "dispute_rate");
        assert_eq!(
            connector.adjusted_unavailable.as_ref().unwrap().reason,
            "window_unavailable"
        );
        assert_eq!(connector.card_testing_incidents[0].refusals, 100);
        assert_eq!(connector.extra["connector_surprise"], 1);
        assert_eq!(shop.extra["shop_surprise"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/risk/shops/pro%2F1");
    }

    const TUNING_JSON: &str = r#"{
        "scope": "shop", "scope_id": "pro_1",
        "adjustments": {"deciding_window": "worst_of", "min_volume": 50,
            "components": {"dispute_rate": {"threshold": 0.0075}},
            "future_knob": 3},
        "revision": 7, "updated_at": "2026-01-01T00:00:00Z",
        "updated_by": {"id": "user_1", "name": "owner@example.com"},
        "reference": {"model_version": 3, "settings": {"deciding_window": "worst_of",
            "bands": {"30d": {"watch": 40, "at_risk": 65, "critical": 85},
                "60d": {"watch": 40, "at_risk": 65, "critical": 85},
                "90d": {"watch": 40, "at_risk": 65, "critical": 85}},
            "min_volume": 20},
            "components": {"dispute_rate": {"default": {"threshold": 0.0075, "weight": 0.4}}}},
        "effective": {"settings": {"deciding_window": "worst_of",
            "bands": {"30d": {"watch": 40, "at_risk": 65, "critical": 85},
                "60d": {"watch": 40, "at_risk": 65, "critical": 85},
                "90d": {"watch": 40, "at_risk": 65, "critical": 85}},
            "min_volume": 50},
            "sources": {"deciding_window": "shop",
                "bands": {"30d": "reference", "60d": "reference", "90d": "reference"},
                "min_volume": "shop"}},
        "recompute_pending": true, "tuning_surprise": 1
    }"#;

    fn adjustments() -> RiskAdjustments {
        RiskAdjustments::new()
            .deciding_window("30d")
            .bands(RiskWindowBandOverrides {
                d30: Some(RiskBands::new(40, 65, 85)),
                ..Default::default()
            })
            .min_volume(25)
            .component(
                "refund_rate",
                RiskComponentAdjustment {
                    weight: Some(0.0),
                    ..Default::default()
                },
            )
    }

    #[tokio::test]
    async fn retrieve_tuning_gets_each_scopes_path() {
        let (client, mock) = client_with(vec![
            Step::ok(TUNING_JSON),
            Step::ok(TUNING_JSON),
            Step::ok(TUNING_JSON),
        ]);
        let tuning = client
            .risk()
            .retrieve_tuning(&RiskTuningTarget::Merchant)
            .await
            .unwrap();
        assert_eq!(tuning.revision, 7);
        assert!(tuning.recompute_pending);
        assert_eq!(tuning.adjustments.min_volume, Some(50));
        assert_eq!(
            tuning.adjustments.components["dispute_rate"].threshold,
            Some(0.0075)
        );
        assert_eq!(tuning.adjustments.extra["future_knob"], 3);
        assert_eq!(tuning.extra["tuning_surprise"], 1);
        assert!(!format!("{tuning:?}").contains("owner@example.com"));
        client
            .risk()
            .retrieve_tuning(&RiskTuningTarget::Project("prj/1".to_string()))
            .await
            .unwrap();
        client
            .risk()
            .retrieve_tuning(&RiskTuningTarget::Shop("pro_1".to_string()))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/risk/tuning");
        assert_eq!(seen[1].url, "https://api.test/risk/tuning/projects/prj%2F1");
        assert_eq!(seen[2].url, "https://api.test/risk/tuning/shops/pro_1");
    }

    #[tokio::test]
    async fn update_tuning_puts_the_adjustments_and_expected_revision() {
        let (client, mock) = client_with(vec![Step::ok(TUNING_JSON)]);
        let req = RiskTuningUpdateRequest::new(adjustments(), 7);
        client
            .risk()
            .update_tuning(&RiskTuningTarget::Shop("pro_1".to_string()), &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/risk/tuning/shops/pro_1");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "adjustments": {
                    "deciding_window": "30d",
                    "bands": {"30d": {"watch": 40, "at_risk": 65, "critical": 85}},
                    "min_volume": 25,
                    "components": {"refund_rate": {"weight": 0.0}}
                },
                "expected_revision": 7
            })
        );
    }

    #[tokio::test]
    async fn update_tuning_saves_back_fields_it_read_but_does_not_model() {
        // A field a newer API sends survives a read-modify-save: dropping
        // `extra` from serialization would reset it to inherited.
        let (client, mock) = client_with(vec![Step::ok(TUNING_JSON), Step::ok(TUNING_JSON)]);
        let target = RiskTuningTarget::Merchant;
        let read = client.risk().retrieve_tuning(&target).await.unwrap();
        let req = RiskTuningUpdateRequest::new(read.adjustments.min_volume(60), read.revision);
        client.risk().update_tuning(&target, &req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[1].body_json();
        assert_eq!(body["adjustments"]["future_knob"], 3);
        assert_eq!(body["adjustments"]["min_volume"], 60);
        assert_eq!(body["expected_revision"], 7);
    }

    #[tokio::test]
    async fn update_tuning_surfaces_a_stale_revision_as_ir_16_without_retrying() {
        let (client, mock) = client_with_retries(
            vec![Step::status(
                400,
                r#"{"error":{"code":"IR_16","type":"invalid_request","message":"The revision moved"}}"#,
            )],
            2,
        );
        let req = RiskTuningUpdateRequest::new(RiskAdjustments::new(), 6);
        let err = client
            .risk()
            .update_tuning(&RiskTuningTarget::Merchant, &req)
            .await
            .unwrap_err();
        match err {
            DelopayError::Api(api) => {
                assert_eq!(api.status, 400);
                assert_eq!(api.code, "IR_16");
            }
            other => panic!("expected Api, got {other:?}"),
        }
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn update_tuning_is_not_retried_on_5xx() {
        let (client, mock) = client_with_retries(
            vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
            2,
        );
        let req = RiskTuningUpdateRequest::new(RiskAdjustments::new(), 1);
        client
            .risk()
            .update_tuning(&RiskTuningTarget::Merchant, &req)
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn reset_tuning_deletes_with_the_expected_revision() {
        let (client, mock) = client_with(vec![Step::ok(TUNING_JSON), Step::ok(TUNING_JSON)]);
        client
            .risk()
            .reset_tuning(&RiskTuningTarget::Merchant, 7)
            .await
            .unwrap();
        client
            .risk()
            .reset_tuning(&RiskTuningTarget::Project("prj_1".to_string()), 2)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/risk/tuning?expected_revision=7"
        );
        assert!(seen[0].body.is_none());
        assert_eq!(
            seen[1].url,
            "https://api.test/risk/tuning/projects/prj_1?expected_revision=2"
        );
    }

    #[tokio::test]
    async fn preview_tuning_posts_the_adjustments_under_the_preview_path() {
        let (client, mock) = client_with(vec![
            Step::ok(
                r#"{"scope":"merchant","scope_id":"mer_1","shops":[{"shop_id":"pro_1",
                    "connectors":[{"connector":"stripe","reference":{"band":"watch","risk_index":45},
                    "current":{"band":"watch","risk_index":45},
                    "proposed":{"band":"healthy","risk_index":30},"x":1}]}],
                    "evidence_until":"2026-10-27","model_version":3,"y":2}"#,
            ),
            Step::ok(
                r#"{"scope":"shop","scope_id":"pro_1","shops":[{"shop_id":"pro_1",
                    "connectors":[{"connector":"paypal","unavailable":"no_evidence"}]}],
                    "evidence_until":"2026-10-27","model_version":3}"#,
            ),
        ]);
        let out = client
            .risk()
            .preview_tuning(&RiskTuningTarget::Merchant, &adjustments())
            .await
            .unwrap();
        let connector = &out.shops[0].connectors[0];
        assert_eq!(connector.proposed.as_ref().unwrap().band, "healthy");
        assert_eq!(connector.reference.as_ref().unwrap().risk_index, Some(45));
        assert_eq!(connector.extra["x"], 1);
        assert_eq!(out.extra["y"], 2);
        let shop = client
            .risk()
            .preview_tuning(
                &RiskTuningTarget::Shop("pro/1".to_string()),
                &RiskAdjustments::new(),
            )
            .await
            .unwrap();
        assert_eq!(
            shop.shops[0].connectors[0].unavailable.as_deref(),
            Some("no_evidence")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/risk/tuning/preview");
        assert_eq!(seen[0].body_json()["adjustments"]["min_volume"], 25);
        assert_eq!(
            seen[1].url,
            "https://api.test/risk/tuning/shops/pro%2F1/preview"
        );
        assert_eq!(seen[1].body_json(), json!({"adjustments": {}}));
    }

    /// Drift guard for `RISK_ADJUSTMENTS_NAMED`.
    #[test]
    fn risk_adjustments_named_fields_are_complete() {
        let value = serde_json::to_value(adjustments()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                RISK_ADJUSTMENTS_NAMED.contains(&key.as_str()),
                "RISK_ADJUSTMENTS_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn adjustments_validate_rejects_colliding_extra_key() {
        let mut adj = RiskAdjustments::new();
        adj.extra.insert("min_volume".to_string(), json!(5));
        match adj.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("min_volume")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// Every write here ignores the client-wide idempotency key: none sends
    /// it, and none is replayed after a `503`. Switching a call site back to
    /// `request(.., None)` makes it send the key and retry.
    #[tokio::test]
    async fn writes_ignore_the_client_wide_idempotency_key() {
        let steps = (0..3)
            .map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .risk()
            .update_tuning(
                &RiskTuningTarget::Merchant,
                &RiskTuningUpdateRequest::new(RiskAdjustments::new(), 1),
            )
            .await
            .unwrap_err();
        client
            .risk()
            .reset_tuning(&RiskTuningTarget::Shop("pro_1".to_string()), 1)
            .await
            .unwrap_err();
        client
            .risk()
            .preview_tuning(&RiskTuningTarget::Merchant, &RiskAdjustments::new())
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 3);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }

    /// A keyed client does not replay these writes after a network error
    /// either: a connect failure is retriable for a keyed call, so a call site
    /// that fell back to the client-wide key would send it and try again.
    #[tokio::test]
    async fn writes_are_not_retried_after_a_network_error_with_a_client_key() {
        let steps = (0..3)
            .map(|_| Step::Fail(crate::http::transport::TransportErrorKind::Connect))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .risk()
            .update_tuning(
                &RiskTuningTarget::Merchant,
                &RiskTuningUpdateRequest::new(RiskAdjustments::new(), 4),
            )
            .await
            .unwrap_err();
        client
            .risk()
            .reset_tuning(&RiskTuningTarget::Shop("pro_1".to_string()), 4)
            .await
            .unwrap_err();
        client
            .risk()
            .preview_tuning(&RiskTuningTarget::Merchant, &RiskAdjustments::new())
            .await
            .unwrap_err();

        assert_eq!(mock.call_count(), 3);
        let seen = mock.seen.lock().unwrap();
        for request in seen.iter() {
            assert!(
                !request.had_idempotency_key(),
                "{} sent the client key",
                request.url
            );
        }
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("PUT", "https://api.test/risk/tuning")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "DELETE",
                "https://api.test/risk/tuning/shops/pro_1?expected_revision=4"
            )
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("POST", "https://api.test/risk/tuning/preview")
        );
    }
}