-
-
Notifications
You must be signed in to change notification settings - Fork 90
Add an example of using a pooled bb8 connection with rustls #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
weiznich
merged 3 commits into
weiznich:main
from
ThouCheese:postgres-pool-rustls-example
Mar 20, 2023
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
/target | ||
**/target | ||
Cargo.lock |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
[package] | ||
name = "pooled-with-rustls" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] | ||
diesel = { version = "2.0.2", default-features = false, features = ["postgres"] } | ||
diesel-async = { version = "0.2.0", path = "../../../", features = ["bb8", "postgres"] } | ||
futures-util = "0.3.21" | ||
rustls = "0.20.8" | ||
rustls-native-certs = "0.6.2" | ||
tokio = { version = "1.2.0", default-features = false, features = ["macros", "rt-multi-thread"] } | ||
tokio-postgres = "0.7.7" | ||
tokio-postgres-rustls = "0.9.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
use diesel::{ConnectionError, ConnectionResult}; | ||
use diesel_async::pooled_connection::bb8::Pool; | ||
use diesel_async::pooled_connection::AsyncDieselConnectionManager; | ||
use diesel_async::AsyncPgConnection; | ||
use futures_util::future::BoxFuture; | ||
use futures_util::FutureExt; | ||
use std::time::Duration; | ||
|
||
#[tokio::main] | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
let db_url = std::env::var("DATABASE_URL").expect("Env var `DATABASE_URL` not set"); | ||
|
||
// First we have to construct a connection manager with our custom `establish_connection` | ||
// function | ||
let mgr = AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_setup( | ||
db_url, | ||
establish_connection, | ||
); | ||
// From that connection we can then create a pool, here given with some example settings. | ||
// | ||
// This creates a TLS configuration that's equivalent to `libpq'` `sslmode=verify-full`, which | ||
// means this will check whether the provided certificate is valid for the given database host. | ||
// | ||
// `libpq` does not perform these checks by default (https://www.postgresql.org/docs/current/libpq-connect.html) | ||
// If you hit a TLS error while conneting to the database double check your certificates | ||
let pool = Pool::builder() | ||
.max_size(10) | ||
.min_idle(Some(5)) | ||
.max_lifetime(Some(Duration::from_secs(60 * 60 * 24))) | ||
.idle_timeout(Some(Duration::from_secs(60 * 2))) | ||
.build(mgr) | ||
.await?; | ||
|
||
// Now we can use our pool to run queries over a TLS-secured connection: | ||
let conn = pool.get().await?; | ||
let _ = conn; | ||
|
||
Ok(()) | ||
} | ||
|
||
fn establish_connection(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> { | ||
let fut = async { | ||
// We first set up the way we want rustls to work. | ||
let rustls_config = rustls::ClientConfig::builder() | ||
.with_safe_defaults() | ||
.with_root_certificates(root_certs()) | ||
.with_no_client_auth(); | ||
let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config); | ||
let (client, conn) = tokio_postgres::connect(config, tls) | ||
.await | ||
.map_err(|e| ConnectionError::BadConnection(e.to_string()))?; | ||
tokio::spawn(async move { | ||
if let Err(e) = conn.await { | ||
eprintln!("Database connection: {e}"); | ||
} | ||
}); | ||
AsyncPgConnection::try_from(client).await | ||
}; | ||
fut.boxed() | ||
} | ||
|
||
fn root_certs() -> rustls::RootCertStore { | ||
let mut roots = rustls::RootCertStore::empty(); | ||
let certs = rustls_native_certs::load_native_certs().expect("Certs not loadable!"); | ||
let certs: Vec<_> = certs.into_iter().map(|cert| cert.0).collect(); | ||
roots.add_parsable_certificates(&certs); | ||
roots | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.