Skip to main content

seaorm_pool/
config.rs

1//! # Application Configuration Module
2//!
3//! This module defines the configuration structures required for the application,
4//! focusing on database connectivity through `sea-orm`. It is designed to be
5//! flexible, serializable, and easily integrated into various application setups.
6//!
7//! The primary entry point is the `AppConfig` struct, which encapsulates all
8//! other configuration settings, including the `DatabaseConfig` for `sea-orm`
9//! connections.
10//!
11//! All structures derive `serde::Serialize` and `serde::Deserialize` to allow for
12//! effortless parsing from configuration files (e.g., TOML, YAML, JSON).
13//!
14//! ## Module Components
15//!
16//! - **`AppConfig`**: The root configuration struct for the application.
17//! - **`DatabaseConfig`**: Holds all settings related to the database connection,
18//!   including credentials, address, and pooling.
19//! - **`PoolOptions`**: Specifies the behavior of the database connection pool,
20//!   such as connection limits and timeouts.
21//!
22//! ## Example Usage (TOML File)
23//!
24//! ```toml
25//! # Database connection settings are nested under the 'database' key.
26//! [database]
27//! host = "localhost"
28//! port = 5432
29//! username = "user"
30//! password = "password"
31//! databaseName = "app_db"
32//!
33//! # Optional: SSL settings for a secure connection.
34//! # sslCa = "/path/to/ca.pem"
35//!
36//! # Connection pool settings.
37//! [database.poolOptions]
38//! maxConnections = 20
39//! minConnections = 5
40//! acquireTimeout = "30s"
41//! idleTimeout = "10m"
42//! maxLifetime = "30m"
43//! ```
44
45use std::time::Duration;
46
47/// Represents the main configuration for the application.
48///
49/// This struct serves as the top-level container, holding all configuration
50/// necessary for the application to run. It includes database-specific settings
51/// encapsulated within the `database` field.
52///
53/// # Examples
54///
55/// An example of how this might be represented in a TOML configuration file:
56///
57/// ```toml
58/// [database]
59/// host = "127.0.0.1"
60/// port = 4000
61/// username = "admin"
62/// password = "secret"
63/// databaseName = "mydb"
64///
65/// [database.poolOptions]
66/// maxConnections = 10
67/// ```
68#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
69#[serde(rename_all = "camelCase")]
70pub struct AppConfig {
71    /// Configuration for the database connection, using `sea-orm`.
72    pub database: DatabaseConfig,
73}
74
75/// Defines the configuration for connecting to a database using `sea-orm`.
76///
77/// This struct contains all necessary parameters to establish and manage
78/// database connections. It includes server details, authentication credentials,
79/// and nested configuration for connection pooling and SSL.
80///
81/// # Examples
82///
83/// An example of how this might be represented in a TOML configuration file:
84///
85/// ```toml
86/// host = "db.example.com"
87/// port = 5432
88/// username = "db_user"
89/// password = "super_secret"
90/// databaseName = "production_db"
91///
92/// [poolOptions]
93/// maxConnections = 15
94/// minConnections = 2
95/// ```
96#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
97#[serde(rename_all = "camelCase")]
98pub struct DatabaseConfig {
99    /// The hostname or IP address of the database server.
100    pub host: String,
101
102    /// The port number of the database server.
103    ///
104    /// If not specified, this will default to the standard port used by the
105    /// `sea-orm` driver (e.g., 5432 for PostgreSQL, 3306 for MySQL).
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub port: Option<u16>,
108
109    /// The username for authenticating to the database server.
110    pub username: String,
111
112    /// The password for authenticating to the database server.
113    pub password: String,
114
115    /// The name of the specific database to connect to.
116    pub database_name: String,
117
118    /// Connection pooling options to manage database connections efficiently.
119    ///
120    /// If this section is omitted from a configuration file, default pool settings
121    /// will be applied.
122    #[serde(default)]
123    pub pool_options: PoolOptions,
124
125    /// The file path to the SSL Certificate Authority (CA) for establishing a
126    /// secure, encrypted connection.
127    ///
128    /// If this is `None`, SSL/TLS will not be explicitly configured.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub ssl_ca: Option<String>,
131}
132
133impl DatabaseConfig {
134    /// Returns the full network address of the database server as a single string.
135    ///
136    /// If a port is specified, it formats the output as `"host:port"`.
137    /// Otherwise, it returns the host alone.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// // Assuming this module is in a file named `config.rs`
143    /// // use crate::config::{DatabaseConfig, PoolOptions};
144    /// # use super_project::DatabaseConfig; // This line is for documentation test purposes
145    ///
146    /// // A config with a specified port
147    /// let mut config_with_port = DatabaseConfig::default();
148    /// config_with_port.host = "127.0.0.1".to_string();
149    /// config_with_port.port = Some(5432);
150    /// assert_eq!(config_with_port.get_address(), "127.0.0.1:5432");
151    ///
152    /// // A config without a specified port
153    /// let mut config_without_port = DatabaseConfig::default();
154    /// config_without_port.host = "db.example.com".to_string();
155    /// assert_eq!(config_without_port.get_address(), "db.example.com");
156    /// ```
157    pub fn get_address(&self) -> String {
158        if let Some(port) = self.port {
159            format!("{}:{}", self.host, port)
160        } else {
161            self.host.clone()
162        }
163    }
164}
165
166/// Provides a default, non-functional `DatabaseConfig` for convenience.
167///
168/// The default values are empty or zero-like, and must be overridden with
169/// actual configuration before use.
170impl Default for DatabaseConfig {
171    fn default() -> Self {
172        Self {
173            host: "localhost".to_string(),
174            port: None,
175            username: String::new(),
176            password: String::new(),
177            database_name: String::new(),
178            pool_options: PoolOptions::default(),
179            ssl_ca: None,
180        }
181    }
182}
183
184// Private helper functions to provide default values for `PoolOptions`.
185// This is a standard pattern when using `#[serde(default = "...")]`.
186fn default_max_connections() -> u32 {
187    10
188}
189fn default_min_connections() -> u32 {
190    1
191}
192fn default_acquire_timeout() -> Duration {
193    Duration::from_secs(30)
194}
195fn default_idle_timeout() -> Duration {
196    Duration::from_secs(300)
197}
198fn default_max_lifetime() -> Duration {
199    Duration::from_secs(1800)
200}
201fn default_is_lazy() -> bool {
202    true
203}
204fn default_statement_cache_capacity() -> usize {
205    100
206}
207
208/// Configures the behavior of the database connection pool.
209///
210/// These settings control the lifecycle and allocation of database connections,
211/// which is critical for application performance and stability. The options
212/// map directly to the underlying `sqlx::PoolOptions`.
213///
214/// # Examples
215///
216/// An example of how this might be represented in a TOML configuration file:
217///
218/// ```toml
219/// maxConnections = 20
220/// minConnections = 5
221/// acquireTimeout = "30s"
222/// idleTimeout = "5m"
223/// maxLifetime = "30m"
224/// isLazy = false
225/// statementCacheCapacity = 200
226/// ```
227#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
228#[serde(rename_all = "camelCase")]
229pub struct PoolOptions {
230    /// The maximum number of connections the pool should maintain.
231    ///
232    /// This value should be set carefully based on the database server's capacity
233    /// and the expected application load.
234    ///
235    /// **Default**: `10`
236    #[serde(default = "default_max_connections")]
237    pub max_connections: u32,
238
239    /// The minimum number of idle connections the pool should maintain.
240    ///
241    /// When the pool is created, this many connections will be established. If the number
242    /// of idle connections drops below this value, the pool will attempt to create new
243    /// ones to replenish it.
244    ///
245    /// **Default**: `1`
246    #[serde(default = "default_min_connections")]
247    pub min_connections: u32,
248
249    /// The maximum time to wait for a connection to become available.
250    ///
251    /// If a connection cannot be acquired from the pool within this duration, the
252    /// operation will time out and return an error.
253    ///
254    /// **Default**: `30` seconds
255    #[serde(with = "humantime_serde")]
256    #[serde(default = "default_acquire_timeout")]
257    pub acquire_timeout: Duration,
258
259    /// The maximum duration a connection can remain idle in the pool.
260    ///
261    /// Any connection that has been idle for longer than this duration will be
262    /// closed and removed from the pool. This helps release resources on the
263    /// database server.
264    ///
265    /// **Default**: `300` seconds (5 minutes)
266    #[serde(with = "humantime_serde")]
267    #[serde(default = "default_idle_timeout")]
268    pub idle_timeout: Duration,
269
270    /// The maximum lifetime of any single connection.
271    ///
272    /// A connection will be gracefully closed once it has been open for this
273    /// duration. This is a crucial practice for preventing resource leaks and ensuring
274    /// connections are periodically recycled.
275    ///
276    /// **Default**: `1800` seconds (30 minutes)
277    #[serde(with = "humantime_serde")]
278    #[serde(default = "default_max_lifetime")]
279    pub max_lifetime: Duration,
280
281    /// If `true`, the pool will not establish connections until one is first requested.
282    ///
283    /// If `false`, the pool will try to establish `min_connections` immediately
284    /// upon creation.
285    ///
286    /// **Default**: `true`
287    #[serde(default = "default_is_lazy")]
288    pub is_lazy: bool,
289
290    /// The capacity of the prepared statement cache for each connection.
291    ///
292    /// Caching is managed using an LRU (Least Recently Used) policy. When the number
293    /// of cached statements exceeds this capacity, the oldest one is evicted.
294    ///
295    /// **Default**: `100`
296    #[serde(default = "default_statement_cache_capacity")]
297    pub statement_cache_capacity: usize,
298}
299
300impl Default for PoolOptions {
301    /// Creates a `PoolOptions` instance with sensible default values.
302    fn default() -> Self {
303        Self {
304            max_connections: default_max_connections(),
305            min_connections: default_min_connections(),
306            acquire_timeout: default_acquire_timeout(),
307            idle_timeout: default_idle_timeout(),
308            max_lifetime: default_max_lifetime(),
309            is_lazy: default_is_lazy(),
310            statement_cache_capacity: default_statement_cache_capacity(),
311        }
312    }
313}
314
315// The tests module
316#[cfg(test)]
317mod tests {
318    use super::*;
319    // Import everything from the outer module.
320
321    /// Test 1: Full deserialization of an AppConfig from a TOML string.
322    /// Verifies that all fields, including nested ones, are correctly parsed.
323    #[test]
324    fn test_full_app_config_deserialization() {
325        let toml_str = r#"
326            [database]
327            host = "prod.db.internal"
328            port = 5433
329            username = "prod_user"
330            password = "prod_password"
331            databaseName = "prod_db"
332            sslCa = "/etc/ssl/certs/ca-certificates.crt"
333
334            [database.poolOptions]
335            maxConnections = 50
336            minConnections = 10
337            acquireTimeout = "60s"
338            idleTimeout = "10m"
339            maxLifetime = "1h"
340            isLazy = false
341            statementCacheCapacity = 250
342        "#;
343
344        let config: AppConfig = toml::from_str(toml_str).expect("Failed to parse TOML");
345
346        // Assert database config
347        assert_eq!(config.database.host, "prod.db.internal");
348        assert_eq!(config.database.port, Some(5433));
349        assert_eq!(config.database.username, "prod_user");
350        assert_eq!(config.database.password, "prod_password");
351        assert_eq!(config.database.database_name, "prod_db");
352        assert_eq!(
353            config.database.ssl_ca,
354            Some("/etc/ssl/certs/ca-certificates.crt".to_string())
355        );
356
357        // Assert pool options
358        assert_eq!(config.database.pool_options.max_connections, 50);
359        assert_eq!(config.database.pool_options.min_connections, 10);
360        assert_eq!(
361            config.database.pool_options.acquire_timeout,
362            Duration::from_secs(60)
363        );
364        assert_eq!(
365            config.database.pool_options.idle_timeout,
366            Duration::from_secs(600)
367        );
368        assert_eq!(
369            config.database.pool_options.max_lifetime,
370            Duration::from_secs(3600)
371        );
372        assert_eq!(config.database.pool_options.is_lazy, false);
373        assert_eq!(config.database.pool_options.statement_cache_capacity, 250);
374    }
375
376    /// Test 2: Deserialization with minimal configuration.
377    /// Verifies that default values are applied correctly for omitted fields.
378    #[test]
379    fn test_minimal_config_uses_defaults() {
380        let toml_str = r#"
381            [database]
382            host = "test.db"
383            username = "test_user"
384            password = "test_password"
385            databaseName = "test_db"
386        "#;
387
388        let config: AppConfig = toml::from_str(toml_str).expect("Failed to parse TOML");
389
390        // Assert provided values
391        assert_eq!(config.database.host, "test.db");
392        assert_eq!(config.database.database_name, "test_db");
393
394        // Assert default values
395        assert_eq!(config.database.port, None);
396        assert_eq!(config.database.ssl_ca, None);
397        assert_eq!(config.database.pool_options, PoolOptions::default());
398    }
399
400    /// Test 3: Partial pool options deserialization. (CORRECTED)
401    /// Verifies that specified pool options override defaults, while others remain default.
402    #[test]
403    fn test_partial_pool_options_deserialization() {
404        // This TOML must represent a valid AppConfig to ensure parsing succeeds.
405        // We provide the necessary database fields and a partial poolOptions table.
406        let toml_str = r#"
407            [database]
408            host = "dummy"
409            username = "dummy"
410            password = "dummy"
411            databaseName = "dummy"
412
413            # Only specify a subset of pool options
414            [database.poolOptions]
415            maxConnections = 5
416            acquireTimeout = "5s"
417        "#;
418
419        // Parse the full AppConfig. This should now succeed.
420        let config: AppConfig =
421            toml::from_str(toml_str).expect("Failed to parse TOML with partial pool options");
422
423        let pool_opts = &config.database.pool_options;
424
425        // Assert that the specified values have been overridden
426        assert_eq!(pool_opts.max_connections, 5); // Overridden, this will now pass
427        assert_eq!(pool_opts.acquire_timeout, Duration::from_secs(5)); // Overridden
428
429        // Assert that the unspecified values correctly fall back to their defaults
430        assert_eq!(pool_opts.min_connections, default_min_connections()); // Default
431        assert_eq!(pool_opts.idle_timeout, default_idle_timeout()); // Default
432        assert_eq!(pool_opts.max_lifetime, default_max_lifetime()); // Default
433    }
434
435    /// Test 4: `PoolOptions::default()` constructor.
436    /// Verifies that the default constructor for PoolOptions provides the correct values.
437    #[test]
438    fn test_pool_options_default_values() {
439        let defaults = PoolOptions::default();
440        assert_eq!(defaults.max_connections, 10);
441        assert_eq!(defaults.min_connections, 1);
442        assert_eq!(defaults.acquire_timeout, Duration::from_secs(30));
443        assert_eq!(defaults.idle_timeout, Duration::from_secs(300));
444        assert_eq!(defaults.max_lifetime, Duration::from_secs(1800));
445        assert_eq!(defaults.is_lazy, true);
446        assert_eq!(defaults.statement_cache_capacity, 100);
447    }
448
449    /// Test 5: `DatabaseConfig::default()` constructor.
450    /// Verifies the default values for the main database configuration struct.
451    #[test]
452    fn test_database_config_default_values() {
453        let defaults = DatabaseConfig::default();
454        assert_eq!(defaults.host, "localhost");
455        assert_eq!(defaults.port, None);
456        assert!(defaults.username.is_empty());
457        assert!(defaults.password.is_empty());
458        assert!(defaults.database_name.is_empty());
459        assert_eq!(defaults.ssl_ca, None);
460        assert_eq!(defaults.pool_options, PoolOptions::default());
461    }
462
463    /// Test 6: `get_address()` method with a port specified.
464    #[test]
465    fn test_get_address_with_port() {
466        let mut config = DatabaseConfig::default();
467        config.host = "127.0.0.1".to_string();
468        config.port = Some(5432);
469        assert_eq!(config.get_address(), "127.0.0.1:5432");
470    }
471
472    /// Test 7: `get_address()` method without a port specified.
473    #[test]
474    fn test_get_address_without_port() {
475        let mut config = DatabaseConfig::default();
476        config.host = "database.service.local".to_string();
477        config.port = None;
478        assert_eq!(config.get_address(), "database.service.local");
479    }
480
481    /// Test 8: Serialization and deserialization roundtrip.
482    /// Ensures that a configuration can be serialized and then deserialized back
483    /// into an identical structure. Uses JSON for simplicity.
484    #[test]
485    fn test_json_serialization_roundtrip() {
486        let original_config = AppConfig {
487            database: DatabaseConfig {
488                host: "roundtrip.db".to_string(),
489                port: Some(1234),
490                username: "rt_user".to_string(),
491                password: "rt_password".to_string(),
492                database_name: "rt_db".to_string(),
493                ssl_ca: Some("/tmp/ca.pem".to_string()),
494                pool_options: PoolOptions {
495                    max_connections: 99,
496                    ..Default::default()
497                },
498            },
499        };
500
501        let json_string = serde_json::to_string(&original_config).expect("Serialization failed");
502        let deserialized_config: AppConfig =
503            serde_json::from_str(&json_string).expect("Deserialization failed");
504
505        assert_eq!(original_config, deserialized_config);
506    }
507
508    /// Test 9: `skip_serializing_if` attribute behavior.
509    /// Verifies that optional fields with `None` values are omitted from the
510    /// serialized output.
511    #[test]
512    fn test_skip_serializing_if_none() {
513        let config = DatabaseConfig {
514            port: None,
515            ssl_ca: None,
516            ..DatabaseConfig::default()
517        };
518
519        let toml_string = toml::to_string(&config).expect("Failed to serialize to TOML");
520
521        // Check that the keys for `None` values are not present in the output
522        assert!(!toml_string.contains("port ="));
523        assert!(!toml_string.contains("sslCa ="));
524    }
525
526    /// Test 10: `camelCase` naming convention is correctly handled.
527    /// This is implicitly tested in other tests, but this one focuses on it.
528    #[test]
529    fn test_camel_case_field_names() {
530        let toml_str = r#"
531            [database]
532            host = "dummy"
533            username = "dummy"
534            password = "dummy"
535            databaseName = "camel_case_db"
536
537            [database.poolOptions]
538            maxConnections = 123
539        "#;
540
541        let config: AppConfig = toml::from_str(toml_str).expect("Failed to parse");
542
543        assert_eq!(config.database.database_name, "camel_case_db");
544        assert_eq!(config.database.pool_options.max_connections, 123);
545    }
546
547    /// Test 11: Deserializing human-readable durations.
548    /// Verifies that `humantime_serde` correctly parses string representations of time.
549    #[test]
550    fn test_humantime_duration_parsing() {
551        let toml_str = r#"
552            acquireTimeout = "1m"
553            idleTimeout = "2h"
554            maxLifetime = "3d"
555        "#;
556        let pool_opts: PoolOptions = toml::from_str(toml_str).expect("Failed to parse humantime");
557
558        assert_eq!(pool_opts.acquire_timeout, Duration::from_secs(60));
559        assert_eq!(pool_opts.idle_timeout, Duration::from_secs(2 * 3600));
560        assert_eq!(pool_opts.max_lifetime, Duration::from_secs(3 * 24 * 3600));
561    }
562}