Skip to content
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
115 changes: 100 additions & 15 deletions crates/database/src/db/pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::time::{Duration, Instant};

use futures_util::future::{BoxFuture, join_all};
use sqlx::pool::{PoolConnection, PoolOptions};
use sqlx::{Connection as _, Pool, SqlStr};
use sqlx::{ConnectOptions as _, Connection as _, Pool, SqlStr};
use sqlx_core::transaction::TransactionManager;
use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};

Expand Down Expand Up @@ -423,6 +423,7 @@ impl Group {
let pools = self.pools::<DB>(entry, endpoint).await?;
let start = self.preferred(state, pools.len())?;
let mut last_error = sqlx::Error::PoolClosed;
let mut last_host = None;
for offset in 0..pools.len() {
let index = (start + offset) % pools.len();
// SQLx's acquire future holds its whole connect and TLS handshake. Erasing its type keeps...
Expand All @@ -438,7 +439,10 @@ impl Group {
}
return Ok(connection);
}
Err(error) => last_error = error,
Err(error) => {
last_error = error;
last_host = Some(&pools[index]);
}
}
if self.retired.load(Ordering::Acquire) {
break;
Expand All @@ -447,16 +451,26 @@ impl Group {

// A pool with no connection timed out connecting, not waiting for a connection in use.
let held = pools.iter().any(|host| host.pool.size() > 0);
let context =
if matches!(self.mode, Mode::Test { .. }) && held && matches!(last_error, sqlx::Error::PoolTimedOut) {
format!(
"couldn't acquire a connection to database `{}`: a test that refreshes the database runs on \
one connection, and an unfinished transaction or query is holding it",
let context = if is_connection_refused(&last_error) {
match last_host.and_then(|host| host_endpoint::<DB>(&host.pool.connect_options())) {
Some(address) => format!(
"couldn't connect to database `{}` at `{address}`; make sure the database server is running",
entry.name
)
} else {
format!("couldn't acquire a connection to database `{}`", entry.name)
};
),
None => format!(
"couldn't connect to database `{}`; make sure the database server is running",
entry.name
),
}
} else if matches!(self.mode, Mode::Test { .. }) && held && matches!(last_error, sqlx::Error::PoolTimedOut) {
format!(
"couldn't acquire a connection to database `{}`: a test that refreshes the database runs on \
one connection, and an unfinished transaction or query is holding it",
entry.name
)
} else {
format!("couldn't acquire a connection to database `{}`", entry.name)
};
use crate::error::ErrorInternals as _;

Err(crate::Error::wrap(last_error, context))
Expand All @@ -480,8 +494,9 @@ fn lease<DB: Backend>(
let parking = host.parking.clone();
async move {
let Some(parking) = parking else {
let probe = !matches!(DB::DRIVER, Driver::Sqlite) && pool.size() == 0;
return Ok(Lease {
connection: Some(pool.acquire().await?),
connection: Some(acquire_from_pool(&pool, deadline, probe).await?),
parking: None,
leased_at: Instant::now(),
clean: false,
Expand All @@ -495,9 +510,7 @@ fn lease<DB: Backend>(
Some(parked) => (parked.connection, parked.leased_at),
// `SQLx`'s own acquire timeout stays as a backstop.
None => (
tokio::time::timeout_at(deadline, pool.acquire())
.await
.map_err(|_| sqlx::Error::PoolTimedOut)??,
acquire_from_pool(&pool, deadline, !matches!(DB::DRIVER, Driver::Sqlite)).await?,
Instant::now(),
),
};
Expand All @@ -510,6 +523,78 @@ fn lease<DB: Backend>(
}
}

/// How long to wait before probing a connecting pool directly so a refused server doesn't sit in
/// `SQLx`'s `ConnectionRefused` retry loop for the whole `acquire_timeout`.
const REFUSED_PROBE_DELAY: Duration = Duration::from_secs(3);

async fn acquire_from_pool<DB: Backend>(
pool: &Pool<DB>,
deadline: tokio::time::Instant,
probe_refused: bool,
) -> sqlx::Result<PoolConnection<DB>> {
let acquire = pool.acquire();
let future = async {
if !probe_refused {
return acquire.await;
}

let probe = async {
tokio::time::sleep(REFUSED_PROBE_DELAY).await;
let options = pool.connect_options();
match options.connect().await {
Ok(connection) => {
let _ = connection.close().await;
std::future::pending::<sqlx::Error>().await
}
Err(error) if is_connection_refused(&error) => error,
Err(_) => std::future::pending::<sqlx::Error>().await,
}
};

tokio::select! {
result = acquire => result,
error = probe => Err(error),
}
};

tokio::time::timeout_at(deadline, future)
.await
.map_err(|_| sqlx::Error::PoolTimedOut)?
}

fn is_connection_refused(error: &sqlx::Error) -> bool {
matches!(error, sqlx::Error::Io(io) if io.kind() == std::io::ErrorKind::ConnectionRefused)
}

fn host_endpoint<DB: Backend>(options: &<DB::Connection as sqlx::Connection>::Options) -> Option<String> {
let options: &dyn Any = options;
#[cfg(feature = "database-postgres")]
if let Some(pg) = options.downcast_ref::<sqlx::postgres::PgConnectOptions>() {
return Some(match pg.get_socket() {
Some(socket) => socket.display().to_string(),
None => format_host_port(pg.get_host(), pg.get_port()),
});
}
#[cfg(feature = "database-mysql")]
if let Some(mysql) = options.downcast_ref::<sqlx::mysql::MySqlConnectOptions>() {
return Some(match mysql.get_socket() {
Some(socket) => socket.display().to_string(),
None => format_host_port(mysql.get_host(), mysql.get_port()),
});
}
let _ = options;
None
}

#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
fn format_host_port(host: &str, port: u16) -> String {
if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
}
}

fn lazy_pools<DB: Backend>(entry: &Entry, endpoint: Option<&Endpoint>, mode: &Mode) -> Result<Vec<Host<DB>>> {
let config = &entry.config;
// A test's own database replaces the connection's, on its own host.
Expand Down
25 changes: 25 additions & 0 deletions tests/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,3 +671,28 @@ async fn mysql_migrate_force_creates_a_missing_database_and_fresh_drops_its_tabl
assert_eq!(checks, Some(1), "fresh should turn foreign key checks back on");
Ok(())
}

#[cfg(feature = "database-postgres")]
#[tokio::test]
async fn migrate_fails_fast_when_the_database_server_is_not_running() -> laravel::Result<()> {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
drop(listener);

let url = format!("postgres://postgres@127.0.0.1:{port}/laravel");
let app = on_server("postgres", &url);

let migrate = tokio::time::timeout(std::time::Duration::from_secs(10), app.command("migrate"))
.await
.expect("migrate should fail fast on connection refused instead of waiting for acquire_timeout");
migrate.assert_failed();
migrate.assert_error_output_contains(&format!(
"couldn't connect to database `postgres` at `127.0.0.1:{port}`; make sure the database server is running"
));
assert!(
!migrate.error_output().contains("pool timed out"),
"expected connection refused, not pool timeout: {}",
migrate.error_output()
);
Ok(())
}