monovm-whois-rust 1.0.0

Domain WHOIS and RDAP lookups with availability detection, structured record parsing, referral chasing, caching and rate limiting.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! The synchronous [`WhoisClient`] and its builder.

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

use crate::cache::{MemoryCache, NullCache, ResponseCache};
use crate::client::lookup::{Explanation, Lookup};
use crate::client::plan::{self, Plan, Preference, ReferralPolicy};
use crate::client::Parts;
use crate::detect::{DetectionEngine, Evidence};
use crate::domain::{Availability, DomainName, Tld};
use crate::error::{Error, Result};
use crate::registry::{Endpoint, RegistryProvider, WhoisEndpoint};
use crate::transport::{
    CachingTransport, RawResponse, RetryPolicy, RetryTransport, Router, ThrottlePolicy,
    ThrottleTransport, Transport, TransportConfig, Whois43Transport,
};

#[cfg(feature = "parser")]
use crate::parser::{CompositeParser, WhoisRecord};

/// Looks domains up, synchronously.
///
/// Cheap to clone and safe to share: the collaborators are behind `Arc`, so one
/// client can serve a whole thread pool and they will share its cache and its rate
/// limiter — which is the point, since a per-thread limiter does not limit anything.
#[derive(Debug, Clone)]
pub struct WhoisClient {
    parts: Parts,
    transport: Arc<dyn Transport>,
}

impl WhoisClient {
    /// A client with the default configuration.
    ///
    /// The bundled registry data under IANA's RDAP snapshot, port 43 preferred with
    /// RDAP as a fallback, three attempts per endpoint, one second between queries
    /// to the same host, one referral hop, and no caching.
    ///
    /// # Errors
    ///
    /// Only if the HTTP client cannot be constructed, which means a broken TLS
    /// backend rather than anything about the query.
    pub fn new() -> Result<Self> {
        WhoisClient::builder().build()
    }

    /// Start configuring a client.
    pub fn builder() -> WhoisClientBuilder {
        WhoisClientBuilder::new()
    }

    /// Look a domain up.
    ///
    /// Accepts anything [`DomainName::parse`] does — a bare name, a URL, mixed case,
    /// an internationalised name in either spelling.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidDomain`] for input that is not a domain,
    /// [`Error::UnsupportedTld`] when no registry serves the suffix, and
    /// [`Error::Refused`] or [`Error::Inconclusive`] when the servers were reached
    /// but gave no usable answer. An unanswered query is never reported as
    /// availability.
    pub fn lookup(&self, domain: &str) -> Result<Lookup> {
        self.lookup_name(&DomainName::parse(domain)?)
    }

    /// Look an already-validated name up.
    pub fn lookup_name(&self, name: &DomainName) -> Result<Lookup> {
        let resolution = self.parts.registry.resolve(name)?;
        let plan = Plan::build(resolution, self.parts.preference)?;

        let (verdict, mut responses) = self.first_usable_answer(&plan)?;

        // A referral only has something to add when there is a registration to
        // describe. Chasing one for a free domain spends a round trip to be told
        // again that nothing is there.
        if verdict.availability.is_registered() {
            self.follow_referrals(&plan, &mut responses);
        }

        #[cfg(feature = "parser")]
        let record = self
            .parts
            .parser
            .parse_all(&responses)
            .ok()
            .filter(|record| !record.is_empty());

        Ok(Lookup {
            queried: plan.resolution.queried.clone(),
            domain: plan.resolution.registrable.clone(),
            tld: plan.resolution.tld.clone(),
            verdict,
            responses,
            #[cfg(feature = "parser")]
            record,
        })
    }

    /// Just the verdict.
    pub fn availability(&self, domain: &str) -> Result<Availability> {
        Ok(self.lookup(domain)?.availability())
    }

    /// Whether the domain is free to register at the ordinary price.
    ///
    /// A premium or reserved name answers `false`, and a query that could not be
    /// answered is an error rather than `false` — the caller decides what an unknown
    /// means for them.
    pub fn is_available(&self, domain: &str) -> Result<bool> {
        Ok(self.lookup(domain)?.is_available())
    }

    /// Look up and report what every detection rule made of the response.
    ///
    /// The tool for a verdict that looks wrong.
    pub fn explain(&self, domain: &str) -> Result<Explanation> {
        let lookup = self.lookup(domain)?;

        let registry = self.parts.registry.get(&lookup.tld);
        let report = match lookup.primary_response() {
            Some(response) => {
                let evidence = Evidence::from_response(response, &lookup.tld, registry.as_deref());
                self.parts.engine.report(&evidence)
            }
            None => {
                let evidence = Evidence::new(
                    "",
                    crate::transport::ResponseKind::WhoisText,
                    &lookup.tld,
                    registry.as_deref(),
                );
                self.parts.engine.report(&evidence)
            }
        };

        Ok(Explanation { lookup, report })
    }

    /// The parsed registration record.
    ///
    /// # Errors
    ///
    /// As [`lookup`](WhoisClient::lookup), plus [`Error::Inconclusive`] when the domain
    /// is not registered — there is no registration to describe for a free name.
    ///
    /// The decision is made on the verdict, not on whether anything parsed. Some
    /// registries name the domain in their "not registered" answer — DENIC replies
    /// `Domain: …` / `Status: free` — so a non-empty parse is not evidence of a
    /// registration, and treating it as one would return a record consisting of the
    /// name that was asked about.
    #[cfg(feature = "parser")]
    pub fn record(&self, domain: &str) -> Result<WhoisRecord> {
        let lookup = self.lookup(domain)?;
        let consulted = || {
            lookup
                .consulted()
                .iter()
                .map(Endpoint::address)
                .collect::<Vec<_>>()
                .join(", ")
        };

        if !lookup.availability().is_registered() {
            return Err(Error::Inconclusive {
                domain: lookup.domain.as_ascii().to_string(),
                consulted: consulted(),
                detail: format!(
                    "no registration record: the domain is {}",
                    lookup.availability()
                ),
            });
        }

        lookup.record.clone().ok_or_else(|| Error::Inconclusive {
            domain: lookup.domain.as_ascii().to_string(),
            consulted: consulted(),
            detail: "the domain is registered but no field of its record could be parsed"
                .to_string(),
        })
    }

    /// The registry provider in use.
    pub fn registry(&self) -> &Arc<dyn RegistryProvider> {
        &self.parts.registry
    }

    /// The detection engine in use.
    pub fn engine(&self) -> &Arc<DetectionEngine> {
        &self.parts.engine
    }

    /// A description of the transport stack, e.g. `cached(retry(throttle(router(…))))`.
    pub fn transport_name(&self) -> String {
        self.transport.name()
    }

    /// Every suffix this client can look up.
    pub fn supported_tlds(&self) -> Vec<Tld> {
        self.parts.registry.tlds()
    }

    /// Whether a name's suffix is served.
    pub fn can_lookup(&self, domain: &str) -> bool {
        DomainName::parse(domain)
            .map(|name| self.parts.registry.can_resolve(&name))
            .unwrap_or(false)
    }

    /// Try each planned endpoint until one gives an answer.
    ///
    /// A response that cannot be interpreted counts as an endpoint failure, not a
    /// verdict: a rate-limited port 43 service should fall through to the registry's
    /// RDAP endpoint rather than ending the lookup.
    fn first_usable_answer(
        &self,
        plan: &Plan,
    ) -> Result<(crate::detect::Verdict, Vec<RawResponse>)> {
        let mut failures: Vec<(Endpoint, Error)> = Vec::new();

        for endpoint in &plan.attempts {
            let query = plan.query(endpoint);

            let response = match self.transport.fetch(&query) {
                Ok(response) => response,
                Err(error) => {
                    if error.is_endpoint_failure() {
                        failures.push((endpoint.clone(), error));
                        continue;
                    }
                    return Err(error);
                }
            };

            match plan::interpret(&self.parts.engine, &response, &plan.resolution) {
                Ok(verdict) => return Ok((verdict, vec![response])),
                Err(error) => failures.push((endpoint.clone(), error)),
            }
        }

        Err(plan::combined_failure(
            plan.resolution.registrable.as_ascii(),
            failures,
        ))
    }

    /// Ask the registrar's server too, while the policy allows it.
    ///
    /// Failures are swallowed: the verdict is already established, and a registrar
    /// whose server is down should cost the extra contact details rather than the
    /// whole lookup.
    fn follow_referrals(&self, plan: &Plan, responses: &mut Vec<RawResponse>) {
        let mut visited: Vec<WhoisEndpoint> = responses
            .iter()
            .filter_map(|response| match response.endpoint() {
                Endpoint::Whois(endpoint) => Some(endpoint.clone()),
                Endpoint::Rdap(_) => None,
            })
            .collect();

        loop {
            let Some(last) = responses.last() else { return };
            let Some(next) = plan::next_referral(
                last,
                &plan.resolution.registry,
                self.parts.referrals,
                &visited,
            ) else {
                return;
            };

            let endpoint = Endpoint::Whois(next.clone());
            let query = plan.query(&endpoint);

            match self.transport.fetch(&query) {
                Ok(response) => {
                    visited.push(next);
                    responses.push(response);
                }
                Err(_) => return,
            }
        }
    }
}

/// Assembles a [`WhoisClient`].
///
/// The defaults are the ones this crate recommends; every one of them can be
/// replaced, including whole collaborators. Supplying a
/// [`transport`](WhoisClientBuilder::transport) bypasses the retry, throttle and
/// cache settings entirely — at that point the stack is the caller's to compose.
#[derive(Debug, Default)]
pub struct WhoisClientBuilder {
    registry: Option<Arc<dyn RegistryProvider>>,
    engine: Option<Arc<DetectionEngine>>,
    #[cfg(feature = "parser")]
    parser: Option<Arc<CompositeParser>>,
    transport: Option<Arc<dyn Transport>>,
    cache: Option<Arc<dyn ResponseCache>>,
    config: TransportConfig,
    retry: RetryPolicy,
    throttle: ThrottlePolicy,
    preference: Preference,
    referrals: ReferralPolicy,
}

impl WhoisClientBuilder {
    /// A builder holding the defaults.
    pub fn new() -> Self {
        WhoisClientBuilder {
            registry: None,
            engine: None,
            #[cfg(feature = "parser")]
            parser: None,
            transport: None,
            cache: None,
            config: TransportConfig::default(),
            retry: RetryPolicy::default(),
            throttle: ThrottlePolicy::default(),
            preference: Preference::default(),
            referrals: ReferralPolicy::default(),
        }
    }

    /// Use a different source of registry definitions.
    pub fn registry(mut self, registry: impl RegistryProvider + 'static) -> Self {
        self.registry = Some(Arc::new(registry));
        self
    }

    /// Use an already-shared registry provider.
    pub fn shared_registry(mut self, registry: Arc<dyn RegistryProvider>) -> Self {
        self.registry = Some(registry);
        self
    }

    /// Use a different detection engine.
    pub fn engine(mut self, engine: DetectionEngine) -> Self {
        self.engine = Some(Arc::new(engine));
        self
    }

    /// Use a different record parser.
    #[cfg(feature = "parser")]
    pub fn parser(mut self, parser: CompositeParser) -> Self {
        self.parser = Some(Arc::new(parser));
        self
    }

    /// Supply the whole transport stack.
    ///
    /// Overrides [`timeouts`](WhoisClientBuilder::timeouts),
    /// [`retry`](WhoisClientBuilder::retry), the throttle settings and the cache:
    /// those exist to build the default stack, and a caller who brings their own has
    /// already made those decisions.
    pub fn transport(mut self, transport: impl Transport + 'static) -> Self {
        self.transport = Some(Arc::new(transport));
        self
    }

    /// Supply an already-shared transport stack.
    pub fn shared_transport(mut self, transport: Arc<dyn Transport>) -> Self {
        self.transport = Some(transport);
        self
    }

    /// Set the connect and read timeouts.
    pub fn timeouts(mut self, config: TransportConfig) -> Self {
        self.config = config;
        self
    }

    /// Set the connect timeout.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.config.connect_timeout = timeout;
        self
    }

    /// Set the read timeout.
    pub fn read_timeout(mut self, timeout: Duration) -> Self {
        self.config.read_timeout = timeout;
        self
    }

    /// Set the retry policy.
    pub fn retry(mut self, policy: RetryPolicy) -> Self {
        self.retry = policy;
        self
    }

    /// Set the rate-limiting policy.
    pub fn throttle(mut self, policy: ThrottlePolicy) -> Self {
        self.throttle = policy;
        self
    }

    /// Set a minimum gap between queries to the same host.
    pub fn throttle_per_host(mut self, gap: Duration) -> Self {
        self.throttle = ThrottlePolicy::per_host(gap);
        self
    }

    /// Cache responses in memory for `ttl`.
    pub fn memory_cache(mut self, ttl: Duration) -> Self {
        self.cache = Some(Arc::new(MemoryCache::with_ttl(ttl)));
        self
    }

    /// Cache responses somewhere else.
    pub fn cache(mut self, cache: impl ResponseCache + 'static) -> Self {
        self.cache = Some(Arc::new(cache));
        self
    }

    /// Use an already-shared cache.
    ///
    /// The way to share one cache across several clients.
    pub fn shared_cache(mut self, cache: Arc<dyn ResponseCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Choose which protocol to try first.
    pub fn prefer(mut self, preference: Preference) -> Self {
        self.preference = preference;
        self
    }

    /// Set how far to chase referrals.
    pub fn referrals(mut self, policy: ReferralPolicy) -> Self {
        self.referrals = policy;
        self
    }

    /// Build the client.
    ///
    /// # Errors
    ///
    /// [`Error::Definitions`] if the HTTP client for RDAP cannot be constructed.
    pub fn build(self) -> Result<WhoisClient> {
        let transport = match &self.transport {
            Some(transport) => Arc::clone(transport),
            None => self.default_transport()?,
        };

        let parts = Parts::new(self.registry, self.engine, self.preference, self.referrals);
        #[cfg(feature = "parser")]
        let parts = parts.with_parser(self.parser);

        Ok(WhoisClient { parts, transport })
    }

    /// The recommended stack, innermost first.
    ///
    /// Ordering is deliberate. Throttling sits inside retrying so that a retry is
    /// paced like any other attempt; caching sits outside both so a repeated
    /// question is answered without waiting for a rate limiter it does not need.
    fn default_transport(&self) -> Result<Arc<dyn Transport>> {
        #[cfg(feature = "rdap")]
        let router = Router::new()
            .with(Whois43Transport::with_config(self.config))
            .with(crate::transport::RdapTransport::with_config(self.config)?);

        #[cfg(not(feature = "rdap"))]
        let router = Router::new().with(Whois43Transport::with_config(self.config));

        let throttled = ThrottleTransport::new(router, self.throttle.clone());
        let retried = RetryTransport::new(throttled, self.retry);

        Ok(match &self.cache {
            Some(cache) => Arc::new(CachingTransport::new(retried, Arc::clone(cache))),
            None => Arc::new(CachingTransport::new(retried, NullCache)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::JsonRegistry;
    use crate::transport::{MockTransport, Scripted};

    /// A registry with one thin `.test` suffix, so referral chasing is exercised.
    fn registry() -> JsonRegistry {
        JsonRegistry::from_json(
            r#"{"registries":[
                {"tlds":["test"],"whois":"registry.test","available":["No match for"],"thin":true},
                {"tlds":["thick"],"whois":"registry.thick","available":["No match for"]},
                {"tlds":["both"],"whois":"registry.both","rdap":["https://rdap.both/"]}
            ]}"#,
            "test",
        )
        .unwrap()
    }

    fn client(transport: MockTransport) -> WhoisClient {
        WhoisClient::builder()
            .registry(registry())
            .transport(transport)
            .build()
            .unwrap()
    }

    const REGISTERED: &str = "\
Domain Name: EXAMPLE.TEST
Registrar: Example Registrar, LLC
Registrar WHOIS Server: registrar.test
Domain Status: clientTransferProhibited
";

    #[test]
    fn an_available_domain_is_reported_available() {
        let client = client(MockTransport::answering("No match for \"NOTHERE.TEST\""));
        let lookup = client.lookup("nothere.test").unwrap();

        assert_eq!(lookup.availability(), Availability::Available);
        assert!(lookup.is_available());
        assert_eq!(lookup.verdict.rule, "registry-marker");
    }

    #[test]
    fn a_registered_domain_is_reported_registered() {
        let client = client(MockTransport::routed([
            ("registry.test".to_string(), REGISTERED.to_string()),
            (
                "registrar.test".to_string(),
                "Registrant Name: Ada\n".to_string(),
            ),
        ]));

        let lookup = client.lookup("example.test").unwrap();
        assert!(lookup.is_registered());
    }

    #[test]
    fn a_thin_registrys_referral_is_followed() {
        let transport = MockTransport::routed([
            ("registry.test".to_string(), REGISTERED.to_string()),
            (
                "registrar.test".to_string(),
                "Registrant Name: Ada Lovelace\nRegistrant Country: GB\n".to_string(),
            ),
        ]);
        let client = client(transport.clone());

        let lookup = client.lookup("example.test").unwrap();

        assert!(lookup.followed_referral());
        assert_eq!(transport.contacted(), ["registry.test", "registrar.test"]);

        #[cfg(feature = "parser")]
        {
            let record = lookup.record.as_ref().unwrap();
            assert_eq!(record.registrar.as_deref(), Some("Example Registrar, LLC"));
            assert_eq!(
                record.registrant.as_ref().unwrap().name.as_deref(),
                Some("Ada Lovelace"),
                "the referral's contacts should be merged in"
            );
        }
    }

    #[test]
    fn a_thick_registrys_referral_is_left_alone() {
        let transport = MockTransport::routed([(
            "registry.thick".to_string(),
            REGISTERED.replace("EXAMPLE.TEST", "EXAMPLE.THICK"),
        )]);
        let client = client(transport.clone());

        client.lookup("example.thick").unwrap();
        assert_eq!(
            transport.contacted(),
            ["registry.thick"],
            "no referral expected"
        );
    }

    #[test]
    fn no_referral_is_chased_for_a_free_name() {
        let transport = MockTransport::answering("No match for \"NOTHERE.TEST\"");
        let client = client(transport.clone());

        client.lookup("nothere.test").unwrap();
        assert_eq!(
            transport.call_count(),
            1,
            "a free name has no record to fetch"
        );
    }

    #[test]
    fn a_failed_referral_costs_only_the_extra_detail() {
        let transport =
            MockTransport::routed([("registry.test".to_string(), REGISTERED.to_string())]);
        let client = client(transport);

        // `registrar.test` has no route, so fetching it fails; the verdict stands.
        let lookup = client.lookup("example.test").unwrap();
        assert!(lookup.is_registered());
        assert!(!lookup.followed_referral());
    }

    #[test]
    fn a_refused_endpoint_falls_through_to_the_next() {
        // Port 43 is rate limited; RDAP answers.
        let transport = MockTransport::routed([
            (
                "registry.both".to_string(),
                "%% queries limit exceeded".to_string(),
            ),
            (
                "https://rdap.both/".to_string(),
                r#"{"errorCode":404,"title":"Not Found"}"#.to_string(),
            ),
        ]);
        let client = client(transport.clone());

        let lookup = client.lookup("nothere.both").unwrap();
        assert_eq!(lookup.availability(), Availability::Available);
        assert_eq!(lookup.verdict.rule, "rdap");
        assert_eq!(transport.contacted().len(), 2);
    }

    #[test]
    fn when_every_endpoint_fails_the_error_names_them_all() {
        let transport = MockTransport::new(vec![
            Scripted::Fail(Error::Timeout {
                server: "registry.both".into(),
                elapsed: Duration::ZERO,
            }),
            Scripted::Fail(Error::Http {
                url: "https://rdap.both/".into(),
                status: 500,
            }),
        ]);
        let client = client(transport);

        match client.lookup("example.both").unwrap_err() {
            Error::Inconclusive { consulted, .. } => {
                assert!(consulted.contains("registry.both"), "{consulted}");
                assert!(consulted.contains("rdap.both"), "{consulted}");
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn an_unsupported_suffix_is_rejected_before_any_query() {
        let transport = MockTransport::answering("should not be reached");
        let client = client(transport.clone());

        assert!(matches!(
            client.lookup("example.unknown").unwrap_err(),
            Error::UnsupportedTld { .. }
        ));
        assert_eq!(transport.call_count(), 0);
    }

    #[test]
    fn invalid_input_is_rejected_before_any_query() {
        let transport = MockTransport::answering("should not be reached");
        let client = client(transport.clone());

        for input in ["", "localhost", "192.0.2.1", "-bad.test"] {
            assert!(
                matches!(
                    client.lookup(input).unwrap_err(),
                    Error::InvalidDomain { .. }
                ),
                "accepted {input:?}"
            );
        }
        assert_eq!(transport.call_count(), 0);
    }

    #[test]
    fn a_subdomain_is_trimmed_to_the_registrable_name() {
        let transport = MockTransport::answering("No match for \"EXAMPLE.TEST\"");
        let client = client(transport.clone());

        let lookup = client.lookup("www.mail.example.test").unwrap();
        assert_eq!(lookup.queried.as_ascii(), "www.mail.example.test");
        assert_eq!(lookup.domain.as_ascii(), "example.test");
        assert_eq!(transport.wire_names(), ["example.test"]);
    }

    #[test]
    fn urls_are_accepted_as_input() {
        let transport = MockTransport::answering("No match for \"EXAMPLE.TEST\"");
        let client = client(transport.clone());

        client.lookup("HTTPS://Example.TEST:443/path?q=1").unwrap();
        assert_eq!(transport.wire_names(), ["example.test"]);
    }

    #[test]
    fn preference_can_exclude_a_protocol() {
        let transport = MockTransport::answering(r#"{"errorCode":404}"#);
        let client = WhoisClient::builder()
            .registry(registry())
            .transport(transport.clone())
            .prefer(Preference::RdapOnly)
            .build()
            .unwrap();

        client.lookup("nothere.both").unwrap();
        assert_eq!(transport.contacted(), ["https://rdap.both/"]);

        // And a suffix with no RDAP endpoint then has nowhere to go.
        assert!(matches!(
            client.lookup("nothere.test").unwrap_err(),
            Error::NoEndpoint { .. }
        ));
    }

    #[test]
    fn explain_reports_every_rules_opinion() {
        let client = client(MockTransport::answering(REGISTERED));
        let explanation = client.explain("example.test").unwrap();

        assert_eq!(explanation.report.judgements.len(), 9);
        assert!(explanation.report.outcome.is_ok());
        assert!(explanation.to_string().contains("example.test"));
    }

    #[test]
    fn availability_helpers_agree_with_the_lookup() {
        let client = client(MockTransport::answering("No match for \"X.TEST\""));

        assert_eq!(
            client.availability("x.test").unwrap(),
            Availability::Available
        );
        assert!(client.is_available("x.test").unwrap());
    }

    #[test]
    fn can_lookup_reflects_the_registry() {
        let client = client(MockTransport::answering("x"));

        assert!(client.can_lookup("example.test"));
        assert!(!client.can_lookup("example.unknown"));
        assert!(!client.can_lookup("not a domain"));
        assert_eq!(client.supported_tlds().len(), 3);
    }

    #[cfg(feature = "parser")]
    #[test]
    fn record_returns_the_parsed_registration() {
        let client = client(MockTransport::routed([(
            "registry.test".to_string(),
            REGISTERED.to_string(),
        )]));

        let record = client.record("example.test").unwrap();
        assert_eq!(record.registrar.as_deref(), Some("Example Registrar, LLC"));
        assert!(record.is_transfer_locked());
    }

    #[cfg(feature = "parser")]
    #[test]
    fn record_of_a_free_name_is_an_error_not_an_empty_struct() {
        let client = client(MockTransport::answering("No match for \"NOTHERE.TEST\""));

        match client.record("nothere.test").unwrap_err() {
            Error::Inconclusive { detail, .. } => assert!(detail.contains("available"), "{detail}"),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn the_default_stack_is_layered_as_documented() {
        let client = WhoisClient::new().unwrap();
        let name = client.transport_name();

        assert!(name.starts_with("cached("), "{name}");
        assert!(name.contains("retry("), "{name}");
        assert!(name.contains("throttle("), "{name}");
        assert!(name.contains("whois43"), "{name}");
    }

    #[test]
    fn a_client_is_cheap_to_clone_and_shares_its_transport() {
        let transport = MockTransport::answering("No match for \"X.TEST\"");
        let client = client(transport.clone());
        let clone = client.clone();

        client.lookup("a.test").unwrap();
        clone.lookup("b.test").unwrap();
        assert_eq!(transport.call_count(), 2, "clones must share one transport");
    }

    #[test]
    fn a_client_is_shareable_across_threads() {
        let transport = MockTransport::answering("No match for \"X.TEST\"");
        let client = Arc::new(client(transport.clone()));

        let handles: Vec<_> = (0..4)
            .map(|index| {
                let client = Arc::clone(&client);
                std::thread::spawn(move || client.lookup(&format!("d{index}.test")).is_ok())
            })
            .collect();

        for handle in handles {
            assert!(handle.join().unwrap());
        }
        assert_eq!(transport.call_count(), 4);
    }
}