diff --git a/docs/database.md b/docs/database.md index 2a41db3..3b97540 100644 --- a/docs/database.md +++ b/docs/database.md @@ -90,6 +90,10 @@ async def startup(): await app.setup_database( "postgresql://user:password@localhost:5432/dbname", max_connections=20, + min_connections=2, # connections kept open + acquire_timeout_secs=10, # give up waiting for a free connection after 10 s + idle_timeout_secs=300, # close connections idle for 5 minutes + max_lifetime_secs=1800, # recycle connections after 30 minutes ) @app.on_shutdown diff --git a/oxyroute/_oxyroute.pyi b/oxyroute/_oxyroute.pyi index c9b4006..3b5ddb6 100644 --- a/oxyroute/_oxyroute.pyi +++ b/oxyroute/_oxyroute.pyi @@ -52,9 +52,10 @@ class App: def setup_database( self, url: str, - min_connections: int = 1, max_connections: int = 10, - acquire_timeout_secs: float = 30.0, + *, + min_connections: int = 1, + acquire_timeout_secs: float = 3.0, idle_timeout_secs: float = 600.0, max_lifetime_secs: float = 1800.0, ) -> Coroutine[Any, Any, None]: ... diff --git a/oxyroute/app.py b/oxyroute/app.py index f029f79..029fb8d 100644 --- a/oxyroute/app.py +++ b/oxyroute/app.py @@ -335,12 +335,34 @@ def _docs() -> Response: self._docs_ui = ui_n self._docs_mounted = True - async def setup_database(self, url: str, max_connections: int = 10) -> None: + async def setup_database( + self, + url: str, + max_connections: int = 10, + *, + min_connections: int = 1, + acquire_timeout_secs: float = 3.0, + idle_timeout_secs: float = 600.0, + max_lifetime_secs: float = 1800.0, + ) -> None: """ Connect to a PostgreSQL database and store the pool in the Rust hot path. Must be awaited (e.g. inside ``on_startup``). - """ - await self._app.setup_database(url, max_connections) + + Pool tuning (all durations are seconds and must be finite and >= 0): + ``min_connections`` and ``max_connections`` bound the pool size, + ``acquire_timeout_secs`` is how long to wait for a free connection, + ``idle_timeout_secs`` closes connections left idle that long, and + ``max_lifetime_secs`` recycles connections after that long. + """ + await self._app.setup_database( + url, + max_connections, + min_connections=min_connections, + acquire_timeout_secs=acquire_timeout_secs, + idle_timeout_secs=idle_timeout_secs, + max_lifetime_secs=max_lifetime_secs, + ) async def close_database(self) -> None: """ diff --git a/src/lib.rs b/src/lib.rs index 021ecd3..1411cad 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ use std::collections::HashSet; use std::str::FromStr; use std::sync::Arc; +use std::time::Duration; use parking_lot::RwLock; @@ -27,6 +28,19 @@ mod websocket; use dispatch::{run_rsgi, try_rsgi_sync_short_circuit}; use state::AppState; +/// Convert a Python float of seconds to a `Duration`, rejecting values that would panic +/// (negative, NaN, infinite or too large). +fn secs_to_duration(name: &str, value: f64) -> PyResult { + if !value.is_finite() || value < 0.0 { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "{name} must be a finite number >= 0, got {value}" + ))); + } + Duration::try_from_secs_f64(value).map_err(|_| { + pyo3::exceptions::PyValueError::new_err(format!("{name} is too large: {value}")) + }) +} + /// Hidden Criterion / microbench surface (issue #110). Not part of the stable Python API. #[doc(hidden)] pub mod microbench { @@ -840,17 +854,37 @@ impl App { } /// Connect to a PostgreSQL database and store the pool in `AppState`. - #[pyo3(signature = (url, max_connections=10))] + #[pyo3(signature = ( + url, + max_connections=10, + *, + min_connections=1, + acquire_timeout_secs=3.0, + idle_timeout_secs=600.0, + max_lifetime_secs=1800.0 + ))] + #[allow(clippy::too_many_arguments)] fn setup_database<'py>( &self, py: Python<'py>, url: String, max_connections: u32, + min_connections: u32, + acquire_timeout_secs: f64, + idle_timeout_secs: f64, + max_lifetime_secs: f64, ) -> PyResult> { + let acquire_timeout = secs_to_duration("acquire_timeout_secs", acquire_timeout_secs)?; + let idle_timeout = secs_to_duration("idle_timeout_secs", idle_timeout_secs)?; + let max_lifetime = secs_to_duration("max_lifetime_secs", max_lifetime_secs)?; let state = self.state.clone(); pyo3_async_runtimes::tokio::future_into_py(py, async move { let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(max_connections) + .min_connections(min_connections) + .acquire_timeout(acquire_timeout) + .idle_timeout(idle_timeout) + .max_lifetime(max_lifetime) .connect(&url) .await .map_err(|e| { diff --git a/tests/test_database_pool.py b/tests/test_database_pool.py index 5bef305..5b0af73 100644 --- a/tests/test_database_pool.py +++ b/tests/test_database_pool.py @@ -8,7 +8,22 @@ async def test_database_pool_failure(): # Attempting to connect to a non-existent database should fail fast with pytest.raises(RuntimeError, match="DB connect error:"): - await app.setup_database("postgresql://foo:bar@127.0.0.1:12345/baz") + await app.setup_database( + "postgresql://foo:bar@127.0.0.1:12345/baz", acquire_timeout_secs=0.5 + ) + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "option", ["acquire_timeout_secs", "idle_timeout_secs", "max_lifetime_secs"] +) +@pytest.mark.parametrize("bad", [-1.0, float("nan"), float("inf")]) +async def test_database_pool_rejects_bad_durations(option, bad): + app = App() + + # Negative or non-finite durations must raise a ValueError, not panic in Rust + with pytest.raises(ValueError, match=option): + await app.setup_database("postgresql://foo:bar@127.0.0.1:12345/baz", **{option: bad}) @pytest.mark.anyio @@ -20,3 +35,17 @@ async def test_database_pool_teardown_no_op(): # __rsgi_del__ should also gracefully do nothing if no db was set up await app.__rsgi_del__() + + +@pytest.mark.anyio +async def test_database_pool_acquire_timeout_is_applied(): + import time + + app = App() + start = time.monotonic() + with pytest.raises(RuntimeError, match="DB connect error:"): + await app.setup_database( + "postgresql://foo:bar@127.0.0.1:12345/baz", acquire_timeout_secs=0.2 + ) + # The default is 3.0s, so finishing well under that shows the option applied. + assert time.monotonic() - start < 2.0