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
4 changes: 4 additions & 0 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions oxyroute/_oxyroute.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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]: ...
Expand Down
28 changes: 25 additions & 3 deletions oxyroute/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down
36 changes: 35 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use parking_lot::RwLock;

Expand All @@ -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<Duration> {
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 {
Expand Down Expand Up @@ -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<Bound<'py, PyAny>> {
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| {
Expand Down
31 changes: 30 additions & 1 deletion tests/test_database_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Loading