### Complete ConnectionGuard Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Demonstrates the basic usage of Pool and ConnectionGuard, including getting a connection, using it, and observing pool state changes. The connection is automatically returned to the pool when the guard is dropped. ```rust use fast_pool::{Manager, Pool, ConnectionGuard}; use std::ops::{Deref, DerefMut}; #[derive(Debug)] pub struct MyManager; impl Manager for MyManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("conn".to_string()) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { if conn.is_empty() { return Err("connection lost".to_string()); } Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let pool = Pool::new(MyManager); pool.set_max_open(10); // Basic usage { let mut conn = pool.get().await?; println!("Using: {}", conn.deref_mut()); // Connection returned here } // Check state after return let state = pool.state(); println!("Idle connections: {}", state.idle); // Multiple connections let mut connections = vec![]; for _ in 0..5 { let conn = pool.get().await?; connections.push(conn); } let state = pool.state(); println!("In-use connections: {}", state.in_use); // All returned when dropped drop(connections); Ok(()) } ``` -------------------------------- ### Complete Example: DurationManager with Skip Interval Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md A full example demonstrating the DurationManager with a skip interval strategy. It shows connection pool setup, usage, and how the skip interval affects validation timing. ```rust use fast_pool::{Manager, Pool}; use fast_pool::plugin::{DurationManager, CheckMode}; use std::time::Duration; #[derive(Debug)] pub struct DatabaseManager { connection_string: String, } impl DatabaseManager { pub fn new(connection_string: &str) -> Self { Self { connection_string: connection_string.to_string(), } } } impl Manager for DatabaseManager { type Connection = String; // In real code: sqlx::PgConnection type Error = String; async fn connect(&self) -> Result { println!("Creating new connection"); Ok(format!("connection:{}", uuid::Uuid::new_v4())) } async fn check(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> { println!("Validating connection"); Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let base_manager = DatabaseManager::new("postgres://localhost/db"); // Wrap with duration manager: skip validation for 30 seconds let duration_manager = DurationManager::new( base_manager, CheckMode::SkipInterval(Duration::from_secs(30)) ); let pool = Pool::new(duration_manager); pool.set_max_open(20); // First connection: will be validated let conn1 = pool.get().await?; drop(conn1); // Within 30 seconds: skips validation let conn2 = pool.get().await?; drop(conn2); // Wait 31 seconds, then: will re-validate tokio::time::sleep(Duration::from_secs(31)).await; let conn3 = pool.get().await?; drop(conn3); Ok(()) } ``` -------------------------------- ### Full Manager Implementation Example (Postgres) Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/manager-trait.md Provides a complete example of implementing the Manager trait for PostgreSQL connections using sqlx. ```rust use fast_pool::Manager; use sqlx::PgPool; pub struct PostgresManager { connection_string: String, } impl Manager for PostgresManager { type Connection = sqlx::PgConnection; type Error = String; async fn connect(&self) -> Result { sqlx::PgConnection::connect(&self.connection_string) .await .map_err(|e| format!("Connection failed: {}", e)) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { sqlx::query("SELECT 1") .execute(&mut **conn) .await .map(|_| ()) // Map the result to Ok(()) .map_err(|e| format!("Health check failed: {}", e)) } } #[tokio::main] async fn main() -> Result<(), Box> { let manager = PostgresManager { connection_string: "postgres://localhost/mydb".to_string(), }; let pool = fast_pool::Pool::new(manager); pool.set_max_open(20); let mut conn = pool.get().await?; // Use connection Ok(()) } ``` -------------------------------- ### Complete Fast Pool Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Demonstrates the full lifecycle of acquiring and releasing connections, and observing the pool's state changes. This example requires the `fast_pool` and `tokio` crates. ```rust use fast_pool::{Manager, Pool}; use std::time::Duration; #[derive(Debug)] pub struct MyManager; impl Manager for MyManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("conn".to_string()) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let pool = Pool::new(MyManager); pool.set_max_open(20); println!("Initial state: {}", pool.state()); // Acquire multiple connections let mut conns = vec![]; for i in 0..5 { let conn = pool.get().await?; println!("Acquired connection {}: {}", i, pool.state()); conns.push(conn); } // All in use let state = pool.state(); println!("All acquired: {}", state); assert_eq!(state.in_use, 5); // Release one drop(conns.pop()); println!("After dropping one: {}", pool.state()); // Release all drop(conns); println!("All returned: {}", pool.state()); Ok(()) } ``` -------------------------------- ### DurationManager Initialization Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Example of how to create and configure a DurationManager with a SkipInterval check mode and integrate it into a Pool. ```rust use fast_pool::plugin::{DurationManager, CheckMode}; use std::time::Duration; let manager = MyManager; let duration_manager = DurationManager::new( manager, CheckMode::SkipInterval(Duration::from_secs(30)) ); let pool = Pool::new(duration_manager); ``` -------------------------------- ### Example: Implementing connect() for MyManager Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/manager-trait.md Demonstrates how to implement the `connect` method for a custom manager, returning a new database connection. ```rust impl Manager for MyManager { type Connection = DatabaseConnection; type Error = String; async fn connect(&self) -> Result { DatabaseConnection::new("server:5432") .await .map_err(|e| e.to_string()) } } ``` -------------------------------- ### connect() Method Example: Database Connection Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Implementation of the `connect` method for a PostgreSQL database connection using sqlx. ```rust #[derive(Debug)] struct DatabaseManager { connection_string: String, } impl Manager for DatabaseManager { type Connection = sqlx::PgConnection; type Error = String; async fn connect(&self) -> Result { sqlx::PgConnection::connect(&self.connection_string) .await .map_err(|e| format!("Connection failed: {}", e)) } } ``` -------------------------------- ### Handling Connection Acquisition Timeout Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/error-handling.md Example of attempting to get a connection with a specified timeout and the expected error format. ```Rust let conn = pool.get_timeout(Some(Duration::from_secs(5))).await; // Error: Err(String::from("get_timeout")) ``` -------------------------------- ### connect() Method Example: String Connection Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md A minimal implementation of the `connect` method for a String connection type. ```rust impl Manager for StringManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("connection".to_string()) // Minimal implementation } } ``` -------------------------------- ### Simple In-Memory Pool Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Demonstrates setting up and using a connection pool with a custom in-memory manager that generates unique connection IDs. ```Rust use fast_pool::Manager; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; #[derive(Debug)] struct CountingManager { counter: Arc, } impl Manager for CountingManager { type Connection = u64; type Error = String; async fn connect(&self) -> Result { Ok(self.counter.fetch_add(1, Ordering::SeqCst)) } async fn check(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> { Ok(()) // Connection IDs are always valid } } #[tokio::main] async fn main() -> Result<(), Box> { let manager = CountingManager { counter: Arc::new(AtomicU64::new(0)), }; let pool = fast_pool::Pool::new(manager); pool.set_max_open(5); for _ in 0..10 { let conn = pool.get().await?; println!("Got connection: {}", *conn); } Ok(()) } ``` -------------------------------- ### Complete Fast Pool Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/pool.md Demonstrates the full lifecycle of using fast_pool, including creating a custom manager, configuring pool settings, and acquiring connections. ```rust use fast_pool::{Manager, Pool}; use std::ops::DerefMut; use std::time::Duration; #[derive(Debug)] pub struct MyManager; impl Manager for MyManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("connection".to_string()) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { if conn.is_empty() { return Err("invalid connection".to_string()); } Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let pool = Pool::new(MyManager); // Configure pool pool.set_max_open(20); pool.set_max_idle_conns(10); pool.set_timeout_check(Some(Duration::from_secs(5))); pool.set_timeout_wait(Some(Duration::from_secs(10))); // Check state println!("State: {}", pool.state()); // Acquire connection with default timeout let mut conn = pool.get().await?; println!("Connection: {}", conn.deref_mut()); // Acquire with custom timeout let mut conn = pool.get_timeout(Some(Duration::from_secs(5))).await?; println!("Connection: {}", conn.deref_mut()); // Connection automatically returned on drop Ok(()) } ``` -------------------------------- ### Detect Connection Churn Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Example demonstrating how to detect connection churn by comparing pool states over a short interval. ```rust let state1 = pool.state(); tokio::time::sleep(Duration::from_secs(1)).await; let state2 = pool.state(); if state2.connections > state1.connections { println!("New connections being created"); } ``` -------------------------------- ### Connection Type Examples Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Examples of defining the associated 'Connection' type for the Manager trait. Choose a type that represents your resource. ```rust type Connection = String; // Simple type ``` ```rust type Connection = sqlx::PgConnection; // Real database connection ``` ```rust type Connection = tokio::net::TcpStream; // Network socket ``` ```rust type Connection = Arc>; // Wrapped connection ``` ```rust struct CustomConnection { inner: RealConnection, created_at: Instant, } type Connection = CustomConnection; // Custom wrapper ``` -------------------------------- ### Example: Implementing check() for MyManager Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/manager-trait.md Shows how to implement the `check` method for a custom manager to validate an existing connection using a ping operation. ```rust impl Manager for MyManager { async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { conn.ping() .await .map_err(|e| e.to_string()) } } ``` -------------------------------- ### connect() Method Example: HTTP Client Connection Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Implementation of the `connect` method for creating a reqwest HTTP client. Clients are typically cheap to create. ```rust #[derive(Debug)] struct HttpClientManager; impl Manager for HttpClientManager { type Connection = reqwest::Client; type Error = String; async fn connect(&self) -> Result { Ok(reqwest::Client::new()) // Client is cheap to create } } ``` -------------------------------- ### DurationConnection Deref and DerefMut Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Example demonstrating how to access and modify the inner connection of a DurationConnection using Deref and DerefMut traits. ```rust let mut conn = pool.get().await?; // conn is DurationConnection let inner: &String = &*conn; // Deref access *conn = "modified".to_string(); // DerefMut access ``` -------------------------------- ### State Display Format Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/types.md Illustrates the default display format for the State struct, showing the pool's current metrics. ```rust { max_open: 32, connections: 10, in_use: 5, idle: 5, connecting: 0, checking: 0, waits: 0 } ``` -------------------------------- ### Monitor Active Usage Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Example of monitoring the current active, idle, and total connections in the pool. ```rust let state = pool.state(); println!("Active: {}", state.in_use); println!("Idle: {}", state.idle); println!("Total: {}", state.connections); ``` -------------------------------- ### HTTP Client Connection Check Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Example for an HTTP client manager where connection validation is not needed as each request establishes its own connection. ```Rust impl Manager for HttpClientManager { async fn check(&self, _conn: &mut reqwest::Client) -> Result<(), String> { // HTTP clients don't need connection validation // (each request establishes its own connection) Ok(()) } } ``` -------------------------------- ### TCP Socket Pool Example Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Illustrates creating a connection pool for TCP sockets, including implementing `connect` and `check` methods for `tokio::net::TcpStream`. ```Rust use fast_pool::Manager; use tokio::net::TcpStream; use std::net::SocketAddr; #[derive(Debug, Clone)] struct TcpManager { address: SocketAddr, } impl Manager for TcpManager { type Connection = TcpStream; type Error = String; async fn connect(&self) -> Result { TcpStream::connect(self.address) .await .map_err(|e| e.to_string()) } async fn check(&self, conn: &mut TcpStream) -> Result<(), Self::Error> { // Test if socket is still connected conn.readable() .await .map_err(|e| format!("socket check failed: {}", e))?; Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let manager = TcpManager { address: "127.0.0.1:8080".parse()?, }; let pool = fast_pool::Pool::new(manager); pool.set_max_open(50); let mut conn = pool.get().await?; // Use TcpStream Ok(()) } ``` -------------------------------- ### String Connection Check Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Example of implementing the `check` method for a simple string-based connection manager. This checks if the connection string is empty. ```Rust impl Manager for StringManager { async fn check(&self, conn: &mut String) -> Result<(), String> { if conn.is_empty() { Err("connection lost".to_string()) } else { Ok(()) } } } ``` -------------------------------- ### Database Connection Check Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Example of implementing the `check` method for a database connection manager using sqlx. It performs a simple query to validate the connection. ```Rust impl Manager for DatabaseManager { async fn check(&self, conn: &mut sqlx::PgConnection) -> Result<(), String> { sqlx::query("SELECT 1") .execute(conn) .await .map(|_| ()) // Map the result to Ok(()) .map_err(|e| format!("Health check failed: {}", e)) } } ``` -------------------------------- ### Periodic Monitoring Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Example of setting up a periodic task to monitor and log the pool's state, including alerts for high wait times. ```rust tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(10)); loop { interval.tick().await; let state = pool.state(); println!("Pool state: {}", state); if state.waits > 5 { eprintln!("Alert: {} goroutines waiting!", state.waits); } } }); ``` -------------------------------- ### Database Connection Check with Timeout Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Example of implementing a `check` method with a timeout for database connections to prevent long-running validation queries. ```Rust impl Manager for DatabaseManager { async fn check(&self, conn: &mut sqlx::PgConnection) -> Result<(), String> { tokio::time::timeout( Duration::from_secs(2), sqlx::query("SELECT 1").execute(&mut *conn) ) .await .map_err(|_| "health check timeout".to_string())? // Handle timeout error .map(|_| ()) // Map the successful execution result .map_err(|e| format!("health check failed: {}", e)) // Map the query execution error } } ``` -------------------------------- ### Set and Get Max Open Connections Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Configure and retrieve the maximum number of connections the pool can simultaneously hold. ```rust pool.set_max_open(100); let max = pool.get_max_open(); ``` -------------------------------- ### Acquire Connection from Pool Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Get a connection from the pool. The connection is automatically returned when it goes out of scope. ```rust let mut conn = pool.get().await?; // Use connection ``` -------------------------------- ### Set and Get Max Idle Connections Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Configure and retrieve the maximum number of idle connections to keep in the pool. ```rust pool.set_max_idle_conns(20); let max = pool.get_max_idle_conns(); ``` -------------------------------- ### Set and Get Connection Wait Timeout Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Configure and retrieve the timeout duration for waiting to acquire a connection. ```rust pool.set_timeout_wait(Some(Duration::from_secs(10))); let timeout = pool.get_timeout_wait(); ``` -------------------------------- ### Set Maximum Safety Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Configure the connection pool for maximum safety by setting limits on open connections, idle connections, and timeouts. This example demonstrates setting these parameters programmatically. ```rust pool.set_max_open(50); pool.set_max_idle_conns(10); pool.set_timeout_check(Some(Duration::from_secs(10))); pool.set_timeout_wait(Some(Duration::from_secs(30))); let manager = DurationManager::new( base_manager, CheckMode::NoLimit ); ``` -------------------------------- ### Instrumented Pool Get Operation Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/error-handling.md This Rust function demonstrates how to instrument the `pool.get().await` operation. It logs the time elapsed and the pool's state (connections in use) before and after attempting to acquire a connection. This is useful for monitoring pool performance and identifying potential bottlenecks. ```rust async fn instrumented_get(pool: &Pool) -> Result, String> { let start = Instant::now(); let state_before = pool.state(); match pool.get().await { Ok(conn) => { let state_after = pool.state(); eprintln!( "get() succeeded in {:?} (in_use: {} → {})", start.elapsed(), state_before.in_use, state_after.in_use ); Ok(conn) } Err(e) => { let state_after = pool.state(); eprintln!( "get() failed after {:?}: {} (state: {}, {})", start.elapsed(), e, state_before.connections, state_after.connections ); Err(e) } } } ``` -------------------------------- ### Monitor Pool State Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Retrieve and print the current state of the connection pool, including connection counts and wait times. This example also shows how to access the specific check mode of a DurationManager. ```rust let state = pool.state(); println!("Connections: {}", state.connections); println!("In use: {}", state.in_use); println!("Idle: {}", state.idle); println!("Waiting: {}", state.waits); println!("Check mode: {:?}", pool.downcast_manager::>()?.mode.get_mode()); ``` -------------------------------- ### Error Type Examples Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Examples of defining the associated 'Error' type for the Manager trait. It must implement `From<&'a str>`. ```rust type Error = String; // Simplest option ``` ```rust #[derive(Debug)] enum PoolError { ConnectionFailed(String), ValidationFailed(String), } impl From<&str> for PoolError { fn from(s: &str) -> Self { PoolError::ConnectionFailed(s.to_string()) } } type Error = PoolError; // Domain error enum ``` -------------------------------- ### Simple Pool Creation and Usage Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Demonstrates how to create a basic connection pool with a custom manager and retrieve a connection. Ensure tokio is set up as the async runtime. ```rust use fast_pool::{Manager, Pool}; #[derive(Debug)] struct SimpleManager; impl Manager for SimpleManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("connection".to_string()) } async fn check(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> { Ok(()) } } #[tokio::main] async fn main() -> Result<(), Box> { let pool = Pool::new(SimpleManager); pool.set_max_open(10); let conn = pool.get().await?; println!("Connection: {}", conn); Ok(()) } ``` -------------------------------- ### Custom Connection Initialization Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Demonstrates how to initialize a connection with specific settings upon creation within a custom Manager implementation. ```rust pub struct InitializedConnection { inner: RawConnection, initialized: bool, } impl Manager for MyManager { type Connection = InitializedConnection; type Error = String; async fn connect(&self) -> Result { let inner = RawConnection::new().await?; // Initialize connection inner.execute("SET search_path = public").await?; inner.execute("SET client_encoding = UTF8").await?; Ok(InitializedConnection { inner, initialized: true, }) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { if !conn.initialized { return Err("connection not initialized".to_string()); } conn.inner.ping().await.map_err(|e| e.to_string()) } } ``` -------------------------------- ### Set and Get Connection Check Timeout Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Configure and retrieve the timeout duration for validating connections. ```rust pool.set_timeout_check(Some(Duration::from_secs(5))); let timeout = pool.get_timeout_check(); ``` -------------------------------- ### Pool Creation with Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Initialize a connection pool with specific configuration settings for maximum connections, idle connections, and timeouts. ```rust let pool = Pool::new(MyManager {}); pool.set_max_open(100); pool.set_max_idle_conns(20); pool.set_timeout_check(Some(Duration::from_secs(5))); pool.set_timeout_wait(Some(Duration::from_secs(10))); ``` -------------------------------- ### Basic fast_pool Usage with Custom Manager Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Demonstrates how to implement the Manager trait, create a pool, and acquire a connection. The connection is automatically returned to the pool when the ConnectionGuard is dropped. ```rust use fast_pool::{Manager, Pool}; use std::time::Duration; // 1. Implement Manager trait for your connection type #[derive(Debug)] struct MyManager; impl Manager for MyManager { type Connection = String; // Your connection type type Error = String; // Your error type async fn connect(&self) -> Result { Ok("connection".to_string()) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { Ok(()) } } // 2. Create and configure pool #[tokio::main] async fn main() -> Result<(), Box> { let pool = Pool::new(MyManager); pool.set_max_open(20); // 3. Acquire connections let mut conn = pool.get().await?; println!("Connection: {}", conn); // Connection automatically returned on drop Ok(()) } ``` -------------------------------- ### Basic ConnectionGuard Usage Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Illustrates the fundamental usage of ConnectionGuard, acquiring a connection, using it via Deref/DerefMut, and relying on automatic return to the pool upon scope exit. ```rust let mut conn = pool.get().await?; // Use connection via Deref/DerefMut let result = conn.execute_query().await?; // Automatically returned to pool on drop ``` -------------------------------- ### Check Overall Pool Health Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Example of checking the pool's overall health by monitoring waiting goroutines and capacity. ```rust let state = pool.state(); if state.waits > 0 { println!("Pool is under pressure: {} goroutines waiting", state.waits); } if state.connections >= state.max_open { println!("Pool is at capacity"); } ``` -------------------------------- ### Configuration Hierarchy for Pool Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/INDEX.md Details the default configuration applied when creating a Pool and how to further customize it using setter methods. ```text Pool::new(manager) ← Default configuration ├─ max_open: 32 ├─ max_idle: 32 ├─ timeout_check: 10s └─ timeout_wait: 30s Then call set_* methods to customize: ├─ pool.set_max_open() ├─ pool.set_max_idle_conns() ├─ pool.set_timeout_check() └─ pool.set_timeout_wait() For check strategies, wrap manager: └─ DurationManager::new(manager, CheckMode) ``` -------------------------------- ### Get maximum idle connections limit Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/pool.md Retrieve the current limit for the maximum number of idle connections the pool will maintain. ```rust pub fn get_max_idle_conns(&self) -> u64 ``` -------------------------------- ### Common Pool Methods Checklist Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/INDEX.md Highlights frequently used methods on the Pool object for creation, acquisition, state checking, and configuration. ```text - [ ] `Pool::new()` — Create pool - [ ] `Pool::get()` — Acquire connection - [ ] `Pool::state()` — Check metrics - [ ] `Pool::set_max_open()` — Configure - [ ] `Pool::set_timeout_check()` — Set check timeout ``` -------------------------------- ### Get maximum open connections limit Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/pool.md Retrieve the current limit for the maximum number of open connections allowed in the pool. ```rust pub fn get_max_open(&self) -> u64 ``` -------------------------------- ### Get Pool State Information Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Retrieve the current state of the connection pool, including usage, idle, and waiting counts. ```rust let state = pool.state(); println!("{}", state); // Display format // Access fields println!("In use: {}", state.in_use); println!("Idle: {}", state.idle); println!("Waiting: {}", state.waits); println!("Max: {}", state.max_open); ``` -------------------------------- ### Balanced Production Pool Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Recommended settings for a balanced production environment, optimizing for a mix of performance, resource usage, and connection freshness. ```rust pool.set_max_open(100); pool.set_max_idle_conns(20); pool.set_timeout_check(Some(Duration::from_secs(5))); pool.set_timeout_wait(Some(Duration::from_secs(10))); let manager = DurationManager::new( base_manager, CheckMode::SkipInterval(Duration::from_secs(30)) ); ``` -------------------------------- ### Dynamically Reconfigure Pool Settings Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Demonstrates changing pool configurations like max_open connections and timeout checks at runtime without recreating the pool. Configuration methods are thread-safe. ```rust let pool = Pool::new(manager); // Configure pool.set_max_open(100); // Later, reconfigure pool.set_max_open(50); pool.set_timeout_check(Some(Duration::from_secs(5))); // For DurationManager, mode can change atomically if let Some(dm) = pool.downcast_manager::>() { dm.mode.set_mode(CheckMode::NoLimit); } ``` -------------------------------- ### Manager Error Type Examples Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/error-handling.md Demonstrates how to define the Error type for the Manager trait, showing both a simple String alias and a custom enum. ```Rust impl Manager for MyManager { type Error = String; // or custom enum // or type Error = MyError; // custom enum } ``` ```Rust type Error = String; // Simple: from_str automatically works #[derive(Debug)] enum PoolError { ConnectionFailed(String), ValidationFailed(String), } impl From<&str> for PoolError { fn from(s: &str) -> Self { PoolError::ConnectionFailed(s.to_string()) } } type Error = PoolError; // Domain-specific errors ``` -------------------------------- ### Test Connection Creation Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Verify that a connection can be successfully acquired from the pool when it's initially created. ```rust #[tokio::test] async fn test_connect() { let pool = Pool::new(MyManager {}); let _conn = pool.get().await.unwrap(); assert!(pool.state().in_use > 0); } ``` -------------------------------- ### Minimal Pool Creation with Custom Manager Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Create a new connection pool using a custom Manager implementation. The Manager must implement `connect` and `check` methods. ```rust impl Manager for MyManager { type Connection = String; type Error = String; async fn connect(&self) -> Result { Ok("connection".to_string()) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { Ok(()) } } let pool = Pool::new(MyManager {}); ``` -------------------------------- ### Create a new Pool Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/pool.md Instantiate a new Pool with a given connection manager. Ensure the manager's connection type implements Unpin and Send. The pool is created with default configuration values. ```rust use fast_pool::{Manager, Pool}; let manager = MyManager {}; let pool = Pool::new(manager); ``` -------------------------------- ### connect() Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/manager-trait.md Creates a new connection instance. This method is called by the pool when it needs to establish a new connection to meet demand or maintain the pool size. ```APIDOC ## connect() ### Description Creates a new connection instance. ### Method `async fn connect(&self) -> Result` ### Parameters None (uses `self`) ### Returns - `Ok(Connection)` — A newly created connection ready for use - `Err(Error)` — If connection creation fails ### When called When the pool needs to establish a new connection to meet demand or maintain the pool size. ### Example ```rust impl Manager for MyManager { type Connection = DatabaseConnection; type Error = String; async fn connect(&self) -> Result { DatabaseConnection::new("server:5432") .await .map_err(|e| e.to_string()) } } ``` ``` -------------------------------- ### Benchmarking Results for fast_pool Source: https://github.com/rbatis/fast_pool/blob/main/README.md Performance benchmarks for the fast_pool on Windows and Linux systems, showing nanoseconds per operation and queries per second. ```log //---- bench_pool windows ---- //Time: 14.0994ms ,each:130 ns/op //QPS: 7086167 QPS/s //---- bench_pool linux ---- //Time: 11.437625ms ,each:114 ns/op //QPS: 8736453 QPS/s ``` -------------------------------- ### Configure Pool Settings Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Set maximum open connections, idle connections, and various timeout durations for connection checking and waiting after pool creation. ```rust let pool = Pool::new(manager); pool.set_max_open(100); // Max open connections (default: 32) pool.set_max_idle_conns(50); // Max idle connections (default: 32) pool.set_timeout_check(Some(Duration::from_secs(5))); // Check timeout (default: 10s) pool.set_timeout_wait(Some(Duration::from_secs(10))); // Wait timeout (default: 30s) ``` -------------------------------- ### CheckModeAtomic Methods Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Provides atomic storage for check mode configuration, enabling lock-free updates. Includes methods to set and get the current check mode. ```APIDOC ## CheckModeAtomic Atomic storage for check mode configuration enabling lock-free updates. ### Methods #### `set_mode(mode: CheckMode)` Atomically update the check mode during runtime. ##### Example ```rust duration_manager.mode.set_mode(CheckMode::NoLimit); ``` #### `get_mode() -> CheckMode` Retrieve the current check mode. ##### Example ```rust let current_mode = duration_manager.mode.get_mode(); match current_mode { CheckMode::NoLimit => println!("Always validating"), CheckMode::SkipInterval(d) => println!("Skip interval: {:?}", d), CheckMode::MaxLifetime(d) => println!("Max lifetime: {:?}", d), } ``` ``` -------------------------------- ### Connection Lifecycle Flow Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/INDEX.md Illustrates the sequence of operations involved in acquiring, using, and returning a connection from the pool. ```text Pool::get() or Pool::get_timeout() ↓ Create connection (manager.connect()) ↓ Validate connection (manager.check()) ↓ Return ConnectionGuard wrapping connection ↓ User accesses via Deref/DerefMut ↓ Guard dropped → connection returned to pool ↓ If idle pool < max_idle: kept for reuse If idle pool >= max_idle: discarded ``` -------------------------------- ### Get Current Check Mode Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Retrieves the current check mode configuration from the DurationManager. This can be used to conditionally execute logic based on the active validation strategy. ```rust let current_mode = duration_manager.mode.get_mode(); match current_mode { CheckMode::NoLimit => println!("Always validating"), CheckMode::SkipInterval(d) => println!("Skip interval: {:?}", d), CheckMode::MaxLifetime(d) => println!("Max lifetime: {:?}", d), } ``` -------------------------------- ### Display Implementation for State Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Demonstrates how to print the State struct in a human-readable format. This is suitable for user-facing output. ```rust impl Display for State ``` ```rust let state = pool.state(); println!("{}", state); // Output: { max_open: 32, connections: 10, in_use: 5, idle: 5, connecting: 0, checking: 0, waits: 0 } ``` -------------------------------- ### Fallback to Direct Connection on Pool Failure Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/error-handling.md Attempts to get a connection from the pool with a timeout. If it fails, it falls back to creating a direct connection using a provided fallback manager. ```rust async fn get_or_fallback( pool: &Pool, fallback_manager: &M, ) -> Result, String> { match pool.get_timeout(Some(Duration::from_secs(5))).await { Ok(conn) => Ok(conn), Err(_) => { eprintln!("Pool failed, creating direct connection"); let conn = fallback_manager.connect().await?; // Return as if from pool (requires care with cleanup) Ok(ConnectionGuard::new(conn, pool.clone())) } } } ``` -------------------------------- ### Set and Get Connection Timeout Wait Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Configure the default timeout for acquiring a connection from the pool. Set to None for an infinite timeout. This timeout applies to connection creation, waiting, and validation. ```rust pool.set_timeout_wait(Some(Duration::from_secs(10))); // 10 second default pool.set_timeout_wait(None); // No timeout // At call time let conn = pool.get().await?; // Or override let conn = pool.get_timeout(Some(Duration::from_secs(5))).await?; // 5 seconds ``` -------------------------------- ### Memory-Constrained Pool Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Recommended settings for environments with memory constraints, prioritizing lower resource usage by reducing the number of open and idle connections. ```rust pool.set_max_open(20); pool.set_max_idle_conns(5); pool.set_timeout_check(Some(Duration::from_secs(2))); pool.set_timeout_wait(Some(Duration::from_secs(5))); ``` -------------------------------- ### Wrapping Third-Party Database Connection Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Shows how to wrap a third-party database connection within a custom struct and manager. This allows integrating external database clients with Fast Pool. ```rust pub struct DatabaseConnection { inner: ThirdPartyConnection, connection_string: String, } struct MyManager { connection_string: String, } impl Manager for MyManager { type Connection = DatabaseConnection; type Error = String; async fn connect(&self) -> Result { let inner = ThirdPartyConnection::connect(&self.connection_string) .await .map_err(|e| e.to_string())?; Ok(DatabaseConnection { inner, connection_string: self.connection_string.clone(), }) } async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> { conn.inner.ping().await.map_err(|e| e.to_string()) } } ``` -------------------------------- ### connect() Method Signature Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Signature for the connect method, which creates a new wrapped connection with a creation timestamp. ```rust async fn connect(&self) -> Result, M::Error> ``` -------------------------------- ### Basic Error Handling for Connection Acquisition Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/quick-reference.md Handle potential errors during connection acquisition using a `match` statement. ```rust match pool.get().await { Ok(conn) => { // Use connection } Err(e) => { eprintln!("Failed: {:?}", e); } } ``` -------------------------------- ### File Structure of fast_pool Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/INDEX.md Overview of the directory structure for the fast_pool project, including documentation and source code organization. ```text output/ ├── INDEX.md (this file) ├── README.md (project overview) ├── types.md (type reference) ├── configuration.md (configuration guide) ├── implementation-guide.md (how to implement Manager) ├── quick-reference.md (cheat sheet) └── api-reference/ ├── manager-trait.md (Manager trait details) ├── pool.md (Pool details) ├── connection-guard.md (ConnectionGuard details) ├── state.md (State details) └── duration-manager.md (DurationManager plugin) ``` -------------------------------- ### Testing Direct Connection Creation Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/error-handling.md Directly tests the manager's ability to establish a new connection. This is useful for troubleshooting 'Connection Creation Fails' symptoms by isolating the connection logic. ```rust // Test connection creation directly match manager.connect().await { Ok(conn) => println!("Connection created successfully"), Err(e) => println!("Connection creation failed: {}", e), } ``` -------------------------------- ### DurationManager::connect Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/duration-manager.md Establishes a new connection using the underlying manager, wrapping it with duration tracking. ```APIDOC ## DurationManager::connect ### Description Creates a new wrapped connection with a creation timestamp, utilizing the underlying manager's connection logic. ### Method `async fn connect(&self) -> Result, M::Error>` ### Parameters None ### Returns - `Ok(DurationConnection)` - A new `DurationConnection` instance containing the established connection and its creation timestamp. - `Err(M::Error)` - An error if the underlying manager fails to create a connection. ### Timestamp Behavior - **NoLimit**: No timestamp is tracked (`None`). - **SkipInterval(_)**: The timestamp is set to the current time. - **MaxLifetime(_)**: The timestamp is set to the current time. ``` -------------------------------- ### Test Connection Acquisition Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Verifies that the connect() method successfully returns a valid connection. ```rust #[tokio::test] async fn test_connect() { let manager = MyManager {}; let conn = manager.connect().await.unwrap(); // Assert connection is valid } ``` -------------------------------- ### Low-Latency Pool Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Recommended settings for achieving low-latency operations, by increasing the number of open connections and optimizing check intervals. ```rust pool.set_max_open(200); pool.set_max_idle_conns(50); pool.set_timeout_check(Some(Duration::from_millis(500))); pool.set_timeout_wait(Some(Duration::from_secs(30))); let manager = DurationManager::new( base_manager, CheckMode::SkipInterval(Duration::from_secs(60)) ); ``` -------------------------------- ### Handle Pool Errors Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Demonstrates how to gracefully handle potential errors when acquiring a connection from the pool using a match statement. ```rust match pool.get().await { Ok(conn) => { /* use conn */ }, Err(e) => eprintln!("Failed: {:?}", e), } ``` -------------------------------- ### PartialEq Implementation for State Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/state.md Shows how to compare two State structs for equality. Note that due to concurrent changes, states may not be equal even if retrieved close in time. ```rust impl PartialEq for State ``` ```rust let state1 = pool.state(); let state2 = pool.state(); assert_eq!(state1, state2); // May not be equal due to concurrent changes ``` -------------------------------- ### Monitor and Tune Pool Configuration Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Monitor the connection pool's state to dynamically adjust configuration. This snippet shows how to check utilization, idle connections, and task waits to grow or shrink the pool. ```rust let state = pool.state(); // Check capacity utilization let utilization = state.in_use as f64 / state.max_open as f64; if utilization > 0.9 { println!("High utilization: {:.1}%", utilization * 100.0); pool.set_max_open(state.max_open + 50); // Grow pool } // Check idle waste if state.idle > state.in_use * 3 { println!("Too many idle connections"); pool.set_max_idle_conns(state.max_idle - 10); // Shrink pool } // Check for contention if state.waits > 0 { println!("{} tasks waiting for connections", state.waits); } ``` -------------------------------- ### Change CheckMode at Runtime Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/README.md Demonstrates how to dynamically change the connection checking strategy of a `DurationManager` at runtime after the pool has been initialized. ```rust let duration_manager = DurationManager::new(manager, CheckMode::SkipInterval(Duration::from_secs(30))); let pool = Pool::new(duration_manager); // Later change strategy let dm = pool.downcast_manager::>().unwrap(); dm.mode.set_mode(CheckMode::MaxLifetime(Duration::from_secs(300))); ``` -------------------------------- ### Pool Constructor Defaults Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/configuration.md Shows the default configuration values applied when creating a new pool using Pool::new(). These include maximum open connections, maximum idle connections, and various timeout durations. ```rust pub fn new(m: M) -> Self { // Default configuration let max_open = 32; let max_idle = 32; let timeout_check = Duration::from_secs(10); let timeout_wait = Duration::from_secs(30); // Build pool with defaults Self { ... } } ``` -------------------------------- ### Acquire a connection with default timeout Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/pool.md Acquire a connection from the pool using the default wait timeout configured for the pool. The connection is returned wrapped in a ConnectionGuard, which automatically handles returning the connection to the pool upon dropping. The manager's check method is used to validate the connection before returning it. ```rust let mut conn = pool.get().await?; // Use connection through Deref/DerefMut let result = conn.execute_query().await?; // Connection automatically returned to pool on drop ``` -------------------------------- ### ConnectionGuard for Error Handling Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Demonstrates how ConnectionGuard ensures connection cleanup even when errors occur within a block. The connection is automatically returned or discarded when the guard goes out of scope, regardless of success or failure. ```rust let mut conn = pool.get().await?; match conn.execute().await { Ok(result) => { println!("Success: {:?}", result); } Err(e) => { // Guard still automatically returns/drops connection return Err(e); } } ``` -------------------------------- ### ConnectionGuard::new() Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Constructs a new ConnectionGuard, wrapping a connection and associating it with a pool for automatic return. ```APIDOC ## ConnectionGuard::new() ### Description Constructs a new `ConnectionGuard`, wrapping a connection and associating it with a pool for automatic return. ### Signature ```rust pub fn new(conn: M::Connection, pool: Pool) -> ConnectionGuard ``` ### Parameters #### Path Parameters - **conn** (`M::Connection`) - Required - The connection to wrap. - **pool** (`Pool`) - Required - The pool instance for returning connection on drop. ### Returns `ConnectionGuard` instance ### Example ```rust let conn = manager.connect().await?; let guard = ConnectionGuard::new(conn, pool.clone()); // Connection returned to pool on drop ``` ``` -------------------------------- ### Automatic Connection Return on Drop Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Demonstrates how the ConnectionGuard automatically returns or discards the connection when it goes out of scope. Valid connections are recycled, invalid ones are discarded. ```rust { let conn = pool.get().await?; // Use connection } // Connection automatically returned here ``` -------------------------------- ### Create ConnectionGuard Instance Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/api-reference/connection-guard.md Instantiates a ConnectionGuard to wrap a connection and manage its return to the pool. Typically used internally by pool methods. ```rust let conn = manager.connect().await?; let guard = ConnectionGuard::new(conn, pool.clone()); // Connection returned to pool on drop ``` -------------------------------- ### Test Connection Return on Drop Source: https://github.com/rbatis/fast_pool/blob/main/_autodocs/implementation-guide.md Ensures that connections are automatically returned to the pool when they are dropped. ```rust #[tokio::test] async fn test_connection_return() { let pool = Pool::new(MyManager {}); { let _conn = pool.get().await.unwrap(); } // Connection dropped here let state = pool.state(); assert_eq!(state.in_use, 0); assert!(state.idle > 0); } ```