1use rocket::figment::Figment;
2
3#[allow(unused_imports)]
4use {std::time::Duration, crate::{Error, Config}};
5
6#[rocket::async_trait]
117pub trait Pool: Sized + Send + Sync + 'static {
118 type Connection;
120
121 type Error: std::error::Error;
123
124 async fn init(figment: &Figment) -> Result<Self, Self::Error>;
137
138 async fn get(&self) -> Result<Self::Connection, Self::Error>;
146
147 async fn close(&self);
153}
154
155#[rocket::async_trait]
161pub trait Configurable: Pool {
162 type Options: Send;
172
173 async fn init_with<F>(figment: &Figment, f: F) -> Result<Self, Self::Error>
183 where F: FnOnce(&Config, Self::Options) -> Result<Self::Options, Self::Error> + Send;
184}
185
186#[cfg(all(
193 feature = "postgres_rustls_native_certs",
194 any(feature = "deadpool_postgres", feature = "diesel_postgres")
195))]
196fn tokio_postgres_tls_provider() -> tokio_postgres_rustls::MakeRustlsConnect {
197 use std::sync::Arc;
198
199 let native = rustls_native_certs::load_native_certs();
200 for e in &native.errors {
201 rocket::warn!("Failed to load native root certificates: {e}");
202 }
203
204 let mut roots = rustls::RootCertStore::empty();
205 let (added, ignored) = roots.add_parsable_certificates(native.certs);
206 if ignored > 0 {
207 rocket::warn!("Ignored {ignored} unparsable native root certificate(s).");
208 }
209
210 if added == 0 {
211 rocket::warn!("No root certificates found: Postgres TLS connections will fail.");
212 rocket::info_!("Set SSL_CERT_FILE or SSL_CERT_DIR to trust a custom CA bundle.");
213 }
214
215 let provider = Arc::new(rustls::crypto::ring::default_provider());
217 let config = rustls::ClientConfig::builder_with_provider(provider)
218 .with_safe_default_protocol_versions()
219 .expect("ring's default provider supports the default protocol versions")
220 .with_root_certificates(roots)
221 .with_no_client_auth();
222
223 tokio_postgres_rustls::MakeRustlsConnect::new(config)
224}
225
226#[cfg(feature = "deadpool")]
227mod deadpool {
228 use deadpool::{Runtime, managed::{Manager, Pool, PoolError, Object}};
229 use super::{Duration, Error, Config, Figment};
230
231 #[cfg(any(feature = "diesel_postgres", feature = "diesel_mysql"))]
232 use diesel_async::pooled_connection::AsyncDieselConnectionManager;
233
234 pub trait DeadManager: Manager + Sized + Send + Sync + 'static {
235 fn new(config: &Config, figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>>;
236 }
237
238 #[cfg(feature = "deadpool_postgres")]
239 impl DeadManager for deadpool_postgres::Manager {
240 fn new(config: &Config, _figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>> {
241 #[cfg(feature = "postgres_rustls_native_certs")]
242 let tls_provider = super::tokio_postgres_tls_provider();
243
244 #[cfg(not(feature = "postgres_rustls_native_certs"))]
245 let tls_provider = deadpool_postgres::tokio_postgres::NoTls;
246
247 let config = config.url.parse().map_err(|e| Error::Init(PoolError::Backend(e)))?;
248 Ok(Self::new(config, tls_provider))
249 }
250 }
251
252 #[cfg(feature = "deadpool_redis")]
253 impl DeadManager for deadpool_redis::Manager {
254 fn new(config: &Config, figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>> {
255 let connection_config = deadpool_redis::redis::AsyncConnectionConfig::new()
256 .set_connection_timeout(None)
257 .set_response_timeout(redis_response_timeout(figment)?);
258
259 Self::new_with_config(config.url.as_str(), connection_config)
260 .map_err(|e| Error::Init(PoolError::Backend(e)))
261 }
262 }
263
264 #[cfg(feature = "deadpool_redis")]
265 fn redis_response_timeout(
266 figment: &Figment
267 ) -> Result<Option<Duration>, rocket::figment::Error> {
268 use rocket::serde::{Deserialize, Deserializer, de::Error};
269
270 #[derive(Deserialize)]
271 #[serde(crate = "rocket::serde")]
272 struct Options {
273 #[serde(default = "default_timeout", deserialize_with = "deserialize_timeout")]
274 response_timeout: Option<Duration>,
275 }
276
277 fn default_timeout() -> Option<Duration> {
278 Some(Duration::from_millis(500))
279 }
280
281 fn deserialize_timeout<'de, D: Deserializer<'de>>(
282 de: D
283 ) -> Result<Option<Duration>, D::Error> {
284 let seconds = f64::deserialize(de)?;
285 let timeout = Duration::try_from_secs_f64(seconds).map_err(D::Error::custom)?;
286 Ok((seconds != 0.0).then_some(timeout))
287 }
288
289 Ok(figment.extract::<Options>()?.response_timeout)
290 }
291
292 #[cfg(feature = "diesel_postgres")]
293 impl DeadManager for AsyncDieselConnectionManager<diesel_async::AsyncPgConnection> {
294 fn new(config: &Config, _figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>> {
295 #[cfg(feature = "postgres_rustls_native_certs")]
296 use diesel_async::AsyncPgConnection;
297 use diesel_async::pooled_connection::ManagerConfig;
298
299 let diesel_config = ManagerConfig::default();
300
301 #[cfg(feature = "postgres_rustls_native_certs")]
302 let diesel_config = {
303 let mut diesel_config = diesel_config;
304 let tls_provider = super::tokio_postgres_tls_provider();
305
306 diesel_config.custom_setup = Box::new(move |url| {
307 let tls_provider = tls_provider.clone();
308 Box::pin(async move {
309 let (client, conn) = tokio_postgres::connect(url, tls_provider)
310 .await
311 .map_err(|e| diesel::ConnectionError::BadConnection(e.to_string()))?;
312
313 AsyncPgConnection::try_from_client_and_connection(client, conn).await
314 }) as std::pin::Pin<Box<_>>
315 });
316
317 diesel_config
318 };
319
320 Ok(Self::new_with_config(config.url.as_str(), diesel_config))
321 }
322 }
323
324 #[cfg(feature = "diesel_mysql")]
325 impl DeadManager for AsyncDieselConnectionManager<diesel_async::AsyncMysqlConnection> {
326 fn new(config: &Config, _figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>> {
327 Ok(Self::new(config.url.as_str()))
328 }
329 }
330
331 #[rocket::async_trait]
332 impl<M: DeadManager, C: From<Object<M>>> crate::Pool for Pool<M, C>
333 where M::Type: Send, C: Send + 'static, M::Error: std::error::Error
334 {
335 type Error = Error<PoolError<M::Error>>;
336
337 type Connection = C;
338
339 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
340 let config: Config = figment.extract()?;
341 let manager = M::new(&config, figment)?;
342
343 Pool::builder(manager)
344 .max_size(config.max_connections)
345 .wait_timeout(Some(Duration::from_secs(config.connect_timeout)))
346 .create_timeout(Some(Duration::from_secs(config.connect_timeout)))
347 .recycle_timeout(config.idle_timeout.map(Duration::from_secs))
348 .runtime(Runtime::Tokio1)
349 .build()
350 .map_err(|_| Error::Init(PoolError::NoRuntimeSpecified))
351 }
352
353 async fn get(&self) -> Result<Self::Connection, Self::Error> {
354 self.get().await.map_err(Error::Get)
355 }
356
357 async fn close(&self) {
358 <Pool<M, C>>::close(self)
359 }
360 }
361}
362
363#[cfg(feature = "sqlx")]
364mod sqlx {
365 use sqlx::ConnectOptions;
366 use crate::Configurable;
367 use super::{Duration, Error, Config, Figment};
368 use rocket::config::LogLevel;
369
370 type Options<D> = <<D as sqlx::Database>::Connection as sqlx::Connection>::Options;
371
372 fn specialize(__options: &mut dyn std::any::Any, __config: &Config, __figment: &Figment) {
374 #[cfg(feature = "sqlx_sqlite")]
375 if let Some(o) = __options.downcast_mut::<sqlx::sqlite::SqliteConnectOptions>() {
376 *o = std::mem::take(o)
377 .busy_timeout(Duration::from_secs(__config.connect_timeout))
378 .create_if_missing(true);
379
380 if let Some(md) = __figment.find_metadata("extensions") {
381 use rocket::yansi::Paint;
382
383 rocket::warn!("found value for deprecated SQLite config key `{}`",
384 "extensions".bold().primary());
385 if let Some(ref source) = md.source {
386 rocket::warn_!("in {} {}", source.primary(), md.name);
387 }
388
389 rocket::warn_!("key has no special meaning");
390 }
391 }
392 }
393
394 #[rocket::async_trait]
395 impl<D: sqlx::Database> crate::Pool for sqlx::Pool<D> {
396 type Error = Error<sqlx::Error>;
397
398 type Connection = sqlx::pool::PoolConnection<D>;
399
400 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
401 Self::init_with(figment, |_, opts| Ok(opts)).await
402 }
403
404 async fn get(&self) -> Result<Self::Connection, Self::Error> {
405 self.acquire().await.map_err(Error::Get)
406 }
407
408 async fn close(&self) {
409 <sqlx::Pool<D>>::close(self).await;
410 }
411 }
412
413 #[rocket::async_trait]
414 impl<D: sqlx::Database> Configurable for sqlx::Pool<D> {
415 type Options = (sqlx::pool::PoolOptions<D>, Options<D>);
416
417 async fn init_with<F>(figment: &Figment, f: F) -> Result<Self, Self::Error>
418 where F: FnOnce(&Config, Self::Options) -> Result<Self::Options, Self::Error> + Send
419 {
420 let config = figment.extract::<Config>()?;
421 let mut opts = config.url.parse::<Options<D>>().map_err(Error::Init)?;
422 specialize(&mut opts, &config, figment);
423
424 opts = opts.disable_statement_logging();
425 if let Ok(level) = figment.extract_inner::<LogLevel>(rocket::Config::LOG_LEVEL) {
426 if !matches!(level, LogLevel::Normal | LogLevel::Off) {
427 opts = opts.log_statements(level.into())
428 .log_slow_statements(level.into(), Duration::default());
429 }
430 }
431
432 let pool = sqlx::pool::PoolOptions::new()
433 .max_connections(config.max_connections as u32)
434 .acquire_timeout(Duration::from_secs(config.connect_timeout))
435 .idle_timeout(config.idle_timeout.map(Duration::from_secs))
436 .min_connections(config.min_connections.unwrap_or_default());
437
438 let (pool, opts) = f(&config, (pool, opts))?;
439 pool.connect_with(opts)
440 .await
441 .map_err(Error::Init)
442 }
443 }
444}
445
446#[cfg(feature = "mongodb")]
447mod mongodb {
448 use mongodb::{Client, options::ClientOptions};
449 use crate::Configurable;
450 use super::{Duration, Error, Config, Figment};
451
452 #[rocket::async_trait]
453 impl crate::Pool for Client {
454 type Error = Error<mongodb::error::Error, std::convert::Infallible>;
455
456 type Connection = Client;
457
458 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
459 Self::init_with(figment, |_, opts| Ok(opts)).await
460 }
461
462 async fn get(&self) -> Result<Self::Connection, Self::Error> {
463 Ok(self.clone())
464 }
465
466 async fn close(&self) {
467 }
469 }
470
471 #[rocket::async_trait]
472 impl Configurable for Client {
473 type Options = ClientOptions;
474
475 async fn init_with<F>(figment: &Figment, f: F) -> Result<Self, Self::Error>
476 where F: FnOnce(&Config, Self::Options) -> Result<Self::Options, Self::Error> + Send
477 {
478 let config = figment.extract::<Config>()?;
479 let mut opts = ClientOptions::parse(&config.url).await.map_err(Error::Init)?;
480 opts.min_pool_size = config.min_connections;
481 opts.max_pool_size = Some(config.max_connections as u32);
482 opts.max_idle_time = config.idle_timeout.map(Duration::from_secs);
483 opts.connect_timeout = Some(Duration::from_secs(config.connect_timeout));
484 opts.server_selection_timeout = Some(Duration::from_secs(config.connect_timeout));
485 let opts = f(&config, opts)?;
486 Client::with_options(opts).map_err(Error::Init)
487 }
488 }
489}