domain-check-lib 1.0.2

A fast, robust library for checking domain availability using RDAP and WHOIS protocols
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
//! Core data types for domain availability checking.
//!
//! This module defines all the main data structures used throughout the library,
//! including domain results, configuration options, and output formatting.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Result of a domain availability check.
///
/// Contains all information about a domain's availability status,
/// registration details, and metadata about the check itself.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainResult {
    /// The domain name that was checked (e.g., "example.com")
    pub domain: String,

    /// Whether the domain is available for registration.
    /// - `Some(true)`: Domain is available
    /// - `Some(false)`: Domain is taken/registered  
    /// - `None`: Status could not be determined
    pub available: Option<bool>,

    /// Detailed registration information (only available for taken domains)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<DomainInfo>,

    /// How long the domain check took to complete
    #[serde(skip_serializing_if = "Option::is_none")]
    pub check_duration: Option<Duration>,

    /// Which method was used to check the domain
    pub method_used: CheckMethod,

    /// Any error message if the check failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
}

/// Detailed information about a registered domain.
///
/// This information is typically extracted from RDAP responses
/// and provides insights into the domain's registration details.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DomainInfo {
    /// The registrar that manages this domain
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registrar: Option<String>,

    /// When the domain was first registered
    #[serde(skip_serializing_if = "Option::is_none")]
    pub creation_date: Option<String>,

    /// When the domain registration expires
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration_date: Option<String>,

    /// Domain status codes (e.g., "clientTransferProhibited")
    pub status: Vec<String>,

    /// Last update date of the domain record
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_date: Option<String>,

    /// Nameservers associated with the domain
    pub nameservers: Vec<String>,
}

/// Configuration options for domain checking operations.
///
/// This struct allows fine-tuning of the domain checking behavior,
/// including performance, timeout, and protocol preferences.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckConfig {
    /// Maximum number of concurrent domain checks
    /// Default: 10, Range: 1-100
    pub concurrency: usize,

    /// Timeout for each individual domain check
    /// Default: 5 seconds
    #[serde(skip)] // Don't serialize Duration directly
    pub timeout: Duration,

    /// Whether to automatically fall back to WHOIS when RDAP fails
    /// Default: true
    pub enable_whois_fallback: bool,

    /// Whether to use IANA bootstrap registry for unknown TLDs
    /// Default: false (uses built-in registry only)
    pub enable_bootstrap: bool,

    /// Whether to extract detailed domain information for taken domains
    /// Default: false (just availability status)
    pub detailed_info: bool,

    /// List of TLDs to check for base domain names
    /// If None, defaults to ["com"]
    pub tlds: Option<Vec<String>>,

    /// Custom timeout for RDAP requests (separate from overall timeout)
    /// Default: 3 seconds
    #[serde(skip)] // Don't serialize Duration directly
    pub rdap_timeout: Duration,

    /// Custom timeout for WHOIS requests
    /// Default: 5 seconds  
    #[serde(skip)] // Don't serialize Duration directly
    pub whois_timeout: Duration,

    /// Custom user-defined TLD presets from config files
    /// Default: empty
    #[serde(skip)] // Handled separately in config merging
    pub custom_presets: HashMap<String, Vec<String>>,
}

/// Method used to check domain availability.
///
/// This helps users understand which protocol was used
/// and can be useful for debugging or performance analysis.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CheckMethod {
    /// Domain checked via RDAP protocol
    #[serde(rename = "rdap")]
    Rdap,

    /// Domain checked via WHOIS protocol
    #[serde(rename = "whois")]
    Whois,

    /// RDAP endpoint discovered via IANA bootstrap registry
    #[serde(rename = "bootstrap")]
    Bootstrap,

    /// Check failed or method unknown
    #[serde(rename = "unknown")]
    Unknown,
}

/// Output mode for displaying results.
///
/// This controls how and when results are presented to the user,
/// affecting both performance perception and data formatting.
#[derive(Debug, Clone, PartialEq)]
pub enum OutputMode {
    /// Stream results as they become available (good for interactive use)
    Streaming,

    /// Collect all results before displaying (good for formatting/sorting)
    Collected,

    /// Automatically choose based on context (terminal vs pipe, etc.)
    Auto,
}

impl Default for CheckConfig {
    /// Create a sensible default configuration.
    ///
    /// These defaults are chosen to work well for most use cases
    /// while being conservative about resource usage.
    fn default() -> Self {
        Self {
            concurrency: 20,
            timeout: Duration::from_secs(5),
            enable_whois_fallback: true,
            enable_bootstrap: true,
            detailed_info: false,
            tlds: None, // Will default to ["com"] when needed
            rdap_timeout: Duration::from_secs(3),
            whois_timeout: Duration::from_secs(5),
            custom_presets: HashMap::new(),
        }
    }
}

impl CheckConfig {
    /// Create a new configuration with custom concurrency.
    ///
    /// Automatically caps concurrency at 100 to prevent resource exhaustion.
    pub fn with_concurrency(mut self, concurrency: usize) -> Self {
        self.concurrency = concurrency.clamp(1, 100);
        self
    }

    /// Set custom timeout for domain checks.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Enable or disable WHOIS fallback.
    pub fn with_whois_fallback(mut self, enabled: bool) -> Self {
        self.enable_whois_fallback = enabled;
        self
    }

    /// Enable or disable IANA bootstrap registry.
    pub fn with_bootstrap(mut self, enabled: bool) -> Self {
        self.enable_bootstrap = enabled;
        self
    }

    /// Enable detailed domain information extraction.
    pub fn with_detailed_info(mut self, enabled: bool) -> Self {
        self.detailed_info = enabled;
        self
    }

    /// Set TLDs to check for base domain names.
    pub fn with_tlds(mut self, tlds: Vec<String>) -> Self {
        self.tlds = Some(tlds);
        self
    }
}

/// Configuration for domain name generation.
///
/// Controls pattern expansion, prefix/suffix permutation, and the generation pipeline.
/// Used by the `generate` module to produce base domain names before TLD expansion.
#[derive(Debug, Clone, Default)]
pub struct GenerateConfig {
    /// Patterns to expand (e.g., "test\d\d", "app?")
    /// Supports: \w (a-z + hyphen), \d (0-9), ? (alphanumeric + hyphen), literals
    pub patterns: Vec<String>,

    /// Prefixes to prepend to base names (e.g., ["get", "my", "try"])
    pub prefixes: Vec<String>,

    /// Suffixes to append to base names (e.g., ["hub", "ly", "ify"])
    pub suffixes: Vec<String>,

    /// Whether to include the bare base name when prefixes/suffixes are provided.
    /// Default: true. When false, only affixed variants are generated.
    pub include_bare: bool,
}

/// Result of the domain name generation pipeline.
#[derive(Debug, Clone)]
pub struct GenerationResult {
    /// Generated base names (validated, ready for TLD expansion)
    pub names: Vec<String>,

    /// Pre-filter estimate of how many names the patterns would produce.
    /// May be higher than `names.len()` due to validation filtering.
    pub estimated_count: usize,
}

impl GenerateConfig {
    /// Create a new GenerateConfig with default settings.
    pub fn new() -> Self {
        Self {
            patterns: Vec::new(),
            prefixes: Vec::new(),
            suffixes: Vec::new(),
            include_bare: true,
        }
    }

    /// Returns true if this config would actually generate anything.
    pub fn has_generation(&self) -> bool {
        !self.patterns.is_empty()
    }

    /// Returns true if affixes are configured.
    pub fn has_affixes(&self) -> bool {
        !self.prefixes.is_empty() || !self.suffixes.is_empty()
    }
}

impl std::fmt::Display for CheckMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CheckMethod::Rdap => write!(f, "RDAP"),
            CheckMethod::Whois => write!(f, "WHOIS"),
            CheckMethod::Bootstrap => write!(f, "Bootstrap"),
            CheckMethod::Unknown => write!(f, "Unknown"),
        }
    }
}

impl std::fmt::Display for OutputMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputMode::Streaming => write!(f, "Streaming"),
            OutputMode::Collected => write!(f, "Collected"),
            OutputMode::Auto => write!(f, "Auto"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── CheckConfig defaults ────────────────────────────────────────────

    #[test]
    fn test_check_config_defaults() {
        let config = CheckConfig::default();
        assert_eq!(config.concurrency, 20);
        assert_eq!(config.timeout, Duration::from_secs(5));
        assert!(config.enable_whois_fallback);
        assert!(config.enable_bootstrap);
        assert!(!config.detailed_info);
        assert!(config.tlds.is_none());
        assert_eq!(config.rdap_timeout, Duration::from_secs(3));
        assert_eq!(config.whois_timeout, Duration::from_secs(5));
        assert!(config.custom_presets.is_empty());
    }

    // ── Builder methods ─────────────────────────────────────────────────

    #[test]
    fn test_with_concurrency_normal() {
        let config = CheckConfig::default().with_concurrency(50);
        assert_eq!(config.concurrency, 50);
    }

    #[test]
    fn test_with_concurrency_clamps_to_max() {
        let config = CheckConfig::default().with_concurrency(200);
        assert_eq!(config.concurrency, 100);
    }

    #[test]
    fn test_with_concurrency_clamps_to_min() {
        let config = CheckConfig::default().with_concurrency(0);
        assert_eq!(config.concurrency, 1);
    }

    #[test]
    fn test_with_concurrency_boundary_values() {
        assert_eq!(CheckConfig::default().with_concurrency(1).concurrency, 1);
        assert_eq!(
            CheckConfig::default().with_concurrency(100).concurrency,
            100
        );
    }

    #[test]
    fn test_with_timeout() {
        let config = CheckConfig::default().with_timeout(Duration::from_secs(30));
        assert_eq!(config.timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_with_whois_fallback() {
        let config = CheckConfig::default().with_whois_fallback(false);
        assert!(!config.enable_whois_fallback);
    }

    #[test]
    fn test_with_bootstrap() {
        let config = CheckConfig::default().with_bootstrap(false);
        assert!(!config.enable_bootstrap);
    }

    #[test]
    fn test_with_detailed_info() {
        let config = CheckConfig::default().with_detailed_info(true);
        assert!(config.detailed_info);
    }

    #[test]
    fn test_with_tlds() {
        let config = CheckConfig::default().with_tlds(vec!["com".into(), "org".into()]);
        assert_eq!(
            config.tlds,
            Some(vec!["com".to_string(), "org".to_string()])
        );
    }

    #[test]
    fn test_builder_chaining_order_independent() {
        let a = CheckConfig::default()
            .with_concurrency(50)
            .with_timeout(Duration::from_secs(10))
            .with_bootstrap(false);

        let b = CheckConfig::default()
            .with_bootstrap(false)
            .with_timeout(Duration::from_secs(10))
            .with_concurrency(50);

        assert_eq!(a.concurrency, b.concurrency);
        assert_eq!(a.timeout, b.timeout);
        assert_eq!(a.enable_bootstrap, b.enable_bootstrap);
    }

    #[test]
    fn test_builder_preserves_other_defaults() {
        let config = CheckConfig::default().with_concurrency(50);
        // Only concurrency changed; everything else should be default
        assert_eq!(config.timeout, Duration::from_secs(5));
        assert!(config.enable_whois_fallback);
        assert!(config.enable_bootstrap);
        assert!(!config.detailed_info);
        assert!(config.tlds.is_none());
    }

    // ── GenerateConfig ──────────────────────────────────────────────────

    #[test]
    fn test_generate_config_new_defaults() {
        let config = GenerateConfig::new();
        assert!(config.patterns.is_empty());
        assert!(config.prefixes.is_empty());
        assert!(config.suffixes.is_empty());
        assert!(config.include_bare);
    }

    #[test]
    fn test_generate_config_has_generation_empty() {
        let config = GenerateConfig::new();
        assert!(!config.has_generation());
    }

    #[test]
    fn test_generate_config_has_generation_with_pattern() {
        let mut config = GenerateConfig::new();
        config.patterns.push("test\\d".to_string());
        assert!(config.has_generation());
    }

    #[test]
    fn test_generate_config_has_affixes_none() {
        let config = GenerateConfig::new();
        assert!(!config.has_affixes());
    }

    #[test]
    fn test_generate_config_has_affixes_prefix_only() {
        let mut config = GenerateConfig::new();
        config.prefixes.push("get".to_string());
        assert!(config.has_affixes());
    }

    #[test]
    fn test_generate_config_has_affixes_suffix_only() {
        let mut config = GenerateConfig::new();
        config.suffixes.push("ly".to_string());
        assert!(config.has_affixes());
    }

    // ── Display impls ───────────────────────────────────────────────────

    #[test]
    fn test_check_method_display() {
        assert_eq!(format!("{}", CheckMethod::Rdap), "RDAP");
        assert_eq!(format!("{}", CheckMethod::Whois), "WHOIS");
        assert_eq!(format!("{}", CheckMethod::Bootstrap), "Bootstrap");
        assert_eq!(format!("{}", CheckMethod::Unknown), "Unknown");
    }

    #[test]
    fn test_output_mode_display() {
        assert_eq!(format!("{}", OutputMode::Streaming), "Streaming");
        assert_eq!(format!("{}", OutputMode::Collected), "Collected");
        assert_eq!(format!("{}", OutputMode::Auto), "Auto");
    }

    // ── Serialization ───────────────────────────────────────────────────

    #[test]
    fn test_check_method_serialization() {
        let json = serde_json::to_string(&CheckMethod::Rdap).unwrap();
        assert_eq!(json, "\"rdap\"");
        let json = serde_json::to_string(&CheckMethod::Whois).unwrap();
        assert_eq!(json, "\"whois\"");
    }

    #[test]
    fn test_check_method_deserialization() {
        let method: CheckMethod = serde_json::from_str("\"bootstrap\"").unwrap();
        assert_eq!(method, CheckMethod::Bootstrap);
    }

    #[test]
    fn test_domain_result_json_skip_none_fields() {
        let result = DomainResult {
            domain: "test.com".to_string(),
            available: Some(true),
            info: None,
            check_duration: None,
            method_used: CheckMethod::Rdap,
            error_message: None,
        };
        let json = serde_json::to_string(&result).unwrap();
        // None fields with skip_serializing_if should be absent
        assert!(!json.contains("info"));
        assert!(!json.contains("check_duration"));
        assert!(!json.contains("error_message"));
        assert!(json.contains("\"domain\":\"test.com\""));
        assert!(json.contains("\"available\":true"));
    }

    #[test]
    fn test_domain_info_default() {
        let info = DomainInfo::default();
        assert!(info.registrar.is_none());
        assert!(info.creation_date.is_none());
        assert!(info.expiration_date.is_none());
        assert!(info.status.is_empty());
        assert!(info.updated_date.is_none());
        assert!(info.nameservers.is_empty());
    }
}