ch_database/mariadb/
pool.rs1use std::future::Future;
2use std::pin::Pin;
3use std::time::Duration;
4
5use anyhow::{Context, Result};
6use sqlx::mysql::MySqlPoolOptions;
7use sqlx::{MySql, MySqlPool, Transaction};
8use thiserror::Error;
9use tokio::time::sleep;
10use tracing::{debug, warn};
11
12use super::url::{MySqlUrlError, normalize_mysql_url};
13
14#[derive(Debug, Error)]
16pub enum MySqlConnectionError {
17 #[error(transparent)]
19 Url(#[from] MySqlUrlError),
20 #[error("max_connections must be greater than zero")]
22 InvalidMaxConnections,
23 #[error("max_attempts must be greater than zero")]
25 InvalidMaxAttempts,
26 #[error("failed to connect to the database after {attempts} attempt(s)")]
28 Connect {
29 attempts: u32,
31 #[source]
33 source: sqlx::Error,
34 },
35}
36
37pub type MySqlConnectionResult<T> = std::result::Result<T, MySqlConnectionError>;
39
40#[derive(Debug, Clone)]
42pub struct MySqlPoolSettings {
43 pub max_connections: u32,
45 pub max_attempts: u32,
47 pub retry_delay: Duration,
49}
50
51impl Default for MySqlPoolSettings {
52 fn default() -> Self {
53 Self {
54 max_connections: 5,
55 max_attempts: 5,
56 retry_delay: Duration::from_secs(4),
57 }
58 }
59}
60
61pub async fn connect_mysql_pool(
63 url: &str,
64 settings: &MySqlPoolSettings,
65) -> MySqlConnectionResult<MySqlPool> {
66 if settings.max_connections == 0 {
67 return Err(MySqlConnectionError::InvalidMaxConnections);
68 }
69 if settings.max_attempts == 0 {
70 return Err(MySqlConnectionError::InvalidMaxAttempts);
71 }
72 let normalized = normalize_mysql_url(url)?;
73
74 let options = normalized
75 .parse::<sqlx::mysql::MySqlConnectOptions>()
76 .map_err(|source| MySqlConnectionError::Connect {
77 attempts: 0,
78 source,
79 })?;
80 connect_mysql_pool_with_options(options, settings).await
81}
82
83pub async fn connect_mysql_pool_with_options(
85 options: sqlx::mysql::MySqlConnectOptions,
86 settings: &MySqlPoolSettings,
87) -> MySqlConnectionResult<MySqlPool> {
88 if settings.max_connections == 0 {
89 return Err(MySqlConnectionError::InvalidMaxConnections);
90 }
91 if settings.max_attempts == 0 {
92 return Err(MySqlConnectionError::InvalidMaxAttempts);
93 }
94 let mut attempt = 0;
95 loop {
96 attempt += 1;
97
98 match MySqlPoolOptions::new()
99 .max_connections(settings.max_connections)
100 .connect_with(options.clone())
101 .await
102 {
103 Ok(pool) => return Ok(pool),
104 Err(error) if attempt < settings.max_attempts => {
105 warn!(
106 attempt,
107 max_attempts = settings.max_attempts,
108 retry_delay_secs = settings.retry_delay.as_secs(),
109 error = %error,
110 "failed to connect to database, retrying"
111 );
112 sleep(settings.retry_delay).await;
113 }
114 Err(error) => {
115 return Err(MySqlConnectionError::Connect {
116 attempts: attempt,
117 source: error,
118 });
119 }
120 }
121 }
122}
123
124pub type TransactionFuture<'c, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'c>>;
126
127pub async fn transaction<'p, T, F>(pool: &'p MySqlPool, f: F) -> Result<T>
129where
130 T: Send + 'static,
131 F: for<'c> FnOnce(&'c mut Transaction<'p, MySql>) -> TransactionFuture<'c, T>,
132{
133 debug!("starting database transaction");
134 let mut tx = pool.begin().await.context("failed to begin transaction")?;
135 let result = f(&mut tx).await;
136
137 match result {
138 Ok(value) => {
139 tx.commit().await.context("failed to commit transaction")?;
140 Ok(value)
141 }
142 Err(error) => {
143 tx.rollback()
144 .await
145 .context("failed to rollback transaction")?;
146 Err(error)
147 }
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::{MySqlConnectionError, MySqlPoolSettings, connect_mysql_pool};
154
155 #[tokio::test]
156 async fn rejects_zero_pool_limits_before_connecting() {
157 let settings = MySqlPoolSettings {
158 max_connections: 0,
159 ..MySqlPoolSettings::default()
160 };
161 assert!(matches!(
162 connect_mysql_pool("mysql://localhost/example", &settings).await,
163 Err(MySqlConnectionError::InvalidMaxConnections)
164 ));
165
166 let settings = MySqlPoolSettings {
167 max_connections: 1,
168 max_attempts: 0,
169 ..MySqlPoolSettings::default()
170 };
171 assert!(matches!(
172 connect_mysql_pool("mysql://localhost/example", &settings).await,
173 Err(MySqlConnectionError::InvalidMaxAttempts)
174 ));
175 }
176}