docsrs-cli 0.1.0

One-shot stdin/stdout CLI that fetches crates.io and docs.rs docs for LLM agents without a daemon
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
//! Offline HTTP integration tests using wiremock (no external network).

use std::time::Duration;

use docsrs_cli::config::Config;
use docsrs_cli::crates_io;
use docsrs_cli::docs_rs;
use docsrs_cli::error::ErrorKind;
use docsrs_cli::http::HttpClient;
use docsrs_cli::item_kind::ItemKind;
use docsrs_cli::shutdown::CancelFlag;
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn allow_localhost() {
    // SAFETY: test-only process environment mutation before concurrent work.
    // Integration tests compile the lib without cfg(test); opt-in localhost.
    // The variable is a boolean allowlist flag for wiremock localhost origins.
    unsafe {
        std::env::set_var("DOCSRS_CLI_ALLOW_LOCALHOST", "1");
    }
}

fn test_cfg(base: &str) -> Config {
    let _ = base;
    Config {
        rate_limit_delay_ms: 0,
        max_retries: 2,
        retry_base_ms: 10,
        timeout_secs: 5,
        connect_timeout_secs: 2,
        user_agent: "docsrs-cli/0.1.0 (test@example.com)".into(),
        ..Config::default()
    }
}

#[tokio::test]
async fn search_crates_fixture_meta_and_fallback_description() {
    allow_localhost();
    let server = MockServer::start().await;
    let body = include_str!("fixtures/crates_io/search_serde.json");
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .and(query_param("q", "serde"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(body),
        )
        .mount(&server)
        .await;

    let cfg = test_cfg(server.uri().as_str());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!(
        "{}/api/v1/crates?q=serde&per_page=10&sort=relevance&page=1",
        server.uri()
    ))
    .unwrap();
    let resp = http.get_json(&url).await.unwrap();
    assert!(resp.status.is_success());
    let text = docsrs_cli::http::decode_utf8(&resp.body).unwrap();
    assert!(text.contains("\"exact_match\": true"));
    assert!(text.contains("No description") || text.contains("serde_json"));
}

#[tokio::test]
async fn search_crates_at_end_to_end_with_seek_meta() {
    allow_localhost();
    let server = MockServer::start().await;
    let body = include_str!("fixtures/crates_io/search_seek_meta.json");
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(body),
        )
        .mount(&server)
        .await;

    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = crates_io::planned_url_on_host(&server.uri(), "example", 10, "downloads", 1).unwrap();
    let data = crates_io::search_crates_at(&http, &url, "example", 10, "downloads", 1)
        .await
        .unwrap();
    assert_eq!(data.hits[0].name, "example");
    assert_eq!(
        data.meta.next_page.as_deref(),
        Some("seek=ABC123&per_page=10")
    );
    assert_eq!(data.meta.prev_page.as_deref(), Some("page=1"));
}

#[tokio::test]
async fn retry_on_503_then_success() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(503))
        .up_to_n_times(1)
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(include_str!("fixtures/crates_io/search_serde.json")),
        )
        .mount(&server)
        .await;

    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/api/v1/crates?q=serde", server.uri())).unwrap();
    let resp = http.get_json(&url).await.unwrap();
    assert!(resp.status.is_success());
}

#[tokio::test]
async fn body_cap_returns_network() {
    allow_localhost();
    let server = MockServer::start().await;
    let big = "x".repeat(1024);
    Mock::given(method("GET"))
        .and(path("/big"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string(big),
        )
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_body_bytes = 64;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/big", server.uri())).unwrap();
    let err = http.get_html(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Network);
    assert!(err.message().contains("max_body_bytes"));
}

#[tokio::test]
async fn docs_rs_readme_fixture_via_mock() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/latest/demo/index.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html; charset=utf-8")
                .set_body_string(include_str!("fixtures/docs_rs/readme_docblock.html")),
        )
        .mount(&server)
        .await;

    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/demo/latest/demo/index.html", server.uri())).unwrap();
    let resp = http.get_html(&url).await.unwrap();
    let html = docsrs_cli::http::decode_utf8(&resp.body).unwrap();
    let (md, empty) = docs_rs::extract_readme_markdown_from_html(&html).unwrap();
    assert!(!empty);
    assert!(md.to_lowercase().contains("demo") || md.contains("main"));
    assert!(!md.contains("alert"));
}

#[tokio::test]
async fn all_html_fixture_kinds() {
    let html = include_str!("fixtures/docs_rs/all_html_sample.html");
    let hits = docs_rs::parse_all_html_hits(html, "demo", "1.0.0", "", None, 100).unwrap();
    assert!(
        hits.iter()
            .any(|h| h.kind == "struct" && h.name == "Client")
    );
    assert!(hits.iter().any(|h| h.kind == "attribute"));
    assert!(hits.iter().any(|h| h.kind == "derive"));
    assert!(hits.iter().any(|h| h.kind == "union"));
    assert!(hits.iter().any(|h| h.name == "de::Deserialize"));
    assert!(!hits.iter().any(|h| h.name == "skipme"));
    let limited = docs_rs::parse_all_html_hits(html, "demo", "1.0.0", "", None, 2).unwrap();
    assert_eq!(limited.len(), 2);
    assert_eq!(limited[0].name, "Client");
}

#[tokio::test]
async fn host_not_allowlisted() {
    allow_localhost();
    let cfg = test_cfg("http://example.com");
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse("https://evil.example/api").unwrap();
    let err = http.get_json(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Network);
}

#[tokio::test]
async fn item_kind_function_alias_url() {
    let segs = vec!["get".into()];
    let u = docs_rs::get_item_url(
        "reqwest",
        "latest",
        ItemKind::parse("function").unwrap(),
        &segs,
    )
    .unwrap();
    assert!(u.as_str().contains("/fn.get.html"));
    let _ = Duration::from_millis(1);
}

#[tokio::test]
async fn fetch_readme_at_end_to_end() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/latest/demo/index.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html; charset=utf-8")
                .set_body_string(include_str!("fixtures/docs_rs/readme_docblock.html")),
        )
        .mount(&server)
        .await;

    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::readme_url_on_origin(&server.uri(), "demo", "latest").unwrap();
    let data = docs_rs::fetch_readme_at(&http, "demo", "latest", &url)
        .await
        .unwrap();
    assert_eq!(data.crate_name, "demo");
    assert_eq!(data.version, "latest");
    assert!(!data.empty);
    assert!(!data.truncated);
    assert!(data.markdown.to_lowercase().contains("demo") || data.markdown.contains("main"));
    assert!(!data.markdown.to_ascii_lowercase().contains("alert"));
    assert!(data.source_url.contains("/demo/latest/demo/index.html"));
}

#[tokio::test]
async fn fetch_readme_at_404() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/missing/latest/missing/index.html"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::readme_url_on_origin(&server.uri(), "missing", "latest").unwrap();
    let err = docs_rs::fetch_readme_at(&http, "missing", "latest", &url)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[tokio::test]
async fn fetch_item_at_end_to_end() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/tokio/latest/tokio/runtime/struct.Runtime.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string(include_str!("fixtures/docs_rs/get_item_main.html")),
        )
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let segs = vec!["tokio".into(), "runtime".into(), "Runtime".into()];
    let url =
        docs_rs::get_item_url_on_origin(&server.uri(), "tokio", "latest", ItemKind::Struct, &segs)
            .unwrap();
    let data = docs_rs::fetch_item_at(&http, "tokio", "latest", ItemKind::Struct, &segs, &url)
        .await
        .unwrap();
    assert_eq!(data.item_type, "struct");
    assert_eq!(data.item_path, "tokio::runtime::Runtime");
    assert!(!data.empty);
    assert!(
        data.markdown.contains("Runtime")
            || data.markdown.contains("Tokio")
            || data.markdown.contains("runtime")
    );
    assert!(data.title.contains("struct"));
}

#[tokio::test]
async fn fetch_item_at_404() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let segs = vec!["Missing".into()];
    let url =
        docs_rs::get_item_url_on_origin(&server.uri(), "demo", "1.0.0", ItemKind::Struct, &segs)
            .unwrap();
    let err = docs_rs::fetch_item_at(&http, "demo", "1.0.0", ItemKind::Struct, &segs, &url)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[tokio::test]
async fn search_in_crate_at_end_to_end() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/1.0.0/demo/all.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string(include_str!("fixtures/docs_rs/all_html_sample.html")),
        )
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::all_html_url_on_origin(&server.uri(), "demo", "1.0.0").unwrap();
    let data = docs_rs::search_in_crate_at(
        &http,
        "demo",
        "1.0.0",
        "Client",
        Some(ItemKind::Struct),
        10,
        &url,
    )
    .await
    .unwrap();
    assert_eq!(data.total, 1);
    assert_eq!(data.emitted, 1);
    assert_eq!(data.hits[0].name, "Client");
    assert_eq!(data.hits[0].kind, "struct");
    assert!(!data.truncated);

    let constants = docs_rs::search_in_crate_at(
        &http,
        "demo",
        "1.0.0",
        "",
        Some(ItemKind::Constant),
        10,
        &url,
    )
    .await
    .unwrap();
    assert_eq!(constants.total, 1, "constant.MAX must be indexed");
    assert_eq!(constants.hits[0].name, "MAX");
    assert_eq!(constants.hits[0].kind, "constant");
}

#[tokio::test]
async fn search_in_crate_at_404() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/gone/latest/gone/all.html"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::all_html_url_on_origin(&server.uri(), "gone", "latest").unwrap();
    let err = docs_rs::search_in_crate_at(&http, "gone", "latest", "x", None, 10, &url)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[tokio::test]
async fn retry_on_429_then_success() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
        .up_to_n_times(1)
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(include_str!("fixtures/crates_io/search_serde.json")),
        )
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 2;
    cfg.retry_base_ms = 5;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/api/v1/crates?q=serde", server.uri())).unwrap();
    let resp = http.get_json(&url).await.unwrap();
    assert!(resp.status.is_success());
}

#[tokio::test]
async fn retry_429_exhausted() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "1"))
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 0; // single attempt
    cfg.retry_base_ms = 1;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/api/v1/crates?q=x", server.uri())).unwrap();
    let err = http.get_json(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::RateLimited);
}

#[tokio::test]
async fn disable_retry_kill_switch_no_second_attempt() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(503))
        .expect(1)
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 5;
    cfg.disable_retry = true;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    assert!(!http.retry_policy().enabled);
    let url = url::Url::parse(&format!("{}/api/v1/crates?q=x", server.uri())).unwrap();
    let err = http.get_json(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Unavailable);
}

#[tokio::test]
async fn permanent_404_not_retried() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/missing"))
        .respond_with(ResponseTemplate::new(404).set_body_string("gone"))
        .expect(1)
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 5;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/missing", server.uri())).unwrap();
    let resp = http.get_html(&url).await.unwrap();
    assert_eq!(resp.status.as_u16(), 404);
}

#[tokio::test]
async fn retry_503_with_retry_after_then_success() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(503).insert_header("retry-after", "0"))
        .up_to_n_times(1)
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(include_str!("fixtures/crates_io/search_serde.json")),
        )
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 2;
    cfg.retry_base_ms = 5;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/api/v1/crates?q=serde", server.uri())).unwrap();
    let resp = http.get_json(&url).await.unwrap();
    assert!(resp.status.is_success());
}

#[tokio::test]
async fn cancel_before_request() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_string("{}"))
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let cancel = CancelFlag::new();
    cancel.cancel();
    let http = HttpClient::new(cfg, cancel).unwrap();
    let url = url::Url::parse(&format!("{}/api/v1/crates", server.uri())).unwrap();
    let err = http.get_json(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Terminated);
}

#[tokio::test]
async fn rate_limit_delay_between_hits() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/ping"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string("ok"),
        )
        .expect(2)
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.rate_limit_delay_ms = 30;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/ping", server.uri())).unwrap();
    let t0 = std::time::Instant::now();
    let _ = http.get_html(&url).await.unwrap();
    let _ = http.get_html(&url).await.unwrap();
    assert!(
        t0.elapsed() >= Duration::from_millis(20),
        "expected rate limit delay between hits"
    );
}

#[tokio::test]
async fn rate_limit_cross_process_stamp_with_cache_dir() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/ping"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string("ok"),
        )
        .expect(2)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let mut cfg = test_cfg(&server.uri());
    cfg.rate_limit_delay_ms = 80;
    cfg.cache_dir = Some(dir.path().to_path_buf());
    cfg.no_cache = true; // only use cache_dir for rate-limit lock/stamp

    let http_a = HttpClient::new(cfg.clone(), CancelFlag::new()).unwrap();
    let http_b = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = url::Url::parse(&format!("{}/ping", server.uri())).unwrap();
    let t0 = std::time::Instant::now();
    let _ = http_a.get_html(&url).await.unwrap();
    // Second client shares stamp via exclusive lock + stamp file.
    let _ = http_b.get_html(&url).await.unwrap();
    assert!(
        t0.elapsed() >= Duration::from_millis(60),
        "cross-process stamp should enforce delay, elapsed={:?}",
        t0.elapsed()
    );
}

#[tokio::test]
async fn rate_limit_cancel_during_sleep_propagates() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/ping"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string("ok"),
        )
        .mount(&server)
        .await;

    let mut cfg = test_cfg(&server.uri());
    cfg.rate_limit_delay_ms = 5_000;
    let cancel = CancelFlag::new();
    let http = HttpClient::new(cfg, cancel.clone()).unwrap();
    let url = url::Url::parse(&format!("{}/ping", server.uri())).unwrap();
    // First hit records in-process clock.
    let _ = http.get_html(&url).await.unwrap();
    cancel.cancel();
    let err = http.get_html(&url).await.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Terminated);
}

#[tokio::test]
async fn non_success_status_on_readme_returns_error() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/latest/demo/index.html"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let mut cfg = test_cfg(&server.uri());
    cfg.max_retries = 0;
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::readme_url_on_origin(&server.uri(), "demo", "latest").unwrap();
    let err = docs_rs::fetch_readme_at(&http, "demo", "latest", &url)
        .await
        .unwrap_err();
    assert!(matches!(
        err.kind(),
        ErrorKind::Unavailable | ErrorKind::Network | ErrorKind::Internal
    ));
}

#[tokio::test]
async fn empty_readme_fixture_via_fetch() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/empty/1.0.0/empty/index.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string("<html><body><main id=\"main-content\"></main></body></html>"),
        )
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::readme_url_on_origin(&server.uri(), "empty", "1.0.0").unwrap();
    let data = docs_rs::fetch_readme_at(&http, "empty", "1.0.0", &url)
        .await
        .unwrap();
    assert!(data.empty);
    assert!(data.markdown.is_empty());
}

#[tokio::test]
async fn origin_url_builders_hyphen_crate() {
    let origin = "http://127.0.0.1:9";
    let r = docs_rs::readme_url_on_origin(origin, "async-trait", "latest").unwrap();
    assert!(
        r.as_str()
            .contains("/async-trait/latest/async_trait/index.html")
    );
    let a = docs_rs::all_html_url_on_origin(origin, "async-trait", "1.0.0").unwrap();
    assert!(
        a.as_str()
            .contains("/async-trait/1.0.0/async_trait/all.html")
    );
    let segs = vec!["Parser".into()];
    let g =
        docs_rs::get_item_url_on_origin(origin, "clap", "latest", ItemKind::Trait, &segs).unwrap();
    assert!(g.as_str().contains("/clap/latest/clap/trait.Parser.html"));
}

#[tokio::test]
async fn disk_cache_serves_second_request_without_network() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(include_str!("fixtures/crates_io/search_serde.json")),
        )
        .expect(1)
        .mount(&server)
        .await;

    let cache_dir = tempfile::tempdir().unwrap();
    let mut cfg = test_cfg(&server.uri());
    cfg.cache_dir = Some(cache_dir.path().to_path_buf());
    cfg.cache_ttl_secs = 3600;
    cfg.no_cache = false;

    let url = url::Url::parse(&format!("{}/api/v1/crates?q=serde", server.uri())).unwrap();
    let http1 = HttpClient::new(cfg.clone(), CancelFlag::new()).unwrap();
    let first = http1.get_json(&url).await.unwrap();
    assert!(first.status.is_success());

    // New process-equivalent client: same cache dir, mock allows only 1 request total.
    let http2 = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let second = http2.get_json(&url).await.unwrap();
    assert!(second.status.is_success());
    assert_eq!(first.body, second.body);
}

#[tokio::test]
async fn no_cache_flag_bypasses_disk() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(include_str!("fixtures/crates_io/search_serde.json")),
        )
        .expect(2)
        .mount(&server)
        .await;

    let cache_dir = tempfile::tempdir().unwrap();
    let mut cfg = test_cfg(&server.uri());
    cfg.cache_dir = Some(cache_dir.path().to_path_buf());
    cfg.no_cache = true;

    let url = url::Url::parse(&format!("{}/api/v1/crates?q=serde", server.uri())).unwrap();
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let _ = http.get_json(&url).await.unwrap();
    let _ = http.get_json(&url).await.unwrap();
}

#[tokio::test]
async fn search_in_crate_truncated_true_when_limit_cuts() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/1.0.0/demo/all.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string(include_str!("fixtures/docs_rs/all_html_sample.html")),
        )
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::all_html_url_on_origin(&server.uri(), "demo", "1.0.0").unwrap();
    let data = docs_rs::search_in_crate_at(&http, "demo", "1.0.0", "", None, 2, &url)
        .await
        .unwrap();
    assert!(data.total > 2);
    assert_eq!(data.emitted, 2);
    assert!(data.truncated);
}

#[tokio::test]
async fn search_in_crate_limit_zero_emits_empty_hits() {
    allow_localhost();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/demo/1.0.0/demo/all.html"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/html")
                .set_body_string(include_str!("fixtures/docs_rs/all_html_sample.html")),
        )
        .mount(&server)
        .await;
    let cfg = test_cfg(&server.uri());
    let http = HttpClient::new(cfg, CancelFlag::new()).unwrap();
    let url = docs_rs::all_html_url_on_origin(&server.uri(), "demo", "1.0.0").unwrap();
    let data = docs_rs::search_in_crate_at(&http, "demo", "1.0.0", "", None, 0, &url)
        .await
        .unwrap();
    assert!(data.total > 0);
    assert_eq!(data.emitted, 0);
    assert!(data.hits.is_empty());
    assert!(data.truncated);
}