hydrafetch 0.12.0

Official Rust client for the Hydrafetch web data API. Turn any URL into clean Markdown and structured data.
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
use hydrafetch::{
    BatchOptions, Client, ExtractOptions, Format, Location, NewsOptions, RateResultInput, Rating,
    ScrapeOptions, SearchJobsOptions, WaitOptions,
};
use serde_json::{json, Value};
use std::time::Duration;
use wiremock::matchers::{header, method, path, query_param};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

async fn client_for(server: &MockServer) -> Client {
    Client::builder()
        .api_key("hf_test")
        .base_url(server.uri())
        .max_retries(0)
        .build()
        .unwrap()
}

fn ok(body: Value) -> ResponseTemplate {
    ResponseTemplate::new(200).set_body_json(body)
}

#[tokio::test]
async fn sends_api_key_header_and_never_bearer() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/scrape"))
        .and(header("x-api-key", "hf_test"))
        .respond_with(ok(
            json!({ "success": true, "data": { "url": "u", "finalUrl": "u", "redirected": false, "status": 200, "cached": false, "metadata": { "title": null, "structure": "markdown", "pageType": "article", "wordCount": 2, "description": null, "language": null, "author": null, "siteName": null, "publishedTime": null, "modifiedTime": null, "image": null }, "markdown": "# hi" } }),
        ))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    let page = hf.scrape("https://example.com", None).await.unwrap();
    assert_eq!(page.markdown.as_deref(), Some("# hi"));

    let requests = server.received_requests().await.unwrap();
    assert!(requests[0].headers.get("authorization").is_none());
}

#[tokio::test]
async fn missing_key_is_rejected_at_construction() {
    std::env::remove_var("HYDRAFETCH_API_KEY");
    let err = Client::builder().build().unwrap_err();
    assert_eq!(err.code(), "MISSING_API_KEY");
}

#[tokio::test]
async fn options_ride_alongside_the_url() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/scrape"))
        .respond_with(ok(json!({ "success": true, "data": { "url": "u", "finalUrl": "u", "redirected": false, "status": 200, "cached": false, "metadata": { "title": null, "structure": "markdown", "pageType": "article", "wordCount": 2, "description": null, "language": null, "author": null, "siteName": null, "publishedTime": null, "modifiedTime": null, "image": null } } })))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    hf.scrape(
        "https://example.com",
        Some(ScrapeOptions {
            formats: Some(vec![Format::Markdown, Format::Links]),
            prefer_structure: Some(true),
            ..Default::default()
        }),
    )
    .await
    .unwrap();

    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(body["url"], "https://example.com");
    assert_eq!(body["preferStructure"], true);
    assert_eq!(body["formats"], json!(["markdown", "links"]));
    assert!(body.get("timeout").is_none());
}

#[tokio::test]
async fn extract_sends_location_and_headers() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/extract"))
        .respond_with(ok(json!({ "success": true, "data": { "results": [] } })))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    hf.extract(
        &["https://shop.example/s?q=ghee"],
        Some(ExtractOptions {
            prompt: Some("products and prices".into()),
            location: Some(Location {
                country: Some("in".into()),
                languages: Some(vec!["en-IN".into()]),
            }),
            headers: Some([("Cookie".to_string(), "store_id=42".to_string())].into()),
            ..Default::default()
        }),
    )
    .await
    .unwrap();

    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(
        body["location"],
        json!({ "country": "in", "languages": ["en-IN"] })
    );
    assert_eq!(body["headers"], json!({ "Cookie": "store_id=42" }));
}

#[tokio::test]
async fn get_endpoints_use_query_parameters() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/web/brand/logo"))
        .and(query_param("domain", "stripe.com"))
        .and(query_param("theme", "dark"))
        .respond_with(ok(
            json!({ "success": true, "data": { "url": "https://img", "domain": "stripe.com", "width": null, "height": null, "dominantColor": null, "blurhash": null, "format": "png", "kind": "icon", "variant": "light" } }),
        ))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    hf.logo(
        "stripe.com",
        Some(hydrafetch::LogoOptions {
            theme: Some("dark".into()),
            kind: None,
        }),
    )
    .await
    .unwrap();
}

#[tokio::test]
async fn error_carries_code_status_and_request_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "success": false,
            "error": { "code": "UNAUTHORIZED", "message": "Invalid API key" },
            "meta": { "requestId": "abc" }
        })))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    let err = hf.scrape("https://example.com", None).await.unwrap_err();
    assert_eq!(err.code(), "UNAUTHORIZED");
    assert_eq!(err.status(), Some(401));
    assert_eq!(err.request_id(), Some("abc"));
    assert!(err.is_auth());
}

#[tokio::test]
async fn classifies_statuses() {
    for (status, check) in [
        (401u16, "auth"),
        (402, "credits"),
        (422, "invalid"),
        (429, "retryable"),
        (503, "retryable"),
    ] {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(
                ResponseTemplate::new(status)
                    .set_body_json(json!({ "success": false, "error": { "message": "x" } })),
            )
            .mount(&server)
            .await;

        let hf = client_for(&server).await;
        let err = hf.scrape("https://example.com", None).await.unwrap_err();
        let matched = match check {
            "auth" => err.is_auth(),
            "credits" => err.is_out_of_credits(),
            "invalid" => err.is_invalid_request(),
            _ => err.is_retryable(),
        };
        assert!(matched, "status {status} should classify as {check}");
    }
}

#[tokio::test]
async fn does_not_retry_validation_failures() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(
            ResponseTemplate::new(422)
                .set_body_json(json!({ "success": false, "error": { "message": "bad url" } })),
        )
        .expect(1)
        .mount(&server)
        .await;

    let hf = Client::builder()
        .api_key("hf_test")
        .base_url(server.uri())
        .max_retries(3)
        .build()
        .unwrap();

    assert!(hf.scrape("nope", None).await.is_err());
}

#[tokio::test]
async fn batch_id_comes_from_top_level() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/batch"))
        .respond_with(
            ResponseTemplate::new(201)
                .set_body_json(json!({ "batchId": "b_1", "status": "running" })),
        )
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    assert_eq!(
        hf.start_batch(&["https://a.example"], None).await.unwrap(),
        "b_1"
    );
}

#[tokio::test]
async fn per_page_options_nest_under_scrape_options() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/batch"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "batchId": "b_1" })))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    hf.start_batch(
        &["https://a.example"],
        Some(BatchOptions {
            scrape_options: Some(ScrapeOptions {
                formats: Some(vec![Format::Markdown]),
                ..Default::default()
            }),
            ..Default::default()
        }),
    )
    .await
    .unwrap();

    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(body["scrapeOptions"]["formats"], json!(["markdown"]));
    assert!(body.get("formats").is_none());
}

#[tokio::test]
async fn polls_until_terminal() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/batch"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "batchId": "b_1" })))
        .mount(&server)
        .await;

    let statuses = std::sync::Mutex::new(vec!["completed", "running", "running"]);
    Mock::given(method("GET"))
        .and(path("/v1/web/batch/b_1"))
        .respond_with(move |_: &Request| {
            let next = statuses.lock().unwrap().pop().unwrap_or("completed");
            ok(json!({ "success": true, "data": { "id": "b_1", "kind": "batch", "status": next, "seedUrl": null, "total": 1, "completed": 0, "failed": 0, "creditsUsed": 0, "pages": [] } }))
        })
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    let job = hf
        .batch(
            &["https://a.example"],
            None,
            Some(WaitOptions {
                poll_interval: Duration::from_millis(1),
                timeout: Duration::from_secs(5),
            }),
        )
        .await
        .unwrap();

    assert_eq!(job.status.to_string(), "completed");
}

#[tokio::test]
async fn job_polling_times_out() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/batch"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "batchId": "b_1" })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/web/batch/b_1"))
        .respond_with(ok(
            json!({ "success": true, "data": { "id": "b_1", "kind": "batch", "status": "running", "seedUrl": null, "total": 1, "completed": 0, "failed": 0, "creditsUsed": 0, "pages": [] } }),
        ))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    let err = hf
        .batch(
            &["https://a.example"],
            None,
            Some(WaitOptions {
                poll_interval: Duration::from_millis(1),
                timeout: Duration::from_millis(5),
            }),
        )
        .await
        .unwrap_err();

    assert!(err.is_timeout());
}

#[tokio::test]
async fn styleguide_reads_one_page_fresh() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/web/styleguide"))
        .and(query_param("url", "https://stripe.com/pricing"))
        .and(query_param("maxAge", "0"))
        .respond_with(ok(json!({ "success": true, "data": {} })))
        .expect(1)
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    let _ = hf
        .styleguide_with(
            "https://stripe.com/pricing",
            hydrafetch::StyleguideOptions { max_age: Some(0) },
        )
        .await;
}

#[tokio::test]
async fn rate_result_posts_the_rating_for_the_last_request() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/scrape"))
        .respond_with(
            ok(json!({ "success": true, "data": { "url": "u", "finalUrl": "u", "redirected": false, "status": 200, "cached": false, "metadata": { "title": null, "structure": "markdown", "pageType": "article", "wordCount": 2, "description": null, "language": null, "author": null, "siteName": null, "publishedTime": null, "modifiedTime": null, "image": null }, "markdown": "# hi" } }))
                .insert_header("x-request-id", "r1"),
        )
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1/web/feedback"))
        .respond_with(ok(
            json!({ "success": true, "data": { "id": "f1", "requestId": "r1", "rating": "bad" } }),
        ))
        .mount(&server)
        .await;

    let hf = client_for(&server).await;
    hf.scrape("https://example.com", None).await.unwrap();
    assert_eq!(hf.last_request_id().as_deref(), Some("r1"));

    let mut input = RateResultInput::for_request(hf.last_request_id().unwrap(), Rating::Bad);
    input.reasons = vec!["missing_content".to_string()];
    input.note = Some("no prices".to_string());
    let out = hf.rate_result(input).await.unwrap();
    assert_eq!(out.rating, Rating::Bad);

    let requests = server.received_requests().await.unwrap();
    let body: Value = serde_json::from_slice(&requests[1].body).unwrap();
    assert_eq!(
        body,
        json!({ "requestId": "r1", "rating": "bad", "reasons": ["missing_content"], "note": "no prices" })
    );
}

#[tokio::test]
async fn rate_result_needs_a_target() {
    let server = MockServer::start().await;
    let hf = client_for(&server).await;
    let input = RateResultInput {
        request_id: None,
        url: None,
        rating: Rating::Good,
        reasons: Vec::new(),
        note: None,
    };
    assert!(hf.rate_result(input).await.is_err());
}

#[tokio::test]
async fn search_jobs_posts_the_query_and_returns_the_list() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/index/jobs/search"))
        .respond_with(ok(json!({ "success": true, "data": [{
            "title": "Data Engineer", "company": null, "domain": "acme.com", "board": "greenhouse",
            "department": null, "location": "Berlin", "remote": false, "employmentType": null,
            "postedAt": null, "firstSeenAt": "2026-11-01T00:00:00Z", "url": null,
            "applyUrl": null, "pay": { "min": 70000, "max": null, "currency": "EUR", "interval": "year" }
        }] })))
        .mount(&server)
        .await;
    let hf = client_for(&server).await;
    let options = SearchJobsOptions {
        location: Some("Berlin".to_string()),
        limit: Some(20),
        ..Default::default()
    };
    let jobs = hf
        .search_jobs("data engineer", Some(options))
        .await
        .unwrap();
    assert_eq!(jobs.len(), 1);
    assert_eq!(jobs[0].pay.as_ref().unwrap().min, Some(70000.0));
    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(
        body,
        json!({ "query": "data engineer", "location": "Berlin", "limit": 20 })
    );
}

#[tokio::test]
async fn hiring_changes_sends_the_domains_and_since() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/index/jobs/changes"))
        .respond_with(ok(json!({ "success": true, "data": [{
            "domain": "acme.com", "company": "Acme", "lastReadAt": null, "since": "2026-10-01",
            "totals": { "open": 4, "opened": 2, "closed": 1 },
            "byDepartment": {}, "bySeniority": {}, "byLocation": {},
            "opened": [], "closed": [], "truncated": false
        }] })))
        .mount(&server)
        .await;
    let hf = client_for(&server).await;
    let out = hf
        .hiring_changes(&["acme.com"], "2026-10-01", None)
        .await
        .unwrap();
    assert_eq!(out[0].totals.opened, 2);
    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(
        body,
        json!({ "domains": ["acme.com"], "since": "2026-10-01" })
    );
}

#[tokio::test]
async fn news_posts_the_query_and_window() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/news"))
        .respond_with(ok(json!({ "success": true, "data": {
            "query": "acme raises", "status": "ok", "results": [{
                "title": "Acme raises $10M", "url": "https://example.com/a", "source": null,
                "publishedAt": "2026-11-04T10:00:00Z", "snippet": null, "data": null
            }]
        } })))
        .mount(&server)
        .await;
    let hf = client_for(&server).await;
    let options = NewsOptions {
        time_range: Some("day".to_string()),
        limit: Some(5),
        ..Default::default()
    };
    let news = hf.news("acme raises", Some(options)).await.unwrap();
    assert_eq!(news.status.to_string(), "ok");
    assert_eq!(news.results[0].published_at, "2026-11-04T10:00:00Z");
    let requests = server.received_requests().await.unwrap();
    let body: Value = requests[0].body_json().unwrap();
    assert_eq!(
        body,
        json!({ "query": "acme raises", "timeRange": "day", "limit": 5 })
    );
}

#[tokio::test]
async fn map_reads_each_link_with_its_lastmod() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(ok(json!({ "success": true, "data": {
            "url": "https://example.com",
            "links": [
                { "url": "https://example.com/a", "lastmod": "2026-10-20T00:00:00.000Z" },
                { "url": "https://example.com/b", "lastmod": null }
            ],
            "count": 2, "total": 53, "truncated": false
        } })))
        .mount(&server)
        .await;
    let hf = client_for(&server).await;
    let site = hf.map("https://example.com", None).await.unwrap();
    assert_eq!(site.links.len(), 2);
    assert_eq!(site.links[0].url, "https://example.com/a");
    assert!(site.links[1].lastmod.is_none());
    assert_eq!(site.total, 53);
}

fn page_json() -> Value {
    json!({ "url": "u", "finalUrl": "u", "redirected": false, "status": 200, "cached": false, "metadata": { "title": null, "structure": "markdown", "pageType": "article", "wordCount": 2, "description": null, "language": null, "author": null, "siteName": null, "publishedTime": null, "modifiedTime": null, "image": null }, "markdown": "# hi" })
}

async fn polling_client(server: &MockServer) -> Client {
    Client::builder()
        .api_key("hf_test")
        .base_url(server.uri())
        .max_retries(0)
        .job_poll_interval(Duration::from_millis(1))
        .build()
        .unwrap()
}

#[tokio::test]
async fn a_202_is_followed_until_the_job_completes() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/scrape"))
        .respond_with(ResponseTemplate::new(202).set_body_json(
            json!({ "jobId": "j-1", "status": "running", "poll": "/v1/web/jobs/j-1" }),
        ))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/web/jobs/j-1"))
        .respond_with(ok(
            json!({ "jobId": "j-1", "status": "completed", "result": { "data": page_json() } }),
        ))
        .mount(&server)
        .await;

    let page = polling_client(&server)
        .await
        .scrape("https://example.com", None)
        .await
        .unwrap();
    assert_eq!(page.markdown.as_deref(), Some("# hi"));
}

#[tokio::test]
async fn a_failed_job_returns_the_error_the_call_would_have() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/scrape"))
        .respond_with(ResponseTemplate::new(202).set_body_json(
            json!({ "jobId": "j-1", "status": "running", "poll": "/v1/web/jobs/j-1" }),
        ))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/web/jobs/j-1"))
        .respond_with(ok(json!({ "jobId": "j-1", "status": "failed", "error": { "code": "SERVICE_UNAVAILABLE", "message": "walled", "status": 503 } })))
        .mount(&server)
        .await;

    let err = polling_client(&server)
        .await
        .scrape("https://example.com", None)
        .await
        .unwrap_err();
    match err {
        hydrafetch::Error::Api { code, status, .. } => {
            assert_eq!(code, "SERVICE_UNAVAILABLE");
            assert_eq!(status, 503);
        }
        other => panic!("unexpected {other:?}"),
    }
}

fn retrying_client(server: &MockServer) -> Client {
    Client::builder()
        .api_key("hf_test")
        .base_url(server.uri())
        .max_retries(2)
        .build()
        .unwrap()
}

#[tokio::test]
async fn waits_for_the_retry_after_header_before_retrying() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(
            ResponseTemplate::new(429)
                .insert_header("Retry-After", "1")
                .set_body_json(json!({ "success": false, "error": { "code": "TOO_MANY_REQUESTS", "message": "slow down" } })),
        )
        .up_to_n_times(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(ok(json!({ "success": true, "data": { "url": "u", "links": [], "count": 0, "total": 0, "truncated": false } })))
        .mount(&server)
        .await;

    let started = std::time::Instant::now();
    let result = retrying_client(&server)
        .map("https://example.com", None)
        .await;
    assert!(result.is_ok(), "{result:?}");
    assert!(started.elapsed() >= Duration::from_millis(950));
}

#[tokio::test]
async fn returns_at_once_when_the_server_asks_for_a_long_wait() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(ResponseTemplate::new(503).set_body_json(json!({
            "success": false,
            "error": { "code": "SERVICE_UNAVAILABLE", "message": "later", "details": { "retryAfterSeconds": 900 } }
        })))
        .mount(&server)
        .await;

    let err = retrying_client(&server)
        .map("https://example.com", None)
        .await
        .unwrap_err();
    assert_eq!(err.retry_after(), Some(900));
    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

#[tokio::test]
async fn reuses_one_idempotency_key_across_retries_of_a_post() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(
            ResponseTemplate::new(503)
                .set_body_json(json!({ "success": false, "error": { "message": "busy" } })),
        )
        .up_to_n_times(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1/web/map"))
        .respond_with(ok(json!({ "success": true, "data": { "url": "u", "links": [], "count": 0, "total": 0, "truncated": false } })))
        .mount(&server)
        .await;

    retrying_client(&server)
        .map("https://example.com", None)
        .await
        .unwrap();
    retrying_client(&server)
        .map("https://example.com", None)
        .await
        .unwrap();

    let keys: Vec<String> = server
        .received_requests()
        .await
        .unwrap()
        .iter()
        .map(|r| {
            r.headers
                .get("idempotency-key")
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()
        })
        .collect();
    assert_eq!(keys.len(), 3);
    assert_eq!(keys[0], keys[1]);
    assert_ne!(keys[1], keys[2]);
}