mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
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
use super::*;

#[test]
fn test_format_response_body_handles_empty_and_truncates() {
    assert_eq!(format_response_body(" \n\t"), "<empty>");

    let body = "a".repeat(4097);
    let formatted = format_response_body(&body);
    assert_eq!(formatted.strip_suffix("\n<truncated>").unwrap().len(), 4096);
    assert!(formatted.ends_with("\n<truncated>"));
}

#[tokio::test(flavor = "current_thread")]
async fn test_retry_rescues_send_failure_with_no_response() {
    // A connection that is accepted and then closed without a response fails
    // with a reqwest "request" error: connecting succeeded, so it is not
    // is_connect(), and no response arrived, so there is no status. HTTP/2
    // REFUSED_STREAM lands in the same class. Before these were classified as
    // transient, such failures exited on the first attempt even with retries
    // enabled.
    let _guard = set_test_http_retries(1);
    let (port, count) = spawn_canned_server(vec!["", ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let reporter = crate::testing::RecordingReport::default();
    let resp =
        crate::resolve_progress::scope(Some(Box::new(reporter.clone())), client.get_async(url))
            .await
            .unwrap();

    let messages = reporter.0.lock().unwrap();
    assert!(
        messages
            .first()
            .unwrap()
            .contains("fetching from 127.0.0.1")
    );
    assert!(
        messages
            .iter()
            .any(|message| message.contains("retrying 127.0.0.1 (attempt 2"))
    );
    assert!(messages.last().unwrap().contains("fetching from 127.0.0.1"));
    assert!(resp.status().is_success());
    // Two connections: the aborted one, then the retry that succeeded.
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_retry_succeeds_after_two_502s() {
    // 2 retries is enough to verify the rescue path (2 failures + 1 success)
    // without paying the third backoff (~12.5s).
    let _guard = set_test_http_retries(2);
    let (port, count) = spawn_canned_server(vec![
        bad_gateway_response(),
        bad_gateway_response(),
        ok_response(),
    ])
    .await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let resp = client.get_async(url).await.unwrap();
    assert!(resp.status().is_success());
    // Should have served 3 connections: two 502s + one 200.
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
}

#[tokio::test(flavor = "current_thread")]
async fn test_prefer_offline_disables_http_retries() {
    let _guard = set_test_prefer_offline(3);
    let (port, count) = spawn_canned_server(vec![bad_gateway_response(), ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_async(url).await.unwrap_err();

    assert!(format!("{err:?}").contains("502"));
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
    assert_eq!(
        crate::network::fetch_remote_versions_timeout(&Settings::get()),
        Duration::from_secs(3)
    );
}

#[test]
fn test_fetch_client_applies_prefer_offline_timeout_at_request_time() {
    let client = Client::new(Duration::from_secs(30), ClientKind::Fetch).unwrap();
    let _guard = set_test_prefer_offline(3);

    assert_eq!(client.request_timeout(), Duration::from_secs(3));
}

/// Every client kind names its traffic, which is also what proves each one
/// reaches `https_downgrade_policy`: `Client::build` applies the policy
/// unconditionally using this, so there is no arm that can lack it.
#[test]
fn test_every_client_kind_has_a_redirect_subject() {
    let subjects = [ClientKind::Http, ClientKind::Fetch].map(ClientKind::redirect_subject);
    assert!(subjects.iter().all(|subject| !subject.is_empty()));
    assert_ne!(subjects[0], subjects[1]);
}

/// The predicate behind `https_downgrade_policy`, which every client uses.
/// The rejection itself cannot be exercised here: it needs a real HTTPS hop
/// to redirect away from, and mockito serves plain HTTP. Trusting a
/// self-signed cert would mean adding a test-only trust bypass to the
/// client, which is a worse trade than the gap it closes.
#[test]
fn test_https_downgrade_policy_rejects_https_to_http() {
    let https = Url::parse("https://example.com/versions").unwrap();
    let other_https = Url::parse("https://cdn.example.com/versions").unwrap();
    let http = Url::parse("http://cdn.example.com/versions").unwrap();

    assert!(is_https_downgrade(std::slice::from_ref(&https), &http));
    assert!(!is_https_downgrade(
        std::slice::from_ref(&https),
        &other_https
    ));
    assert!(!is_https_downgrade(&[http], &other_https));
}

/// Goes through `download_file_checksum_pinned` itself, so it covers the
/// client wiring and the verification. The downgrade redirect it allows
/// cannot be served here for the reason given on the test above.
#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn test_checksum_pinned_download_keeps_match_and_removes_mismatch() {
    let _guard = set_test_http_retries(0);
    let (port, count) =
        spawn_canned_server(vec![full_download_response(), full_download_response()]).await;
    let url = format!("http://127.0.0.1:{port}/artifact");
    let dir = tempfile::tempdir().unwrap();
    let helloworld_sha256 = "936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af";

    let matching = dir.path().join("matching");
    download_file_checksum_pinned(&url, &matching, helloworld_sha256, None)
        .await
        .unwrap();
    assert_eq!(std::fs::read(&matching).unwrap(), b"helloworld");

    let mismatched = dir.path().join("mismatched");
    let _err = download_file_checksum_pinned(&url, &mismatched, &"0".repeat(64), None)
        .await
        .unwrap_err();
    assert!(!mismatched.exists());
    assert_eq!(count.load(Ordering::SeqCst), 2);
}

#[test]
fn test_remote_fetch_command_keeps_full_budget_under_prefer_offline() {
    // Commands whose job is to enumerate remote versions/tags (`mise lock`,
    // `ls-remote`, ...) must honor the configured timeout and retries even
    // when prefer_offline is set.
    // https://github.com/jdx/mise/discussions/11185
    let client = Client::new(Duration::from_secs(30), ClientKind::Fetch).unwrap();
    let _guard = set_test_prefer_offline(3);
    let _remote_fetch_guard = AtomicBoolGuard::set(&crate::env::REMOTE_FETCH_COMMAND, true);

    assert_eq!(client.request_timeout(), Duration::from_secs(30));
    assert_eq!(
        crate::network::fetch_remote_versions_timeout(&Settings::get()),
        crate::network::configured_fetch_remote_versions_timeout(&Settings::get())
    );
    assert_eq!(crate::network::http_retries(&Settings::get()), 3);
}

#[tokio::test(flavor = "current_thread")]
async fn test_reqwest_dns_error_is_not_transient_and_opens_circuit() {
    let _settings_guard = set_test_prefer_offline(3);
    let timeout = Duration::from_secs(3);
    let client = Client {
        reqwest: Ok(Client::_new()
            .no_proxy()
            .dns_resolver(FailingDnsResolver)
            .read_timeout(timeout)
            .connect_timeout(timeout)
            .build()
            .unwrap()),
        manual_redirects: Default::default(),
        undecoded: Default::default(),
        undecoded_manual_redirects: Default::default(),
        timeout,
        read_timeout: Some(timeout),
        downgrade: Downgrade::Refuse,
        kind: ClientKind::Fetch,
    };
    let url: Url = "https://mise-dns-regression.invalid/?token=secret"
        .parse()
        .unwrap();
    let host_key = http_host_key(&url).unwrap();
    let _hosts_guard = UnavailableHostsGuard::new(vec![host_key.clone()]);

    let err = client.get_async(url).await.unwrap_err();

    assert!(is_dns_error(err.as_ref()), "unexpected error: {err:#}");
    assert!(!is_transient(&err));
    assert!(
        UNAVAILABLE_HTTP_HOSTS
            .lock()
            .unwrap()
            .contains_key(&host_key)
    );
    assert!(
        !UNAVAILABLE_HTTP_HOSTS
            .lock()
            .unwrap()
            .get(&host_key)
            .unwrap()
            .contains("token=secret")
    );
}

#[test]
fn test_only_download_size_mismatches_are_transient_eof_errors() {
    let mismatch: Report = DownloadSizeMismatch {
        expected: 10,
        actual: 5,
    }
    .into();
    assert!(is_transient(&mismatch));

    let unrelated: Report =
        std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "local file truncated").into();
    assert!(!is_transient(&unrelated));
}

#[tokio::test(flavor = "current_thread")]
async fn test_circuit_broken_http_origin_falls_back_to_https() {
    let _settings_guard = set_test_prefer_offline(3);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let http_url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let https_url: Url = format!("https://127.0.0.1:{port}/").parse().unwrap();
    let http_origin = http_host_key(&http_url).unwrap();
    let https_origin = http_host_key(&https_url).unwrap();
    let _hosts_guard = UnavailableHostsGuard::new(vec![http_origin.clone(), https_origin]);
    UNAVAILABLE_HTTP_HOSTS
        .lock()
        .unwrap()
        .insert(http_origin, "connection refused".to_string());

    let accepted = Arc::new(AtomicUsize::new(0));
    let accepted_inner = accepted.clone();
    let server = tokio::spawn(async move {
        if let Ok((mut socket, _)) = listener.accept().await {
            accepted_inner.fetch_add(1, Ordering::SeqCst);
            let _ = socket.shutdown().await;
        }
    });

    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_async(http_url).await.unwrap_err();
    server.await.unwrap();

    assert_eq!(accepted.load(Ordering::SeqCst), 1);
    assert!(!is_unavailable_http_host_error(&err));
}

#[test]
fn test_unavailable_host_error_preserves_original_cause() {
    let err: Report = UnavailableHttpHost {
        origin: "https://example.com:443".to_string(),
        cause: "connection refused".to_string(),
    }
    .into();

    assert!(is_unavailable_http_host_error(&err));
    assert!(err.to_string().contains("connection refused"));
}

#[tokio::test(flavor = "current_thread")]
async fn test_circuit_breaker_is_disabled_without_prefer_offline() {
    let _settings_guard = set_test_http_retries(0);
    let (port, count) = spawn_canned_server(vec![ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let host_key = http_host_key(&url).unwrap();
    let _hosts_guard = UnavailableHostsGuard::new(vec![host_key.clone()]);
    UNAVAILABLE_HTTP_HOSTS
        .lock()
        .unwrap()
        .insert(host_key, "connection refused".to_string());

    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let resp = client.get_async(url).await.unwrap();

    assert!(resp.status().is_success());
    assert_eq!(count.load(Ordering::SeqCst), 1);
}

#[test]
fn test_parse_content_range() {
    assert_eq!(
        parse_content_range("bytes 5-9/10"),
        Some(ParsedContentRange::Bytes {
            start: 5,
            end: 9,
            total: 10
        })
    );
    assert_eq!(
        parse_content_range("bytes */10"),
        Some(ParsedContentRange::Unsatisfied { total: 10 })
    );
    assert_eq!(parse_content_range("bytes 5-10/10"), None);
    assert_eq!(parse_content_range("items 5-9/10"), None);
}

#[test]
fn test_response_validator_requires_strong_etag_or_last_modified() {
    let mut headers = HeaderMap::new();
    headers.insert(ETAG, HeaderValue::from_static("W/\"weak\""));
    assert_eq!(response_validator(&headers), None);

    headers.insert(
        LAST_MODIFIED,
        HeaderValue::from_static("Wed, 21 Oct 2015 07:28:00 GMT"),
    );
    assert_eq!(response_validator(&headers), None);

    headers.insert(
        DATE,
        HeaderValue::from_static("Wed, 21 Oct 2015 07:28:59 GMT"),
    );
    assert_eq!(response_validator(&headers), None);

    headers.insert(
        DATE,
        HeaderValue::from_static("Wed, 21 Oct 2015 07:29:00 GMT"),
    );
    assert_eq!(
        response_validator(&headers),
        Some(DownloadValidator::LastModified {
            value: "Wed, 21 Oct 2015 07:28:00 GMT".to_string(),
            response_date: "Wed, 21 Oct 2015 07:29:00 GMT".to_string(),
        })
    );

    headers.insert(ETAG, HeaderValue::from_static("\"strong\""));
    assert_eq!(
        response_validator(&headers),
        Some(DownloadValidator::Etag("\"strong\"".to_string()))
    );
}

#[test]
fn test_cleanup_download_dir_preserves_only_partial_pairs() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("artifact.tar.gz"), b"complete").unwrap();
    std::fs::write(dir.path().join(".artifact.tar.gz.mise-part"), b"partial").unwrap();
    std::fs::write(
        dir.path().join(".artifact.tar.gz.mise-part.json"),
        b"metadata",
    )
    .unwrap();
    std::fs::write(dir.path().join(".orphan.mise-part"), b"orphan").unwrap();
    let expired_partial = dir.path().join(".expired.mise-part");
    let expired_state = dir.path().join(".expired.mise-part.json");
    std::fs::write(&expired_partial, b"expired partial").unwrap();
    std::fs::write(&expired_state, b"expired metadata").unwrap();
    let expired_time = SystemTime::now() - PARTIAL_DOWNLOAD_MAX_AGE - Duration::from_secs(1);
    crate::file::set_times(&expired_partial, None, Some(expired_time)).unwrap();
    crate::file::set_times(&expired_state, None, Some(expired_time)).unwrap();
    std::fs::create_dir(dir.path().join("extracted")).unwrap();

    cleanup_download_dir(dir.path()).unwrap();

    assert!(!dir.path().join("artifact.tar.gz").exists());
    assert!(!dir.path().join("extracted").exists());
    assert!(dir.path().join(".artifact.tar.gz.mise-part").exists());
    assert!(dir.path().join(".artifact.tar.gz.mise-part.json").exists());
    assert!(!dir.path().join(".orphan.mise-part").exists());
    assert!(!expired_partial.exists());
    assert!(!expired_state.exists());
}

#[tokio::test(flavor = "current_thread")]
async fn test_no_retry_on_404() {
    let _guard = set_test_http_retries(3);
    let (port, count) = spawn_canned_server(vec![not_found_response()]).await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_async(url).await.unwrap_err();
    let msg = format!("{err:?}");
    assert!(msg.contains("404"), "expected 404 in error: {msg}");
    // Should not have retried — only one connection.
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn test_retry_exhausted_on_persistent_500() {
    // Use 1 retry so the test doesn't pay the full backoff schedule;
    // the behavior under test (exhaustion → final error) is the same.
    let _guard = set_test_http_retries(1);
    // 2 connections: initial + 1 retry.
    let (port, count) =
        spawn_canned_server(vec![server_error_response(), server_error_response()]).await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_async(url).await.unwrap_err();
    assert!(format!("{err:?}").contains("500"));
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_text_request_can_override_retry_count() {
    let _guard = set_test_http_retries(3);
    let (port, count) = spawn_canned_server(vec![
        bad_gateway_response(),
        bad_gateway_response(),
        ok_response(),
    ])
    .await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client
        .get_text_request(url)
        .retries(1)
        .send()
        .await
        .unwrap_err();
    assert!(format!("{err:?}").contains("502"));
    // Should stop after the initial request plus the single overridden retry.
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_text_request_respects_offline_mode() {
    let _guard = set_test_offline();
    let (port, count) = spawn_canned_server(vec![ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_text_request(url).send().await.unwrap_err();
    assert_eq!(err.to_string(), "offline mode is enabled");
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 0);
}

#[test]
fn test_backoff_strategy_yields_requested_count_beyond_schedule() {
    // Regression: a fixed-length schedule used to silently cap retries at 4.
    // Now extra retries should fall back to the longest delay.
    let delays: Vec<_> = default_backoff_strategy(7).collect();
    assert_eq!(delays.len(), 7);
}

#[tokio::test(flavor = "current_thread")]
async fn test_retries_disabled_fails_immediately() {
    let _guard = set_test_http_retries(0);
    let (port, count) = spawn_canned_server(vec![bad_gateway_response()]).await;
    let url: Url = format!("http://127.0.0.1:{}/", port).parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();
    let err = client.get_async(url).await.unwrap_err();
    assert!(format!("{err:?}").contains("502"));
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn test_429_with_long_retry_after_is_not_retried() {
    // A limiter that says "come back in a minute" will not be moved by our
    // ~15s backoff, and every retry is another request it counts against us.
    let _guard = set_test_http_retries(3);
    let (port, count) =
        spawn_canned_server(vec![too_many_requests_response(60), ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let err = client.get_async(url).await.unwrap_err();
    // Callers key their fallback on the 429 surviving the wrapper.
    assert_eq!(error_code(&err), Some(429));
    assert!(format!("{err:?}").contains("retry-after: 60s"));
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn test_429_with_short_retry_after_is_retried() {
    let _guard = set_test_http_retries(1);
    let (port, count) =
        spawn_canned_server(vec![too_many_requests_response(0), ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let resp = client.get_async(url).await.unwrap();
    assert!(resp.status().is_success());
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_retry_delay_honors_a_longer_retry_after() {
    // Asserted on the chosen delay rather than by sleeping through it.
    let _guard = set_test_http_retries(0);
    let (port, _) = spawn_canned_server(vec![too_many_requests_response(20)]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let err = client.get_async(url).await.unwrap_err();
    assert_eq!(
        retry_delay(Duration::from_secs(1), &err),
        Duration::from_secs(20)
    );
    assert_eq!(
        retry_delay(Duration::from_secs(30), &err),
        Duration::from_secs(30)
    );
    assert_eq!(
        retry_delay(Duration::from_secs(1), &eyre!("no header")),
        Duration::from_secs(1)
    );
}

#[tokio::test(flavor = "current_thread")]
async fn test_429_retry_after_digits_are_not_a_404() {
    let _guard = set_test_http_retries(0);
    let (port, _) = spawn_canned_server(vec![too_many_requests_response(404)]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let err = client.get_async(url).await.unwrap_err();
    assert_eq!(error_code(&err), Some(429));
}

#[tokio::test(flavor = "current_thread")]
async fn test_long_retry_after_survives_added_context() {
    let _guard = set_test_http_retries(3);
    let (port, count) =
        spawn_canned_server(vec![too_many_requests_response(60), ok_response()]).await;
    let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap();
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let err = client
        .get_async(url)
        .await
        .unwrap_err()
        .wrap_err("while listing versions");
    assert!(!is_transient(&err));
    assert_eq!(error_code(&err), Some(429));
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
}

#[test]
fn test_retry_after_ignores_non_429_and_http_dates() {
    let response = |status: u16, value: &str| {
        Response::from(
            http::Response::builder()
                .status(status)
                .header("retry-after", value)
                .body("")
                .unwrap(),
        )
    };
    assert_eq!(
        retry_after(&response(429, "45")),
        Some(Duration::from_secs(45))
    );
    assert_eq!(retry_after(&response(503, "45")), None);
    assert_eq!(
        retry_after(&response(429, "Wed, 21 Oct 2026 07:28:00 GMT")),
        None
    );
}

#[tokio::test(flavor = "current_thread")]
async fn test_json_deserialization_failure_is_not_transient() {
    // reqwest reports body-read failures (an HTTP/2 stream reset mid-download)
    // and deserialization failures as `Decode`. Only the former is retryable.
    let (port, _) = spawn_canned_server(vec![ok_response()]).await;
    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://127.0.0.1:{port}/"))
        .send()
        .await
        .unwrap();
    let err = resp.json::<serde_json::Value>().await.unwrap_err();
    assert!(err.is_decode());
    assert!(!is_transient(&Report::new(err)));
}

fn json_ok_response() -> &'static str {
    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}"
}

#[tokio::test(flavor = "current_thread")]
async fn test_get_text_retries_a_body_dropped_mid_stream() {
    // The headers arrive and the connection closes before the declared length,
    // so the request resolves and the failure comes from reading the body.
    let _guard = set_test_http_retries(1);
    let (port, count) =
        spawn_canned_server(vec![truncated_download_response(), ok_response()]).await;
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let text = client
        .get_text_request(format!("http://127.0.0.1:{port}/"))
        .send()
        .await
        .unwrap();

    assert_eq!(text, "OK");
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_json_retries_a_body_dropped_mid_stream() {
    let _guard = set_test_http_retries(1);
    let (port, count) =
        spawn_canned_server(vec![truncated_download_response(), json_ok_response()]).await;
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let json: serde_json::Value = client
        .json(format!("http://127.0.0.1:{port}/"))
        .await
        .unwrap();

    assert_eq!(json["ok"], true);
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_get_bytes_retries_a_body_dropped_mid_stream() {
    let _guard = set_test_http_retries(1);
    let (port, count) =
        spawn_canned_server(vec![truncated_download_response(), ok_response()]).await;
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let bytes = client
        .get_bytes(format!("http://127.0.0.1:{port}/"))
        .await
        .unwrap();

    assert_eq!(bytes.as_ref(), b"OK");
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_text_request_allow_html_returns_the_page() {
    const HTML: &str =
        "HTTP/1.1 200 OK\r\nContent-Length: 15\r\nConnection: close\r\n\r\n<!DOCTYPE html>";
    let _guard = set_test_http_retries(0);
    let client = Client::new(Duration::from_secs(2), ClientKind::Http).unwrap();

    let (port, _) = spawn_canned_server(vec![HTML]).await;
    let text = client
        .get_text_request(format!("http://127.0.0.1:{port}/"))
        .allow_html()
        .send()
        .await
        .unwrap();
    assert_eq!(text, "<!DOCTYPE html>");

    // Without it the page is still rejected; an http URL is retried as https first.
    // That retry sends a TLS hello to this plain-HTTP port, which the canned server
    // would sit on waiting for request headers until the client timed out, so
    // answer the first connection and drop the second.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let (mut sock, _) = listener.accept().await.unwrap();
        let _ = sock.read(&mut [0u8; 4096]).await;
        let _ = sock.write_all(HTML.as_bytes()).await;
        drop(sock);
        let _ = listener.accept().await;
    });
    assert!(
        client
            .get_text_request(format!("http://127.0.0.1:{port}/"))
            .send()
            .await
            .is_err()
    );
}