Skip to content

Allow database timeouts to be configured #1344

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
merged 1 commit into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::env;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use diesel::r2d2;
use git2;
Expand Down Expand Up @@ -71,11 +72,19 @@ impl App {
_ => 1,
};

let db_connection_timeout = match (env::var("DB_TIMEOUT"), config.env) {
(Ok(num), _) => num.parse().expect("couldn't parse DB_TIMEOUT"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in the long run we might want to make this error message a little better but it's fine for now

(_, ::Env::Production) => 10,
_ => 30,
};

let thread_pool = Arc::new(ScheduledThreadPool::new(db_helper_threads));

let diesel_db_config = r2d2::Pool::builder()
.max_size(db_pool_size)
.min_idle(db_min_idle)
.connection_timeout(Duration::from_secs(db_connection_timeout))
.connection_customizer(Box::new(db::SetStatementTimeout(db_connection_timeout)))
.thread_pool(thread_pool);

let repo = git2::Repository::open(&config.git_repo_checkout).unwrap();
Expand Down
18 changes: 16 additions & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::env;

use conduit::Request;
use diesel::prelude::{ConnectionResult, PgConnection};
use diesel::r2d2::{self, ConnectionManager};
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager, CustomizeConnection};
use url::Url;

use middleware::app::RequestApp;
Expand Down Expand Up @@ -44,3 +44,17 @@ impl<T: Request + ?Sized> RequestTransaction for T {
self.app().diesel_database.get().map_err(Into::into)
}
}

#[derive(Debug, Clone, Copy)]
pub struct SetStatementTimeout(pub u64);

impl CustomizeConnection<PgConnection, r2d2::Error> for SetStatementTimeout {
fn on_acquire(&self, conn: &mut PgConnection) -> Result<(), r2d2::Error> {
use diesel::sql_query;

sql_query(format!("SET statement_timeout = {}", self.0 * 1000))
.execute(conn)
.map_err(r2d2::Error::QueryError)?;
Ok(())
}
}