### Create SecurityValidator Instance Source: https://docs.rs/waitup/1.0.1/waitup/security/struct Demonstrates how to create a new `SecurityValidator` instance. This is the starting point for configuring security settings. ```Rust pub struct SecurityValidator { /* private fields */ } impl SecurityValidator { pub fn new() -> Self } ``` -------------------------------- ### Microservice Readiness Configuration Source: https://docs.rs/waitup/1.0.1/waitup/config/index Provides examples of configuring WaitConfig for different scenarios: fast polling for local services and conservative settings for external services. ```Rust use waitup::WaitConfig; use std::time::Duration; // Fast polling for local services let local_config = WaitConfig::builder() .timeout(Duration::from_secs(10)) .interval(Duration::from_millis(100)) .max_interval(Duration::from_secs(1)) .connection_timeout(Duration::from_secs(2)) .build(); // Conservative settings for external services let external_config = WaitConfig::builder() .timeout(Duration::from_secs(120)) .interval(Duration::from_secs(2)) .max_interval(Duration::from_secs(30)) .connection_timeout(Duration::from_secs(15)) .max_retries(Some(10)) .build(); ``` -------------------------------- ### Quick Start: Add waitup to Cargo.toml Source: https://docs.rs/waitup/1.0.1/waitup/index This snippet shows how to add the waitup crate and its Tokio dependency to your project's Cargo.toml file for basic usage. ```toml [dependencies] waitup = "1.0" tokio = { version = "1.0", features = ["full"] } ``` -------------------------------- ### Quick Start: Add waitup to Cargo.toml Source: https://docs.rs/waitup/1.0.1/index This snippet shows how to add the waitup crate and its Tokio dependency to your project's Cargo.toml file for basic usage. ```toml [dependencies] waitup = "1.0" tokio = { version = "1.0", features = ["full"] } ``` -------------------------------- ### Wait for Service Readiness with Context (Rust) Source: https://docs.rs/waitup/1.0.1/waitup/error/index An example demonstrating how to configure and wait for multiple services (database and cache) to become ready using `wait_for_connection`. It also shows how to apply context to the overall operation and individual target creations. ```Rust use waitup::{Target, WaitConfig, wait_for_connection, ResultExt}; use std::time::Duration; async fn wait_for_services() -> Result<(), waitup::WaitForError> { let targets = vec![ Target::tcp("database", 5432) .context("Database target creation failed")?, Target::tcp("cache", 6379) .context("Cache target creation failed")?, ]; let config = WaitConfig::builder() .timeout(Duration::from_secs(30)) .build(); wait_for_connection(&targets, &config) .await .context("Service readiness check failed")?; Ok(()) } ``` -------------------------------- ### Multiple Services with Different Strategies Source: https://docs.rs/waitup/1.0.1/waitup/index Shows how to wait for multiple services, including TCP and HTTP targets, to become available. This example configures waiting for all services and sets a maximum retry count. ```rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let targets = vec![ Target::tcp("database", 5432)?, Target::tcp("cache", 6379)?, Target::http_url("https://api.example.com/health", 200)?, ]; // Wait for ALL services to be ready let config = WaitConfig::builder() .timeout(Duration::from_secs(120)) .wait_for_any(false) .max_retries(Some(20)) .build(); wait_for_connection(&targets, &config).await?; println!("All services are ready!"); Ok(()) } ``` -------------------------------- ### Rust Waitup Microservice Readiness Configuration Source: https://docs.rs/waitup/1.0.1/src/waitup/config Provides examples for configuring WaitConfig for different microservice scenarios, including fast polling for local services and conservative settings for external services. ```Rust use waitup::WaitConfig; use std::time::Duration; // Fast polling for local services let local_config = WaitConfig::builder() .timeout(Duration::from_secs(10)) .interval(Duration::from_millis(100)) .max_interval(Duration::from_secs(1)) .connection_timeout(Duration::from_secs(2)) .build(); // Conservative settings for external services let external_config = WaitConfig::builder() .timeout(Duration::from_secs(120)) .interval(Duration::from_secs(2)) .max_interval(Duration::from_secs(30)) .connection_timeout(Duration::from_secs(15)) .max_retries(Some(10)) .build(); ``` -------------------------------- ### Multiple Services with Different Strategies Source: https://docs.rs/waitup/1.0.1/index Shows how to wait for multiple services, including TCP and HTTP targets, to become available. This example configures waiting for all services and sets a maximum retry count. ```rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let targets = vec![ Target::tcp("database", 5432)?, Target::tcp("cache", 6379)?, Target::http_url("https://api.example.com/health", 200)?, ]; // Wait for ALL services to be ready let config = WaitConfig::builder() .timeout(Duration::from_secs(120)) .wait_for_any(false) .max_retries(Some(20)) .build(); wait_for_connection(&targets, &config).await?; println!("All services are ready!"); Ok(()) } ``` -------------------------------- ### Advanced Configuration with Cancellation using waitup Source: https://docs.rs/waitup/1.0.1/src/waitup/lib This example illustrates advanced waitup configuration, including setting an interval and using a cancellation token. It shows how to spawn a task to cancel the wait operation after a specified duration. ```rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; use tokio::time::sleep; #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let target = Target::tcp("slow-service", 8080)?; let (builder, cancel_token) = WaitConfig::builder() .timeout(Duration::from_secs(60)) .interval(Duration::from_millis(500)) .with_cancellation(); let config = builder.build(); // Cancel after 10 seconds let cancel_handle = { let token = cancel_token.clone(); tokio::spawn(async move { sleep(Duration::from_secs(10)).await; token.cancel(); }) }; match wait_for_connection(&[target], &config).await { Ok(_) => println!("Service is ready!"), Err(waitup::WaitForError::Cancelled) => println!("Operation was cancelled"), Err(e) => println!("Error: {}", e), } cancel_handle.abort(); // Clean up the cancel task } ``` -------------------------------- ### Rust: Create a new SecurityValidator instance Source: https://docs.rs/waitup/1.0.1/src/waitup/security A constructor function to create a new instance of the SecurityValidator, initializing it with default security settings. This allows for easy setup of security validation. ```Rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Default WaitConfig Initialization Source: https://docs.rs/waitup/1.0.1/src/waitup/types Provides default values for `WaitConfig`, setting a 30-second total timeout, 1-second initial interval, 30-second max interval, and other sensible defaults for wait operations. This allows for quick setup without specifying every parameter. ```Rust 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, } } } ``` -------------------------------- ### Rust: Integrate Waitup with Docker Compose Source: https://docs.rs/waitup/1.0.1/index Shows how to use waitup to wait for multiple services defined in a Docker Compose setup. It configures timeouts, intervals, and connection timeouts for checking service readiness. ```Rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; /// Wait for services defined in docker-compose.yml #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let services = vec![ Target::tcp("postgres", 5432)?, Target::tcp("redis", 6379)?, Target::tcp("elasticsearch", 9200)?, Target::http_url("http://web:8000/health", 200)?, ]; let config = WaitConfig::builder() .timeout(Duration::from_secs(300)) .interval(Duration::from_secs(2)) .max_interval(Duration::from_secs(10)) .connection_timeout(Duration::from_secs(5)) .wait_for_any(false) .build(); println!("Waiting for services to be ready..."); wait_for_connection(&services, &config).await?; println!("All services are ready! Starting application..."); Ok(()) } ``` -------------------------------- ### Rust: Integrate Waitup with Docker Compose Source: https://docs.rs/waitup/1.0.1/waitup/index Shows how to use waitup to wait for multiple services defined in a Docker Compose setup. It configures timeouts, intervals, and connection timeouts for checking service readiness. ```Rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; /// Wait for services defined in docker-compose.yml #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let services = vec![ Target::tcp("postgres", 5432)?, Target::tcp("redis", 6379)?, Target::tcp("elasticsearch", 9200)?, Target::http_url("http://web:8000/health", 200)?, ]; let config = WaitConfig::builder() .timeout(Duration::from_secs(300)) .interval(Duration::from_secs(2)) .max_interval(Duration::from_secs(10)) .connection_timeout(Duration::from_secs(5)) .wait_for_any(false) .build(); println!("Waiting for services to be ready..."); wait_for_connection(&services, &config).await?; println!("All services are ready! Starting application..."); Ok(()) } ``` -------------------------------- ### Get Reference to Result Value in Rust Source: https://docs.rs/waitup/1.0.1/waitup/error/type Shows the `as_ref` method for Rust Results, which converts a `&Result` into a `Result<&T, &E>`. This allows borrowing the contained value without consuming the Result. Examples are provided for both `Ok` and `Err` variants. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Get Mutable Reference to Result Value in Rust Source: https://docs.rs/waitup/1.0.1/waitup/error/type Demonstrates the `as_mut` method for mutable Rust Results, converting `&mut Result` to `Result<&mut T, &mut E>`. This enables in-place modification of the contained `Ok` or `Err` value. Examples show mutation of both variants. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Waitup Macros for Targets and Configurations Source: https://docs.rs/waitup/1.0.1/waitup/macros/index Provides convenience macros for creating targets and configurations within the waitup crate. These macros simplify the process of defining network targets and their associated settings. ```Rust /// Macro for creating HTTP targets. /// /// # Examples /// /// ```rust /// use waitup::http_targets; /// /// let target = http_targets!("http://example.com"); /// ``` #[macro_export] macro_rules! http_targets { ($url:expr) => { $crate::target::Target::Http(vec![$url.to_string()]) }; } /// Macro for creating TCP targets. /// /// # Examples /// /// ```rust /// use waitup::tcp_targets; /// /// let target = tcp_targets!("localhost:8080"); /// ``` #[macro_export] macro_rules! tcp_targets { ($addr:expr) => { $crate::target::Target::Tcp($addr.to_string()) }; } /// Macro for creating a wait configuration. /// /// # Examples /// /// ```rust /// use waitup::wait_config; /// /// let config = wait_config!(timeout: 5000, retries: 3); /// ``` #[macro_export] macro_rules! wait_config { (timeout: $timeout:expr, retries: $retries:expr) => { $crate::config::WaitConfig { timeout: std::time::Duration::from_millis($timeout), retries: $retries, } }; } /// Macro for asserting that a target is ready. /// /// # Examples /// /// ```rust /// use waitup::assert_ready; /// use async_std::task; /// use std::time::Duration; /// /// async fn check_server() -> bool { /// true // Simulate a successful check /// } /// /// task::spawn(async { /// assert_ready!(check_server(), timeout: 1000); /// }); /// ``` #[macro_export] macro_rules! assert_ready { ($check:expr, timeout: $timeout:expr) => { { let timeout_duration = std::time::Duration::from_millis($timeout); let start_time = std::time::Instant::now(); while start_time.elapsed() < timeout_duration { if $check { break; } tokio::time::sleep(std::time::Duration::from_millis(100)).await; } assert!($check, "Target did not become ready within the specified timeout."); } }; } /// Macro for checking if a target is ready. /// /// # Examples /// /// ```rust /// use waitup::check_ready; /// /// async fn is_service_available() -> bool { /// true // Simulate service availability /// } /// /// let ready = check_ready!(is_service_available()); /// ``` #[macro_export] macro_rules! check_ready { ($check:expr) => { $check }; } /// Macro for creating common port configurations. /// /// # Examples /// /// ```rust /// use waitup::common_ports; /// /// let http_port = common_ports!("http"); /// let https_port = common_ports!("https"); /// ``` #[macro_export] macro_rules! common_ports { ("http") => { 80 }; ("https") => { 443 }; ($port:expr) => { $port }; } /// Macro for lazy formatting of strings. /// /// # Examples /// /// ```rust /// use waitup::lazy_format; /// /// let message = lazy_format!("Processing item: {}", 123); /// ``` #[macro_export] macro_rules! lazy_format { ($($arg:tt)*) => { format!($($arg)*) }; } /// Macro to handle zero allocation errors. /// /// # Examples /// /// ```rust /// use waitup::zero_alloc_error; /// /// zero_alloc_error!("An error occurred"); /// ``` #[macro_export] macro_rules! zero_alloc_error { ($msg:expr) => { eprintln!("Zero alloc error: {}", $msg); }; } ``` -------------------------------- ### Create HTTP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/index Defines HTTP targets using a concise syntax for easier configuration. ```rust http_targets Create HTTP targets from a compact syntax. ``` -------------------------------- ### Rust Method to Get ValidatedPort Value Source: https://docs.rs/waitup/1.0.1/waitup/zero_cost/type A constant function 'get' that returns the validated port number. It is part of the 'ValidatedPort' implementation and provides access to the stored port value. ```Rust pub const fn get(&self) -> u16 ``` -------------------------------- ### Create TCP Targets (Rust) Source: https://docs.rs/waitup/1.0.1/src/waitup/target Demonstrates creating TCP targets using the Target::tcp and Target::localhost methods. It shows how to specify hostnames and ports for direct socket connections. ```Rust use waitup::Target; use url::Url; // Create TCP targets let db = Target::tcp("database.example.com", 5432)?; let localhost_api = Target::localhost(8080)?; // Create HTTP targets let health_check = Target::http_url("https://api.example.com/health", 200)?; let status_page = Target::http( Url::parse("https://status.example.com")?, 200 )?; # Ok::<(), waitup::WaitForError>(()) ``` -------------------------------- ### Get Hostname as String Slice (Rust) Source: https://docs.rs/waitup/1.0.1/src/waitup/types Returns the hostname as a string slice. ```Rust pub fn as_str(&self) -> &str { &self.0 } ``` -------------------------------- ### LinearBackoffStrategy: Get Strategy Name Source: https://docs.rs/waitup/1.0.1/src/waitup/async_traits Returns the static name of the linear backoff retry strategy. ```Rust impl AsyncRetryStrategy for LinearBackoffStrategy { // ... other methods ... #[inline] fn name(&self) -> &'static str { "linear_backoff" } } ``` -------------------------------- ### Create HTTP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/waitup/index Defines HTTP targets using a concise syntax for easier configuration. ```rust http_targets Create HTTP targets from a compact syntax. ``` -------------------------------- ### ExponentialBackoffStrategy: Get Strategy Name Source: https://docs.rs/waitup/1.0.1/src/waitup/async_traits Returns the static name of the exponential backoff retry strategy. ```Rust impl ExponentialBackoffStrategy { // ... other methods ... #[inline] fn name(&self) -> &'static str { "exponential_backoff" } } ``` -------------------------------- ### Get Inner Duration from ValidatedDuration Source: https://docs.rs/waitup/1.0.1/waitup/types/struct Retrieves the underlying standard Rust Duration object from a ValidatedDuration instance. ```Rust pub const fn get(&self) -> Duration ``` -------------------------------- ### Create TCP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/index Defines TCP targets using a concise syntax for easier configuration. ```rust tcp_targets Create TCP targets from a compact syntax. ``` -------------------------------- ### Rust Result iter Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Returns an iterator that yields the Ok value if present, otherwise yields nothing. ```Rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Create TCP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/waitup/index Defines TCP targets using a concise syntax for easier configuration. ```rust tcp_targets Create TCP targets from a compact syntax. ``` -------------------------------- ### Get TypeId of a Value Source: https://docs.rs/waitup/1.0.1/waitup/types/struct The `type_id` method returns the `TypeId` of a value, which is a unique identifier for the type at runtime. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Create HTTP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/waitup Defines HTTP targets using a concise syntax for easier configuration. ```rust http_targets Create HTTP targets from a compact syntax. ``` -------------------------------- ### Converting to String with ToString in Rust Source: https://docs.rs/waitup/1.0.1/waitup/iterators/struct Converts a value implementing the `Display` trait into a `String`. This is a standard way to get a string representation of a type. ```Rust impl ToString for T where T: Display + ?Sized, ``` -------------------------------- ### Configure Complex Targets with Builders Source: https://docs.rs/waitup/1.0.1/waitup/target/index Illustrates using builder patterns for advanced target configurations, such as setting custom headers, authentication, and specific port validation for HTTP and TCP targets. ```Rust use waitup::Target; use url::Url; // HTTP target with custom headers let api_target = Target::http_builder(Url::parse("https://api.example.com/protected")?) .status(201) .auth_bearer("your-api-token") .content_type("application/json") .header("X-Custom-Header", "custom-value") .build()?; // TCP target with specific port type validation let service = Target::tcp_builder("service.example.com")? .registered_port(8080) .build()?; ``` -------------------------------- ### Rust Result iter_mut Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Returns a mutable iterator that yields a mutable reference to the Ok value if present, otherwise yields nothing. ```Rust let mut x: Result = Ok(7); assert_eq!(x.iter_mut().next(), Some(&mut 7)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Rust Result as_deref Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Converts a Result to Result<&::Target, &E> by coercing the Ok variant via Deref. ```Rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Rust Result map_err Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Maps an Err value to a new error type by applying a function, leaving Ok values unchanged. ```Rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Rust Result map_or Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Maps a Result to a default value if Err, or applies a function to the Ok value. Arguments are eagerly evaluated. ```Rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Create HTTP Targets with Builders (Rust) Source: https://docs.rs/waitup/1.0.1/src/waitup/target Illustrates using the builder pattern to configure HTTP targets with custom headers, authentication, and specific status codes. Also shows TCP target configuration with registered ports. ```Rust use waitup::Target; use url::Url; // HTTP target with custom headers let api_target = Target::http_builder(Url::parse("https://api.example.com/protected")?) .status(201) .auth_bearer("your-api-token") .content_type("application/json") .header("X-Custom-Header", "custom-value") .build()?; // TCP target with specific port type validation let service = Target::tcp_builder("service.example.com")? .registered_port(8080) .build()?; # Ok::<(), waitup::WaitForError>(()) ``` -------------------------------- ### Rust: Get Port Value Source: https://docs.rs/waitup/1.0.1/src/waitup/types Provides a method to retrieve the inner `u16` value from a `Port` struct. This allows accessing the port number for further use. ```Rust /// Get the inner port value #[must_use] pub const fn get(&self) -> u16 { self.0.get() } ``` -------------------------------- ### Rust Result inspect_err Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Calls a closure with a reference to the Err value without modifying the Result. Useful for handling errors with side effects. ```Rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Create Basic TCP and HTTP Targets Source: https://docs.rs/waitup/1.0.1/waitup/target/index Demonstrates the creation of basic TCP and HTTP targets using the Target enum. This includes direct socket connections and HTTP requests with status code validation. ```Rust use waitup::Target; use url::Url; // Create TCP targets let db = Target::tcp("database.example.com", 5432)?; let localhost_api = Target::localhost(8080)?; // Create HTTP targets let health_check = Target::http_url("https://api.example.com/health", 200)?; let status_page = Target::http( Url::parse("https://status.example.com")?, 200 )?; ``` -------------------------------- ### Rust Result inspect Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Calls a closure with a reference to the Ok value without modifying the Result. Useful for side effects like logging. ```Rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Rust Result map_or_default Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Maps an Ok value using a function or returns the default value of the type if Err. This is a nightly-only experimental API. ```Rust #![feature(result_option_map_or_default)] let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Test Target Convenience Constructors Source: https://docs.rs/waitup/1.0.1/src/waitup/lib Tests the convenience constructor methods for `Target`, including `localhost`, `loopback`, and `loopback_v6`, with specified ports. It asserts that the created `Target` objects have the correct hostname and port. ```rust #[test] fn test_target_convenience_constructors() { let localhost_target = Target::localhost(8080).unwrap(); assert_eq!(localhost_target.hostname(), "localhost"); assert_eq!(localhost_target.port(), Some(8080)); let loopback_target = Target::loopback(3000).unwrap(); assert_eq!(loopback_target.hostname(), "127.0.0.1"); assert_eq!(loopback_target.port(), Some(3000)); let loopback_v6_target = Target::loopback_v6(9090).unwrap(); assert_eq!(loopback_v6_target.hostname(), "::1"); assert_eq!(loopback_v6_target.port(), Some(9090)); } ``` -------------------------------- ### Rust Result map_or_else Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Maps a Result to a value by applying a fallback function for Err or a mapping function for Ok. Useful for lazy evaluation. ```Rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### Create HTTP Target Builder (Rust) Source: https://docs.rs/waitup/1.0.1/src/waitup/target Creates a builder for configuring HTTP targets. This allows for a more fluent and step-by-step construction of HTTP target configurations, including setting the URL, expected status, and headers. ```Rust pub fn http_builder(url: Url) -> HttpTargetBuilder { HttpTargetBuilder::new(url) } ``` -------------------------------- ### Quick Start: Add waitup to Cargo.toml Source: https://docs.rs/waitup/1.0.1/waitup This snippet shows how to add the waitup crate and its Tokio dependency to your Cargo.toml file for a Rust project. ```toml [dependencies] waitup = "1.0" tokio = { version = "1.0", features = ["full"] } ``` -------------------------------- ### Test TCP Builder Fluent Interface Source: https://docs.rs/waitup/1.0.1/src/waitup/lib Tests the fluent interface of the `Target::tcp_builder`. It demonstrates chaining methods like `registered_port` and `build` to construct a `Target` object and asserts that the hostname and port are set correctly. ```rust #[test] fn test_tcp_builder_fluent_interface() { // Test that builder methods return Self for fluent chaining let target = Target::tcp_builder("example.com") .unwrap() .registered_port(8080) .build() .unwrap(); assert_eq!(target.hostname(), "example.com"); assert_eq!(target.port(), Some(8080)); } ``` -------------------------------- ### Rust Waitup Basic Configuration Source: https://docs.rs/waitup/1.0.1/src/waitup/config Demonstrates basic configuration of WaitConfig using the builder pattern, setting a total timeout and an initial retry interval. ```Rust use waitup::WaitConfig; use std::time::Duration; let config = WaitConfig::builder() .timeout(Duration::from_secs(30)) .interval(Duration::from_secs(1)) .build(); ``` -------------------------------- ### Rust Result Iteration Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Demonstrates iterating over a mutable reference to the value within a Result, modifying it if it's Ok, and handling the None case for Err. ```Rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Parameterized TCP Target Creation Tests Source: https://docs.rs/waitup/1.0.1/src/waitup/lib Uses the `test-case` crate to run parameterized tests for creating TCP targets with various common hostnames and ports (HTTP, HTTPS, SSH, PostgreSQL). It asserts that the target is correctly created and matches the expected host and port. ```Rust #[test_case("localhost", 80; "http port")] #[test_case("example.com", 443; "https port")] #[test_case("127.0.0.1", 22; "ssh port")] #[test_case("db.example.com", 5432; "postgres port")] fn test_tcp_target_creation(hostname: &str, port: u16) { let target = Target::tcp(hostname, port).unwrap(); match target { Target::Tcp { host, port: p } => { assert_eq!(host.as_str(), hostname); assert_eq!(p.get(), port); } _ => panic!("Expected TCP target"), } } ``` -------------------------------- ### Create Development-Friendly SecurityValidator Source: https://docs.rs/waitup/1.0.1/waitup/security/struct Illustrates creating a `SecurityValidator` with more lenient settings, suitable for development and testing. ```Rust impl SecurityValidator { pub fn development() -> Self } ``` -------------------------------- ### Rust: Get Value or Default with unwrap_or Source: https://docs.rs/waitup/1.0.1/waitup/error/type The `unwrap_or` method returns the contained Ok value or a provided default if the Result is Err. The default value is eagerly evaluated. ```Rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Basic waitup Configuration Source: https://docs.rs/waitup/1.0.1/waitup/config/index Demonstrates how to create a basic WaitConfig with a total timeout and a fixed interval. This is useful for simple readiness checks. ```Rust use waitup::WaitConfig; use std::time::Duration; let config = WaitConfig::builder() .timeout(Duration::from_secs(30)) .interval(Duration::from_secs(1)) .build(); ``` -------------------------------- ### Rust Result as_deref_mut Example Source: https://docs.rs/waitup/1.0.1/waitup/error/type Converts a mutable Result to Result<&mut ::Target, &mut E> by coercing the Ok variant via DerefMut. ```Rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### Create Wait Configuration (Rust) Source: https://docs.rs/waitup/1.0.1/index Constructs a wait configuration using a compact and user-friendly syntax. ```rust wait_config Create a wait configuration with a compact syntax. ``` -------------------------------- ### Check if Result is Ok in Rust Source: https://docs.rs/waitup/1.0.1/waitup/error/type Provides examples of the `is_ok` method for Rust's Result type. It returns `true` if the Result is the `Ok` variant and `false` otherwise. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Create Production-Ready SecurityValidator Source: https://docs.rs/waitup/1.0.1/waitup/security/struct Shows how to create a `SecurityValidator` with strict security settings suitable for production environments. ```Rust impl SecurityValidator { pub fn production() -> Self } ``` -------------------------------- ### Create Wait Configuration (Rust) Source: https://docs.rs/waitup/1.0.1/waitup/index Constructs a wait configuration using a compact and user-friendly syntax. ```rust wait_config Create a wait configuration with a compact syntax. ``` -------------------------------- ### Rust: Get Failed Results from TargetResults Slice Source: https://docs.rs/waitup/1.0.1/src/waitup/iterators Returns an iterator over references to `TargetResult` items within a slice that are marked as failed. This enables focused analysis of unsuccessful operations. ```Rust pub trait TargetResultSliceExt { // ... other methods /// Get failed results fn failed_results(&self) -> impl Iterator; // ... other methods } impl TargetResultSliceExt for [TargetResult] { // ... other methods fn failed_results(&self) -> impl Iterator { self.iter().filter(|r| !r.success) } // ... other methods } ``` -------------------------------- ### Build Wait Configuration (Rust) Source: https://docs.rs/waitup/1.0.1/src/waitup/lib Demonstrates the usage of the `WaitConfig::builder` to construct a `WaitConfig` object with custom settings for timeout, interval, max interval, wait for any, and max retries. ```rust use super::*; use proptest::prelude::*; use std::time::Duration; use test_case::test_case; use url::Url; #[test] fn test_wait_config_builder() { let config = WaitConfig::builder() .timeout(Duration::from_secs(60)) .interval(Duration::from_secs(2)) .max_interval(Duration::from_secs(30)) .wait_for_any(true) .max_retries(Some(10)) .build(); assert_eq!(config.timeout, Duration::from_secs(60)); assert_eq!(config.initial_interval, Duration::from_secs(2)); assert_eq!(config.max_interval, Duration::from_secs(30)); } ``` -------------------------------- ### Rust: Get Successful Results from TargetResults Slice Source: https://docs.rs/waitup/1.0.1/src/waitup/iterators Returns an iterator over references to `TargetResult` items within a slice that are marked as successful. This allows for focused processing of successful outcomes. ```Rust pub trait TargetResultSliceExt { // ... other methods /// Get successful results fn successful_results(&self) -> impl Iterator; // ... other methods } impl TargetResultSliceExt for [TargetResult] { // ... other methods fn successful_results(&self) -> impl Iterator { self.iter().filter(|r| r.success) } // ... other methods } ``` -------------------------------- ### Rust: Get Fastest Target Result Source: https://docs.rs/waitup/1.0.1/src/waitup/iterators Finds and returns the `TargetResult` with the minimum `elapsed` time from an iterator. Returns `None` if the iterator is empty. Useful for identifying the quickest operations. ```Rust pub trait TargetResultIterExt: Iterator { // ... other methods /// Get the fastest result (lowest elapsed time) fn fastest(self) -> Option where Self: Sized, { self.min_by_key(|result| result.elapsed) } // ... other methods ``` -------------------------------- ### Create TCP Targets from Compact Syntax (Rust) Source: https://docs.rs/waitup/1.0.1/waitup Defines TCP targets using a concise syntax for easier configuration. ```rust tcp_targets Create TCP targets from a compact syntax. ``` -------------------------------- ### Create Wait Configuration (Rust) Source: https://docs.rs/waitup/1.0.1/waitup Constructs a wait configuration using a compact and user-friendly syntax. ```rust wait_config Create a wait configuration with a compact syntax. ``` -------------------------------- ### Rust: Get Slowest Target Result Source: https://docs.rs/waitup/1.0.1/src/waitup/iterators Finds and returns the `TargetResult` with the maximum `elapsed` time from an iterator. Returns `None` if the iterator is empty. Useful for identifying the longest-running operations. ```Rust pub trait TargetResultIterExt: Iterator { // ... other methods /// Get the slowest result (highest elapsed time) fn slowest(self) -> Option where Self: Sized, { self.max_by_key(|result| result.elapsed) } // ... other methods ``` -------------------------------- ### waitup Macros Source: https://docs.rs/waitup/1.0.1/waitup/presets/index This section lists various macros provided by the waitup crate, such as assert_ready, check_ready, common_ports, http_targets, lazy_format, tcp_targets, wait_config, and zero_alloc_error. These macros likely assist in various aspects of network waiting and configuration. ```Rust assert_ready check_ready common_ports http_targets lazy_format tcp_targets wait_config zero_alloc_error ``` -------------------------------- ### Rust: Get Value or Compute Default with unwrap_or_else Source: https://docs.rs/waitup/1.0.1/waitup/error/type The `unwrap_or_else` method returns the contained Ok value or computes it from a closure if the Result is Err. This allows for lazy evaluation of the default value. ```Rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Test TCP Target Creation Source: https://docs.rs/waitup/1.0.1/src/waitup/lib Tests the creation of TCP targets using `Target::tcp`. It validates that valid hostname and port combinations result in a successful target creation and that the host and port are correctly stored. ```Rust proptest! { #[test] fn test_target_tcp_creation( hostname in "[a-zA-Z0-9][a-zA-Z0-9\-]{0,30}[a-zA-Z0-9]", port in 1u16..=65535 ) { let result = Target::tcp(hostname, port); assert!(result.is_ok()); } } ``` -------------------------------- ### Rust: Get Summary Statistics Source: https://docs.rs/waitup/1.0.1/src/waitup/iterators Calculates and returns summary statistics for a collection of target results. It includes counts of successful and failed targets, total attempts, and the fastest/slowest response times. ```Rust /// Get summary statistics #[must_use] pub fn summary(&self) -> ResultSummary { let successful_count = self.successful_results().count(); let failed_count = self.failed_results().count(); let total_attempts = self.target_results.iter().map(|r| r.attempts).sum(); let fastest = self .target_results .iter() .filter(|r| r.success) .min_by_key(|r| r.elapsed) .map(|r| r.elapsed); let slowest = self .target_results .iter() .max_by_key(|r| r.elapsed) .map(|r| r.elapsed); ResultSummary { total_targets: self.target_results.len(), successful_count, failed_count, total_attempts, total_elapsed: self.elapsed, fastest_response: fastest, slowest_response: slowest, } } ``` -------------------------------- ### Rust Macros for Waitup Crate Source: https://docs.rs/waitup/1.0.1/waitup/zero_cost/index This snippet lists various macros provided by the waitup crate. These macros are likely used for assertion, checking readiness, defining common ports, HTTP targets, TCP targets, and configuration within the crate's zero-cost abstraction framework. ```Rust assert_ready check_ready common_ports http_targets lazy_format tcp_targets wait_config zero_alloc_error ``` -------------------------------- ### Rust: Configure Waitup with Cancellation Source: https://docs.rs/waitup/1.0.1/waitup Demonstrates how to configure waitup with a timeout, interval, and a cancellation token. The example shows how to spawn a task to cancel the wait operation after a specified duration. ```Rust use waitup::{Target, WaitConfig, wait_for_connection}; use std::time::Duration; use tokio::time::sleep; #[tokio::main] async fn main() -> Result<(), waitup::WaitForError> { let target = Target::tcp("slow-service", 8080)?; let (builder, cancel_token) = WaitConfig::builder() .timeout(Duration::from_secs(60)) .interval(Duration::from_millis(500)) .with_cancellation(); let config = builder.build(); // Cancel after 10 seconds let cancel_handle = { let token = cancel_token.clone(); tokio::spawn(async move { sleep(Duration::from_secs(10)).await; token.cancel(); }) }; match wait_for_connection(&[target], &config).await { Ok(_) => println!("Service is ready!"), Err(waitup::WaitForError::Cancelled) => println!("Operation was cancelled"), Err(e) => println!("Error: {}", e), } cancel_handle.abort(); // Clean up the cancel task Ok(()) } ``` -------------------------------- ### Rust: Policy OR Operation Source: https://docs.rs/waitup/1.0.1/waitup/config/struct Creates a new Policy that returns Action::Follow if either self or other policies return Action::Follow. ```Rust fn or(self, other: P) -> Or where T: Policy, P: Policy ``` -------------------------------- ### Create Common Port Configurations (Rust) Source: https://docs.rs/waitup/1.0.1/index Generates common port configurations for network services. ```rust common_ports Create common port configurations. ```