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::{ConnectOptions, MySql, MySqlPool, Transaction};
8use thiserror::Error;
9use tokio::time::sleep;
10use tracing::{debug, warn};
11
12use super::url::{MySqlUrlError, parse_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(
66 url: &str,
67 settings: &MySqlPoolSettings,
68) -> MySqlConnectionResult<MySqlPool> {
69 if settings.max_connections == 0 {
70 return Err(MySqlConnectionError::InvalidMaxConnections);
71 }
72 if settings.max_attempts == 0 {
73 return Err(MySqlConnectionError::InvalidMaxAttempts);
74 }
75 let parsed = parse_mysql_url(url)?;
76 let options = sqlx::mysql::MySqlConnectOptions::from_url(&parsed).map_err(|source| {
77 MySqlConnectionError::Connect {
78 attempts: 0,
79 source,
80 }
81 })?;
82 connect_mysql_pool_with_options(options, settings).await
83}
84
85pub async fn connect_mysql_pool_with_options(
87 options: sqlx::mysql::MySqlConnectOptions,
88 settings: &MySqlPoolSettings,
89) -> MySqlConnectionResult<MySqlPool> {
90 if settings.max_connections == 0 {
91 return Err(MySqlConnectionError::InvalidMaxConnections);
92 }
93 if settings.max_attempts == 0 {
94 return Err(MySqlConnectionError::InvalidMaxAttempts);
95 }
96 let mut attempt = 0;
97 loop {
98 attempt += 1;
99
100 match MySqlPoolOptions::new()
101 .max_connections(settings.max_connections)
102 .connect_with(options.clone())
103 .await
104 {
105 Ok(pool) => return Ok(pool),
106 Err(error) if attempt < settings.max_attempts => {
107 warn!(
108 attempt,
109 max_attempts = settings.max_attempts,
110 retry_delay_secs = settings.retry_delay.as_secs(),
111 error = %error,
112 "failed to connect to database, retrying"
113 );
114 sleep(settings.retry_delay).await;
115 }
116 Err(error) => {
117 return Err(MySqlConnectionError::Connect {
118 attempts: attempt,
119 source: error,
120 });
121 }
122 }
123 }
124}
125
126pub type TransactionFuture<'c, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'c>>;
128
129pub async fn transaction<'p, T, F>(pool: &'p MySqlPool, f: F) -> Result<T>
134where
135 T: Send + 'static,
136 F: for<'c> FnOnce(&'c mut Transaction<'p, MySql>) -> TransactionFuture<'c, T>,
137{
138 debug!("starting database transaction");
139 let mut tx = pool.begin().await.context("failed to begin transaction")?;
140 let result = f(&mut tx).await;
141
142 match result {
143 Ok(value) => {
144 tx.commit().await.context("failed to commit transaction")?;
145 Ok(value)
146 }
147 Err(error) => {
148 if let Err(rollback_error) = tx.rollback().await {
149 warn!(error = %rollback_error, "failed to rollback transaction");
150 }
151 Err(error)
152 }
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::{MySqlConnectionError, MySqlPoolSettings, connect_mysql_pool};
159
160 #[test]
161 fn sqlx_parses_credentials_without_a_normalization_pass() {
162 use crate::mariadb::url::{normalize_mysql_url, parse_mysql_url};
163 use sqlx::{ConnectOptions, mysql::MySqlConnectOptions};
164
165 for raw in [
166 "mysql://user:p@ss word@localhost/db",
167 "mysql://user:päss%20%zz@localhost/db",
168 "mysql://user:p%2Fa%3Fb%23c%25@localhost/db?ssl-mode=REQUIRED&charset=utf8mb4",
169 "mysql://user@name:pass@localhost:3307/db",
170 ] {
171 let direct = MySqlConnectOptions::from_url(&parse_mysql_url(raw).unwrap()).unwrap();
172 let normalized: MySqlConnectOptions =
173 normalize_mysql_url(raw).unwrap().parse().unwrap();
174 assert_eq!(direct.to_url_lossy(), normalized.to_url_lossy());
175 }
176 }
177
178 #[tokio::test]
179 async fn rejects_zero_pool_limits_before_connecting() {
180 let settings = MySqlPoolSettings {
181 max_connections: 0,
182 ..MySqlPoolSettings::default()
183 };
184 assert!(matches!(
185 connect_mysql_pool("mysql://localhost/example", &settings).await,
186 Err(MySqlConnectionError::InvalidMaxConnections)
187 ));
188
189 let settings = MySqlPoolSettings {
190 max_connections: 1,
191 max_attempts: 0,
192 ..MySqlPoolSettings::default()
193 };
194 assert!(matches!(
195 connect_mysql_pool("mysql://localhost/example", &settings).await,
196 Err(MySqlConnectionError::InvalidMaxAttempts)
197 ));
198 }
199}