waitup 1.0.1

Wait for TCP ports and HTTP endpoints to be available. Essential for Docker, K8s, and CI/CD pipelines to ensure services are ready before proceeding.
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
//! Core type definitions for waitup library.
//!
//! This module contains the fundamental types used throughout the waitup library:
//! - [`Port`] and [`Hostname`] - `NewType` wrappers for type safety
//! - [`Target`] - Represents services to wait for (TCP or HTTP)
//! - [`WaitConfig`] - Configuration for wait operations
//! - [`WaitResult`] and [`TargetResult`] - Result types for wait operations
//! - Error types for different failure modes
//!
//! # Examples
//!
//! ## Creating type-safe network identifiers
//!
//! ```rust
//! use waitup::{Port, Hostname};
//!
//! // Create a validated port
//! let port = Port::new(8080).expect("Valid port");
//! assert_eq!(port.get(), 8080);
//!
//! // Use port range validation
//! let http_port = Port::well_known(80).expect("HTTP is well-known");
//! let app_port = Port::registered(8080).expect("8080 is registered");
//! let ephemeral = Port::dynamic(49152).expect("49152 is dynamic");
//!
//! // Create validated hostnames
//! let hostname = Hostname::new("example.com").expect("Valid hostname");
//! let localhost = Hostname::localhost();
//! let ip = Hostname::ipv4("192.168.1.1").expect("Valid IPv4");
//! ```
//!
//! ## Defining targets
//!
//! ```rust
//! use waitup::Target;
//! use url::Url;
//!
//! // TCP target
//! let tcp_target = Target::Tcp {
//!     host: waitup::Hostname::new("database.example.com").unwrap(),
//!     port: waitup::Port::new(5432).unwrap(),
//! };
//!
//! // HTTP target
//! let http_target = Target::Http {
//!     url: Url::parse("https://api.example.com/health").unwrap(),
//!     expected_status: 200,
//!     headers: Some(vec![("Authorization".to_string(), "Bearer token".to_string())]),
//! };
//! ```

use core::fmt;
use core::num::NonZeroU16;
use core::time::Duration;
use std::borrow::Cow;
use thiserror::Error;
use tokio_util::sync::CancellationToken;
use url::Url;

use crate::error_messages;

// Type aliases for complex types to improve readability
/// HTTP headers represented as a vector of key-value pairs
pub type HttpHeaders = Vec<(String, String)>;

/// Result type alias for functions returning a vector of targets
pub type TargetVecResult = crate::Result<Vec<Target>>;

/// `NewType` wrapper for ports to provide type safety
/// Uses `NonZeroU16` internally to guarantee valid port numbers (1-65535)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Port(NonZeroU16);

impl Port {
    /// Create a new port, validating it's not zero
    #[must_use]
    pub const fn new(port: u16) -> Option<Self> {
        match NonZeroU16::new(port) {
            Some(nz) => Some(Self(nz)),
            None => None,
        }
    }

    /// Create a port from a standard well-known port number
    #[must_use]
    pub const fn well_known(port: u16) -> Option<Self> {
        if port == 0 || port > 1023 {
            None
        } else {
            Self::new(port)
        }
    }

    /// Create a port from a registered port number range
    #[must_use]
    pub const fn registered(port: u16) -> Option<Self> {
        if port < 1024 || port > 49151 {
            None
        } else {
            Self::new(port)
        }
    }

    /// Create a port from a dynamic/private port number range
    #[must_use]
    pub const fn dynamic(port: u16) -> Option<Self> {
        if port < 49152 {
            None
        } else {
            Self::new(port)
        }
    }

    /// Create a new port without validation (for known valid values)
    /// Only use this when you know the port is valid (not zero)
    ///
    /// This method uses unwrap internally but is safe because it's only
    /// called with compile-time known valid port numbers.
    #[must_use]
    pub const fn new_unchecked(port: u16) -> Self {
        if let Some(nz) = NonZeroU16::new(port) {
            Self(nz)
        } else {
            // This should never happen for valid known ports
            let safe_port = if port == 0 { 1 } else { port };
            Self(unsafe { NonZeroU16::new_unchecked(safe_port) })
        }
    }

    /// Common HTTP port (80)
    #[must_use]
    pub const fn http() -> Self {
        Self::new_unchecked(80)
    }

    /// Common HTTPS port (443)
    #[must_use]
    pub const fn https() -> Self {
        Self::new_unchecked(443)
    }

    /// Common SSH port (22)
    #[must_use]
    pub const fn ssh() -> Self {
        Self::new_unchecked(22)
    }

    /// Common `PostgreSQL` port (5432)
    #[must_use]
    pub const fn postgres() -> Self {
        Self::new_unchecked(5432)
    }

    /// Common `MySQL` port (3306)
    #[must_use]
    pub const fn mysql() -> Self {
        Self::new_unchecked(3306)
    }

    /// Common Redis port (6379)
    #[must_use]
    pub const fn redis() -> Self {
        Self::new_unchecked(6379)
    }

    /// Get the inner port value
    #[must_use]
    pub const fn get(&self) -> u16 {
        self.0.get()
    }
}

impl fmt::Display for Port {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryFrom<u16> for Port {
    type Error = crate::WaitForError;

    fn try_from(port: u16) -> crate::Result<Self> {
        Self::new(port).ok_or_else(|| crate::WaitForError::InvalidPort(port))
    }
}

impl TryFrom<u32> for Port {
    type Error = crate::WaitForError;

    fn try_from(port: u32) -> crate::Result<Self> {
        if port > u32::from(u16::MAX) {
            return Err(crate::WaitForError::InvalidPort(0)); // Use 0 to represent invalid port
        }
        Self::try_from(u16::try_from(port).unwrap_or(0))
    }
}

impl TryFrom<i32> for Port {
    type Error = crate::WaitForError;

    fn try_from(port: i32) -> crate::Result<Self> {
        if port < 0 || port > i32::from(u16::MAX) {
            return Err(crate::WaitForError::InvalidPort(0)); // Use 0 to represent invalid
        }
        Self::try_from(u16::try_from(port).unwrap_or(0))
    }
}

impl TryFrom<usize> for Port {
    type Error = crate::WaitForError;

    fn try_from(port: usize) -> crate::Result<Self> {
        if port > usize::from(u16::MAX) {
            return Err(crate::WaitForError::InvalidPort(0)); // Use 0 to represent invalid
        }
        Self::try_from(u16::try_from(port).unwrap_or(0))
    }
}

impl TryFrom<NonZeroU16> for Port {
    type Error = crate::WaitForError;

    fn try_from(port: NonZeroU16) -> crate::Result<Self> {
        Ok(Self(port))
    }
}

/// Parse port from string representations
impl std::str::FromStr for Port {
    type Err = crate::WaitForError;

    fn from_str(s: &str) -> crate::Result<Self> {
        let port: u16 = s.parse().map_err(|_| crate::WaitForError::InvalidPort(0))?;
        Self::try_from(port)
    }
}

impl From<Port> for u16 {
    fn from(port: Port) -> Self {
        port.0.get()
    }
}

impl From<Port> for NonZeroU16 {
    fn from(port: Port) -> Self {
        port.0
    }
}

/// `NewType` wrapper for hostnames to provide type safety
/// Uses Cow<'static, str> to avoid allocations for common static hostnames
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Hostname(Cow<'static, str>);

impl Hostname {
    /// Create a new hostname with validation
    ///
    /// # Errors
    ///
    /// Returns an error if the hostname is invalid or too long
    pub fn new(hostname: impl Into<String>) -> crate::Result<Self> {
        let hostname = hostname.into();
        Self::validate(&hostname)?;
        Ok(Self(Cow::Owned(hostname)))
    }

    /// Create a hostname from a static string (zero allocation)
    #[must_use]
    pub const fn from_static(hostname: &'static str) -> Self {
        Self(Cow::Borrowed(hostname))
    }

    /// Validate a hostname according to RFC standards
    fn validate(hostname: &str) -> crate::Result<()> {
        if hostname.is_empty() {
            return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                error_messages::EMPTY_HOSTNAME,
            )));
        }

        if hostname.len() > 253 {
            return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                error_messages::HOSTNAME_TOO_LONG,
            )));
        }

        if hostname.starts_with('-') || hostname.ends_with('-') {
            return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                error_messages::HOSTNAME_INVALID_HYPHEN,
            )));
        }

        for label in hostname.split('.') {
            if label.is_empty() {
                return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::HOSTNAME_EMPTY_LABEL,
                )));
            }
            if label.len() > 63 {
                return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::HOSTNAME_LABEL_TOO_LONG,
                )));
            }
            if label.starts_with('-') || label.ends_with('-') {
                return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::HOSTNAME_LABEL_INVALID_HYPHEN,
                )));
            }
            if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
                return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::HOSTNAME_INVALID_CHARS,
                )));
            }
        }

        Ok(())
    }

    /// Create hostname for localhost (zero allocation)
    #[must_use]
    pub const fn localhost() -> Self {
        Self::from_static("localhost")
    }

    /// Create hostname for IPv4 loopback (zero allocation)
    #[must_use]
    pub const fn loopback() -> Self {
        Self::from_static("127.0.0.1")
    }

    /// Create hostname for IPv6 loopback (zero allocation)
    #[must_use]
    pub const fn loopback_v6() -> Self {
        Self::from_static("::1")
    }

    /// Create hostname for wildcard/any address (zero allocation)
    #[must_use]
    pub const fn any() -> Self {
        Self::from_static("0.0.0.0")
    }

    /// Create hostname for an IPv4 address (validates format)
    ///
    /// # Errors
    ///
    /// Returns an error if the IPv4 format is invalid
    pub fn ipv4(ip: impl AsRef<str>) -> crate::Result<Self> {
        let ip = ip.as_ref();
        // Basic IPv4 validation without allocating a vector
        let mut parts_count = 0;
        for part in ip.split('.') {
            parts_count += 1;
            if parts_count > 4 {
                return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::INVALID_IPV4_FORMAT,
                )));
            }
            let _num: u8 = part.parse().map_err(|_| {
                crate::WaitForError::InvalidHostname(Cow::Borrowed(
                    error_messages::INVALID_IPV4_OCTET,
                ))
            })?;
            // _num is automatically validated to be 0-255 by u8 parsing
        }
        if parts_count != 4 {
            return Err(crate::WaitForError::InvalidHostname(Cow::Borrowed(
                error_messages::INVALID_IPV4_FORMAT,
            )));
        }
        Ok(Self(Cow::Owned(ip.to_string())))
    }

    /// Get the hostname as a string slice
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// IPv4 loopback address (zero allocation)
    #[must_use]
    pub const fn ipv4_loopback() -> Self {
        Self::from_static("127.0.0.1")
    }

    /// IPv6 loopback address (zero allocation)
    #[must_use]
    pub const fn ipv6_loopback() -> Self {
        Self::from_static("::1")
    }

    /// Any IPv4 address (zero allocation)
    #[must_use]
    pub const fn ipv4_any() -> Self {
        Self::from_static("0.0.0.0")
    }

    /// Any IPv6 address (zero allocation)
    #[must_use]
    pub const fn ipv6_any() -> Self {
        Self::from_static("::")
    }
}

impl fmt::Display for Hostname {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryFrom<String> for Hostname {
    type Error = crate::WaitForError;

    fn try_from(hostname: String) -> crate::Result<Self> {
        Self::new(hostname)
    }
}

impl TryFrom<&str> for Hostname {
    type Error = crate::WaitForError;

    fn try_from(hostname: &str) -> crate::Result<Self> {
        Self::new(hostname)
    }
}

/// Parse hostname from string (same as `TryFrom`<&str> but explicit)
impl std::str::FromStr for Hostname {
    type Err = crate::WaitForError;

    fn from_str(s: &str) -> crate::Result<Self> {
        Self::try_from(s)
    }
}

/// Additional conversions for Hostname
impl TryFrom<std::net::IpAddr> for Hostname {
    type Error = crate::WaitForError;

    fn try_from(ip: std::net::IpAddr) -> crate::Result<Self> {
        match ip {
            std::net::IpAddr::V4(ipv4) => Self::ipv4(ipv4.to_string()),
            std::net::IpAddr::V6(ipv6) => Self::new(ipv6.to_string()),
        }
    }
}

impl TryFrom<std::net::Ipv4Addr> for Hostname {
    type Error = crate::WaitForError;

    fn try_from(ip: std::net::Ipv4Addr) -> crate::Result<Self> {
        Self::ipv4(ip.to_string())
    }
}

impl TryFrom<std::net::Ipv6Addr> for Hostname {
    type Error = crate::WaitForError;

    fn try_from(ip: std::net::Ipv6Addr) -> crate::Result<Self> {
        Self::new(ip.to_string())
    }
}

impl AsRef<str> for Hostname {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::borrow::Borrow<str> for Hostname {
    fn borrow(&self) -> &str {
        &self.0
    }
}

/// Specific error types for different connection failure modes
#[derive(Error, Debug)]
pub enum ConnectionError {
    /// Failed to establish TCP connection to the target host and port
    #[error("Failed to connect to {host}:{port} - {reason}")]
    TcpConnection {
        /// The hostname or IP address that connection failed to
        host: Cow<'static, str>,
        /// The port number that connection failed to
        port: u16,
        #[source]
        /// The underlying I/O error that caused the connection failure
        reason: std::io::Error,
    },
    /// Connection attempt timed out before establishing a connection
    #[error("Connection timeout after {timeout_ms}ms")]
    Timeout {
        /// The timeout duration in milliseconds that was exceeded
        timeout_ms: u64,
    },
    /// Failed to resolve hostname to IP address via DNS
    #[error("DNS resolution failed for {host}: {reason}")]
    DnsResolution {
        /// The hostname that failed to resolve
        host: Cow<'static, str>,
        #[source]
        /// The underlying I/O error from DNS resolution
        reason: std::io::Error,
    },
}

/// Specific error types for HTTP operations
#[derive(Error, Debug)]
pub enum HttpError {
    /// HTTP request failed due to network or server error
    #[error("HTTP request failed for {url}: {reason}")]
    RequestFailed {
        /// The URL that the request failed to reach
        url: Cow<'static, str>,
        #[source]
        /// The underlying HTTP client error
        reason: reqwest::Error,
    },
    /// HTTP response returned unexpected status code
    #[error("Unexpected status code: expected {expected}, got {actual}")]
    UnexpectedStatus {
        /// The HTTP status code that was expected
        expected: u16,
        /// The actual HTTP status code received
        actual: u16,
    },
    /// Invalid HTTP header format or value
    #[error("Invalid header: {header}")]
    InvalidHeader {
        /// The header that was invalid
        header: Cow<'static, str>,
    },
}

/// A target service to wait for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// TCP connection target with host and port.
    Tcp {
        /// The hostname or IP address
        host: Hostname,
        /// The port number
        port: Port,
    },
    /// HTTP/HTTPS endpoint target.
    Http {
        /// The URL to check
        url: Url,
        /// Expected HTTP status code
        expected_status: u16,
        /// Optional custom headers
        headers: Option<HttpHeaders>,
    },
}

impl TryFrom<&str> for Target {
    type Error = crate::WaitForError;

    fn try_from(target_str: &str) -> crate::Result<Self> {
        // Use the existing parse method with default status 200
        // Note: This will be implemented in target.rs as Target::parse
        Self::parse(target_str, 200)
    }
}

impl TryFrom<String> for Target {
    type Error = crate::WaitForError;

    fn try_from(target_str: String) -> crate::Result<Self> {
        Self::try_from(target_str.as_str())
    }
}

impl std::str::FromStr for Target {
    type Err = crate::WaitForError;

    fn from_str(s: &str) -> crate::Result<Self> {
        Self::try_from(s)
    }
}

/// Additional Target construction methods
impl Target {
    /// Try to create a TCP target from host and port
    ///
    /// # Errors
    ///
    /// Returns an error if the hostname or port conversion fails
    pub fn try_tcp<H, P>(host: H, port: P) -> crate::Result<Self>
    where
        H: TryInto<Hostname>,
        P: TryInto<Port>,
        H::Error: Into<crate::WaitForError>,
        P::Error: Into<crate::WaitForError>,
    {
        let hostname = host.try_into().map_err(Into::into)?;
        let port = port.try_into().map_err(Into::into)?;
        Ok(Self::Tcp {
            host: hostname,
            port,
        })
    }

    /// Try to create an HTTP target from URL string
    ///
    /// # Errors
    ///
    /// Returns an error if the URL cannot be parsed or is invalid
    pub fn try_http(url: impl AsRef<str>, expected_status: u16) -> crate::Result<Self> {
        let url = Url::parse(url.as_ref())?;
        Ok(Self::Http {
            url,
            expected_status,
            headers: None,
        })
    }
}

/// Validated Duration wrapper with string parsing support
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ValidatedDuration(Duration);

impl ValidatedDuration {
    /// Create a new validated duration
    #[must_use]
    pub const fn new(duration: Duration) -> Self {
        Self(duration)
    }

    /// Get the inner Duration
    #[must_use]
    pub const fn get(&self) -> Duration {
        self.0
    }

    /// Create from seconds
    #[must_use]
    pub const fn from_secs(secs: u64) -> Self {
        Self(Duration::from_secs(secs))
    }

    /// Create from milliseconds
    #[must_use]
    pub const fn from_millis(millis: u64) -> Self {
        Self(Duration::from_millis(millis))
    }
}

impl From<ValidatedDuration> for Duration {
    fn from(vd: ValidatedDuration) -> Self {
        vd.0
    }
}

impl TryFrom<Duration> for ValidatedDuration {
    type Error = crate::WaitForError;

    fn try_from(duration: Duration) -> crate::Result<Self> {
        // Could add validation here (e.g., max duration limits)
        Ok(Self(duration))
    }
}

/// Parse duration from string with support for common suffixes
/// Supports: "30s", "5m", "2h", "1000ms", etc.
impl std::str::FromStr for ValidatedDuration {
    type Err = crate::WaitForError;

    fn from_str(s: &str) -> crate::Result<Self> {
        let s = s.trim();

        if let Ok(secs) = s.parse::<u64>() {
            // Pure number interpreted as seconds
            return Ok(Self::from_secs(secs));
        }

        let (number_part, unit_part) =
            if let Some(pos) = s.find(|c: char| !c.is_ascii_digit() && c != '.') {
                s.split_at(pos)
            } else {
                return Err(crate::WaitForError::InvalidTimeout(
                    Cow::Owned(s.to_string()),
                    Cow::Borrowed("Invalid duration format"),
                ));
            };

        let number: f64 = number_part.parse().map_err(|_| {
            crate::WaitForError::InvalidTimeout(
                Cow::Owned(s.to_string()),
                Cow::Borrowed("Invalid number"),
            )
        })?;

        let duration = match unit_part {
            "ms" => {
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "duration calculation requires f64"
                )]
                let millis = (number * 1.0).min(u64::MAX as f64);
                if millis < 0.0 {
                    return Err(crate::WaitForError::InvalidTimeout(
                        Cow::Owned(s.to_string()),
                        Cow::Borrowed("Duration cannot be negative"),
                    ));
                }
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "safe cast after bounds check"
                )]
                Duration::from_millis(millis as u64)
            }
            "s" => {
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "duration calculation requires f64"
                )]
                let millis = (number * 1000.0).min(u64::MAX as f64);
                if millis < 0.0 {
                    return Err(crate::WaitForError::InvalidTimeout(
                        Cow::Owned(s.to_string()),
                        Cow::Borrowed("Duration cannot be negative"),
                    ));
                }
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "safe cast after bounds check"
                )]
                Duration::from_millis(millis as u64)
            }
            "m" => {
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "duration calculation requires f64"
                )]
                let millis = (number * 60_000.0).min(u64::MAX as f64);
                if millis < 0.0 {
                    return Err(crate::WaitForError::InvalidTimeout(
                        Cow::Owned(s.to_string()),
                        Cow::Borrowed("Duration cannot be negative"),
                    ));
                }
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "safe cast after bounds check"
                )]
                Duration::from_millis(millis as u64)
            }
            "h" => {
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "duration calculation requires f64"
                )]
                let millis = (number * 3_600_000.0).min(u64::MAX as f64);
                if millis < 0.0 {
                    return Err(crate::WaitForError::InvalidTimeout(
                        Cow::Owned(s.to_string()),
                        Cow::Borrowed("Duration cannot be negative"),
                    ));
                }
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "safe cast after bounds check"
                )]
                Duration::from_millis(millis as u64)
            }
            _ => {
                return Err(crate::WaitForError::InvalidTimeout(
                    Cow::Owned(s.to_string()),
                    Cow::Borrowed("Unknown time unit (use: ms, s, m, h)"),
                ));
            }
        };

        Ok(Self(duration))
    }
}

impl TryFrom<&str> for ValidatedDuration {
    type Error = crate::WaitForError;

    fn try_from(s: &str) -> crate::Result<Self> {
        s.parse()
    }
}

impl TryFrom<String> for ValidatedDuration {
    type Error = crate::WaitForError;

    fn try_from(s: String) -> crate::Result<Self> {
        s.as_str().parse()
    }
}

impl fmt::Display for ValidatedDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Display in a human readable format
        let total_ms =
            u64::try_from(self.0.as_millis().min(u128::from(u64::MAX))).unwrap_or(u64::MAX);

        if total_ms >= 3_600_000 {
            write!(f, "{hours}h", hours = total_ms / 3_600_000)
        } else if total_ms >= 60_000 {
            write!(f, "{minutes}m", minutes = total_ms / 60_000)
        } else if total_ms >= 1_000 {
            write!(f, "{seconds}s", seconds = total_ms / 1_000)
        } else {
            write!(f, "{total_ms}ms")
        }
    }
}

/// Configuration for wait operations.
#[derive(Debug, Clone)]
pub struct WaitConfig {
    /// Total timeout for all wait operations.
    pub timeout: Duration,
    /// Initial retry interval.
    pub initial_interval: Duration,
    /// Maximum retry interval for exponential backoff.
    pub max_interval: Duration,
    /// If true, wait for any target to be ready. If false, wait for all targets.
    pub wait_for_any: bool,
    /// Maximum number of retry attempts (None for unlimited).
    pub max_retries: Option<u32>,
    /// Individual connection timeout.
    pub connection_timeout: Duration,
    /// Cancellation token for graceful shutdown.
    pub cancellation_token: Option<CancellationToken>,
    /// Security validator for targets (None to skip validation).
    pub security_validator: Option<crate::security::SecurityValidator>,
    /// Rate limiter for connection attempts (None to disable rate limiting).
    pub rate_limiter: Option<crate::security::RateLimiter>,
}

impl Default for WaitConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(30),
            initial_interval: Duration::from_secs(1),
            max_interval: Duration::from_secs(30),
            wait_for_any: false,
            max_retries: None,
            connection_timeout: Duration::from_secs(10),
            cancellation_token: None,
            security_validator: None,
            rate_limiter: None,
        }
    }
}

// Implement common duration conversions for convenience
impl From<Duration> for WaitConfig {
    fn from(timeout: Duration) -> Self {
        Self {
            timeout,
            ..Default::default()
        }
    }
}

// Custom PartialEq implementation that ignores runtime fields
impl PartialEq for WaitConfig {
    fn eq(&self, other: &Self) -> bool {
        self.timeout == other.timeout
            && self.initial_interval == other.initial_interval
            && self.max_interval == other.max_interval
            && self.wait_for_any == other.wait_for_any
            && self.max_retries == other.max_retries
            && self.connection_timeout == other.connection_timeout
        // Intentionally ignore cancellation_token, security_validator, and rate_limiter
        // as they don't implement PartialEq or are runtime-specific
    }
}

impl Eq for WaitConfig {}

/// Information about a wait operation result.
#[derive(Debug, Clone)]
pub struct WaitResult {
    /// Whether the operation was successful.
    pub success: bool,
    /// Time elapsed during the operation.
    pub elapsed: Duration,
    /// Number of attempts made.
    pub attempts: u32,
    /// Results for each target.
    pub target_results: Vec<TargetResult>,
}

/// Result for an individual target.
#[derive(Debug, Clone)]
pub struct TargetResult {
    /// The target that was tested.
    pub target: Target,
    /// Whether this target was successful.
    pub success: bool,
    /// Time elapsed for this target.
    pub elapsed: Duration,
    /// Number of attempts for this target.
    pub attempts: u32,
    /// Error message if unsuccessful.
    pub error: Option<String>,
}