|
| 1 | +use diesel::{ConnectionError, ConnectionResult}; |
| 2 | +use diesel_async::pooled_connection::bb8::Pool; |
| 3 | +use diesel_async::pooled_connection::AsyncDieselConnectionManager; |
| 4 | +use diesel_async::AsyncPgConnection; |
| 5 | +use futures_util::future::BoxFuture; |
| 6 | +use futures_util::FutureExt; |
| 7 | +use std::time::Duration; |
| 8 | + |
| 9 | +#[tokio::main] |
| 10 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 11 | + let db_url = std::env::var("DATABASE_URL").expect("Env var `DATABASE_URL` not set"); |
| 12 | + |
| 13 | + // First we have to construct a connection manager with our custom `establish_connection` |
| 14 | + // function |
| 15 | + let mgr = AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_setup( |
| 16 | + db_url, |
| 17 | + establish_connection, |
| 18 | + ); |
| 19 | + // From that connection we can then create a pool, here given with some example settings. |
| 20 | + // |
| 21 | + // This creates a TLS configuration that's equivalent to `libpq'` `sslmode=verify-full`, which |
| 22 | + // means this will check whether the provided certificate is valid for the given database host. |
| 23 | + // |
| 24 | + // `libpq` does not perform these checks by default (https://www.postgresql.org/docs/current/libpq-connect.html) |
| 25 | + // If you hit a TLS error while conneting to the database double check your certificates |
| 26 | + let pool = Pool::builder() |
| 27 | + .max_size(10) |
| 28 | + .min_idle(Some(5)) |
| 29 | + .max_lifetime(Some(Duration::from_secs(60 * 60 * 24))) |
| 30 | + .idle_timeout(Some(Duration::from_secs(60 * 2))) |
| 31 | + .build(mgr) |
| 32 | + .await?; |
| 33 | + |
| 34 | + // Now we can use our pool to run queries over a TLS-secured connection: |
| 35 | + let conn = pool.get().await?; |
| 36 | + let _ = conn; |
| 37 | + |
| 38 | + Ok(()) |
| 39 | +} |
| 40 | + |
| 41 | +fn establish_connection(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> { |
| 42 | + let fut = async { |
| 43 | + // We first set up the way we want rustls to work. |
| 44 | + let rustls_config = rustls::ClientConfig::builder() |
| 45 | + .with_safe_defaults() |
| 46 | + .with_root_certificates(root_certs()) |
| 47 | + .with_no_client_auth(); |
| 48 | + let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config); |
| 49 | + let (client, conn) = tokio_postgres::connect(config, tls) |
| 50 | + .await |
| 51 | + .map_err(|e| ConnectionError::BadConnection(e.to_string()))?; |
| 52 | + tokio::spawn(async move { |
| 53 | + if let Err(e) = conn.await { |
| 54 | + eprintln!("Database connection: {e}"); |
| 55 | + } |
| 56 | + }); |
| 57 | + AsyncPgConnection::try_from(client).await |
| 58 | + }; |
| 59 | + fut.boxed() |
| 60 | +} |
| 61 | + |
| 62 | +fn root_certs() -> rustls::RootCertStore { |
| 63 | + let mut roots = rustls::RootCertStore::empty(); |
| 64 | + let certs = rustls_native_certs::load_native_certs().expect("Certs not loadable!"); |
| 65 | + let certs: Vec<_> = certs.into_iter().map(|cert| cert.0).collect(); |
| 66 | + roots.add_parsable_certificates(&certs); |
| 67 | + roots |
| 68 | +} |
0 commit comments