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 + '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\n\
212 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(feature = "diesel")]
232 use diesel_async::pooled_connection::AsyncDieselConnectionManager;
233
234 pub trait DeadManager: Manager + Sized + Send + '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 #[cfg(feature = "diesel_sqlite")]
332 impl DeadManager for AsyncDieselConnectionManager<
333 diesel_async::sync_connection_wrapper::SyncConnectionWrapper::<diesel::SqliteConnection>
334 > {
335 fn new(config: &Config, _figment: &Figment) -> Result<Self, Error<PoolError<Self::Error>>> {
336 Ok(Self::new(config.url.as_str()))
337 }
338 }
339
340 #[rocket::async_trait]
341 impl<M: DeadManager, C: From<Object<M>>> crate::Pool for Pool<M, C>
342 where M::Type: Send, C: Send + 'static, M::Error: std::error::Error
343 {
344 type Error = Error<PoolError<M::Error>>;
345
346 type Connection = C;
347
348 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
349 let config: Config = figment.extract()?;
350 let manager = M::new(&config, figment)?;
351
352 Pool::builder(manager)
353 .max_size(config.max_connections)
354 .wait_timeout(Some(Duration::from_secs(config.connect_timeout)))
355 .create_timeout(Some(Duration::from_secs(config.connect_timeout)))
356 .recycle_timeout(config.idle_timeout.map(Duration::from_secs))
357 .runtime(Runtime::Tokio1)
358 .build()
359 .map_err(|_| Error::Init(PoolError::NoRuntimeSpecified))
360 }
361
362 async fn get(&self) -> Result<Self::Connection, Self::Error> {
363 self.get().await.map_err(Error::Get)
364 }
365
366 async fn close(&self) {
367 <Pool<M, C>>::close(self)
368 }
369 }
370}
371
372#[cfg(feature = "sqlx")]
373mod sqlx {
374 use sqlx::ConnectOptions;
375 use crate::Configurable;
376 use super::{Duration, Error, Config, Figment};
377 use rocket::tracing::level_filters::LevelFilter;
378
379 type Options<D> = <<D as sqlx::Database>::Connection as sqlx::Connection>::Options;
380
381 fn specialize(__options: &mut dyn std::any::Any, __config: &Config, __figment: &Figment) {
383 #[cfg(feature = "sqlx_sqlite")]
384 if let Some(o) = __options.downcast_mut::<sqlx::sqlite::SqliteConnectOptions>() {
385 *o = std::mem::take(o)
386 .busy_timeout(Duration::from_secs(__config.connect_timeout))
387 .create_if_missing(true);
388
389 if let Some(source) = __figment.find_metadata("extensions") {
390 rocket::warn!(
391 %source.name,
392 source.source = source.source.as_ref().map(rocket::tracing::field::display),
393 "found value for deprecated SQLite config key `extensions`\n\
394 key has no special meaning");
395 }
396 }
397 }
398
399 #[rocket::async_trait]
400 impl<D: sqlx::Database> crate::Pool for sqlx::Pool<D> {
401 type Error = Error<sqlx::Error>;
402
403 type Connection = sqlx::pool::PoolConnection<D>;
404
405 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
406 Self::init_with(figment, |_, opts| Ok(opts)).await
407 }
408
409 async fn get(&self) -> Result<Self::Connection, Self::Error> {
410 self.acquire().await.map_err(Error::Get)
411 }
412
413 async fn close(&self) {
414 <sqlx::Pool<D>>::close(self).await;
415 }
416 }
417
418 #[rocket::async_trait]
419 impl<D: sqlx::Database> Configurable for sqlx::Pool<D> {
420 type Options = (sqlx::pool::PoolOptions<D>, Options<D>);
421
422 async fn init_with<F>(figment: &Figment, f: F) -> Result<Self, Self::Error>
423 where F: FnOnce(&Config, Self::Options) -> Result<Self::Options, Self::Error> + Send
424 {
425 let config = figment.extract::<Config>()?;
426 let mut opts = config.url.parse::<Options<D>>().map_err(Error::Init)?;
427 specialize(&mut opts, &config, figment);
428
429 opts = opts.disable_statement_logging();
430 if let Ok(value) = figment.find_value(rocket::Config::LOG_LEVEL) {
431 if let Some(level) = value.as_str().and_then(|v| v.parse().ok()) {
432 let log_level = match level {
433 LevelFilter::OFF => log::LevelFilter::Off,
434 LevelFilter::ERROR => log::LevelFilter::Error,
435 LevelFilter::WARN => log::LevelFilter::Warn,
436 LevelFilter::INFO => log::LevelFilter::Info,
437 LevelFilter::DEBUG => log::LevelFilter::Debug,
438 LevelFilter::TRACE => log::LevelFilter::Trace,
439 };
440
441 opts = opts.log_statements(log_level)
442 .log_slow_statements(log_level, Duration::default());
443 }
444 }
445
446 let pool = sqlx::pool::PoolOptions::new()
447 .max_connections(config.max_connections as u32)
448 .acquire_timeout(Duration::from_secs(config.connect_timeout))
449 .idle_timeout(config.idle_timeout.map(Duration::from_secs))
450 .min_connections(config.min_connections.unwrap_or_default());
451
452 let (pool, opts) = f(&config, (pool, opts))?;
453 Ok(pool.connect_lazy_with(opts))
454 }
455 }
456}
457
458#[cfg(feature = "mongodb")]
459mod mongodb {
460 use mongodb::{Client, options::ClientOptions};
461 use crate::Configurable;
462 use super::{Duration, Error, Config, Figment};
463
464 #[rocket::async_trait]
465 impl crate::Pool for Client {
466 type Error = Error<mongodb::error::Error, std::convert::Infallible>;
467
468 type Connection = Client;
469
470 async fn init(figment: &Figment) -> Result<Self, Self::Error> {
471 Self::init_with(figment, |_, opts| Ok(opts)).await
472 }
473
474 async fn get(&self) -> Result<Self::Connection, Self::Error> {
475 Ok(self.clone())
476 }
477
478 async fn close(&self) {
479 }
481 }
482
483 #[rocket::async_trait]
484 impl Configurable for Client {
485 type Options = ClientOptions;
486
487 async fn init_with<F>(figment: &Figment, f: F) -> Result<Self, Self::Error>
488 where F: FnOnce(&Config, Self::Options) -> Result<Self::Options, Self::Error> + Send
489 {
490 let config = figment.extract::<Config>()?;
491 let mut opts = ClientOptions::parse(&config.url).await.map_err(Error::Init)?;
492 opts.min_pool_size = config.min_connections;
493 opts.max_pool_size = Some(config.max_connections as u32);
494 opts.max_idle_time = config.idle_timeout.map(Duration::from_secs);
495 opts.connect_timeout = Some(Duration::from_secs(config.connect_timeout));
496 opts.server_selection_timeout = Some(Duration::from_secs(config.connect_timeout));
497 let opts = f(&config, opts)?;
498 Client::with_options(opts).map_err(Error::Init)
499 }
500 }
501}