Skip to main content

Pool

Struct Pool 

Source
pub struct Pool { /* private fields */ }
Expand description

Connections to one server, for the tasks of one worker thread.

Make one pool per worker, inside giong::Runtime::run: nothing is shared between threads, so nothing is locked.

use giong_postgres::{Config, Pool};

fn main() -> std::io::Result<()> {
    let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
    giong::Builder::new().build()?.run(move |_worker| {
        let pool = Pool::new(config.clone(), 4);
        async move {
            let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
            let n: i64 = row.get(0).unwrap();
            println!("{n} orders");
        }
    })
}

query and the other statement methods do not take a connection for themselves: they run on the least busy connection, beside statements from other tasks (pipelining), and the pool opens another connection, up to its maximum, when every open one is busy. That is the fast path for statements that stand alone. On one connection the server answers in order, so a statement waits for those sent before it; the pool steers new statements away from a connection whose oldest statement has been running for more than 5 ms. Run statements known to be slow (reports, migrations) on a connection of their own, from get. At most 1024 statements run on one connection at a time; past that, statements use another connection or wait for room.

How many connections. Because statements pipeline, a few connections keep the server busy: start with the server’s cores, shared among the workers’ pools. More than that adds no throughput and raises tail latency, since a backend waiting for a core holds up every statement queued on its connection. Statements that wait on disk or on locks need more.

get takes a connection for one task alone: for a transaction, for session settings (SET, SET ROLE, temporary tables, advisory locks, LISTEN), or for a slow statement. While it is out, no shared statement runs on it. Tasks waiting in get are served in the order they came, and shared statements stop using a connection while a get waits for it, so get is served even when shared statements keep every connection busy; shared statements always keep at least one connection when the pool has room for two. The connection comes back when the PooledClient is dropped, and its session is reset before anything else runs on it: a transaction left open is rolled back, and if anything was sent on it, SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES follows (plus DEALLOCATE ALL after an SQL-level PREPARE). Settings given to Config survive the reset; settings made with SET do not. These requests are pipelined in front of the next statement, so nobody waits a round trip for them; if they fail, the connection is closed instead of reused.

Transactions and session changes never run on the shared connections, since the statements of other tasks would run inside them or under them. query, query_one, query_opt and execute refuse BEGIN, COMMIT, ROLLBACK and the other transaction statements, and all the statement methods refuse statements that change the session (SET without LOCAL, RESET, DISCARD, LISTEN, UNLISTEN, PREPARE, DEALLOCATE, DECLARE, LOAD, CREATE TEMP ...) and COPY ... FROM STDIN, before sending anything (ErrorKind::Statement). Functions that change the session (set_config(.., false), pg_advisory_lock) cannot be recognised this way: call them on a connection from get. batch_execute may carry a whole transaction (BEGIN; ...; COMMIT); if a batch leaves one open, its connection is closed, which rolls it back, and the batch and every statement sent on that connection after it fail with ErrorKind::Closed.

Connections the server closed, or that broke, are left behind as soon as that is noticed, which is when it happens: each connection is read continuously. A connection unused for the idle timeout is closed, and so is one older than the maximum lifetime or whose server refused a write because it is a standby (after a failover), once no statement uses it.

Implementations§

Source§

impl Pool

Source

pub fn new(config: Config, max_size: usize) -> Self

A pool of at most max_size connections to the server in config. Connections are opened when needed, not here.

When opening one fails, the pool opens one at a time until one succeeds, and tasks that waited through a failed attempt, with no connection open to wait for, get its error at once: while the server is down, a burst of calls makes one attempt, not one each. With no connection open, calls after a failed attempt also get its error at once for a pause that starts at 10 ms and doubles with each failure in a row up to 1 s (less a random part of up to half, so that many pools do not try together); the first call after the pause tries again, and the first success ends it.

Size it from the server’s max_connections: the pools of all workers of all processes together must stay below it.

§Panics

Panics if max_size is 0.

Source

pub fn wait_timeout(self, timeout: Duration) -> Self

The longest a task waits for a connection when all max_size are taken or busy: 5 seconds by default. A longer wait fails with ErrorKind::PoolTimeout. A task that opens a new connection waits for it up to Config::connect_timeout instead.

A wait longer than a century (Duration::MAX) counts as a century: no limit.

§Panics

Panics if other clones of this pool exist; set it right after new.

Source

pub fn idle_timeout(self, timeout: Duration) -> Self

How long a connection may sit unused before the pool closes it: 10 minutes by default. The pool opens connections again when it needs them, so a burst does not hold the server’s connections forever.

§Panics

Panics if other clones of this pool exist; set it right after new.

Source

pub fn max_lifetime(self, lifetime: Duration) -> Self

How long a connection may live: 30 minutes by default, less up to a tenth at random so that the connections of a pool do not all close at once. An older connection is closed as soon as no statement uses it, and replaced when needed, so that connections follow DNS changes and failovers, and the server’s per-connection memory is given back.

§Panics

Panics if other clones of this pool exist; set it right after new.

Source

pub async fn query( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Vec<Row>, Error>

Runs a statement on a shared connection and returns its rows; see Client::query. Statements that control a transaction or change the session are refused (ErrorKind::Statement): run them on a connection from get.

Not cancel safe: if the future is dropped, the statement may still run on the server, and what it changes stays; the pool and its connections stay usable.

Source

pub async fn query_one( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Row, Error>

Runs a statement that returns exactly one row; see Client::query_one. Refuses the statements query refuses.

Not cancel safe, like query.

Source

pub async fn query_opt( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Option<Row>, Error>

Runs a statement that returns at most one row; see Client::query_opt. Refuses the statements query refuses.

Not cancel safe, like query.

Source

pub async fn execute( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<u64, Error>

Runs a statement and returns the number of rows it changed; see Client::execute. Refuses the statements query refuses.

Not cancel safe, like query.

Source

pub async fn batch_execute(&self, sql: &str) -> Result<(), Error>

Runs several statements without parameters; see Client::batch_execute.

The batch may hold a whole transaction, BEGIN; ...; COMMIT. If it leaves one open, the connection is closed, which rolls the transaction back, and the batch fails with ErrorKind::Closed, as do the statements other tasks sent on that connection after it: they would otherwise have run inside the transaction. Statements that change the session (SET without LOCAL, LISTEN, COPY ... FROM STDIN and the others listed on Pool) are refused before anything is sent (ErrorKind::Statement).

Not cancel safe, like query.

Source

pub async fn get(&self) -> Result<PooledClient, Error>

Takes a connection for this task alone, for a transaction, session settings or a slow statement:

let mut conn = pool.get().await?;
let tx = conn.transaction().await?;
tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
tx.commit().await?;

Waits up to the wait timeout when every connection is taken or busy and the pool is full. Tasks waiting here are served in the order they came. The session is reset when the connection comes back (see Pool).

Cancel safe: if the future is dropped, no connection is taken, and the place in line goes to the next task.

Source

pub fn stats(&self) -> PoolStats

The pool’s current state and counters.

Trait Implementations§

Source§

impl Clone for Pool

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Pool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Pool

§

impl !Send for Pool

§

impl !Sync for Pool

§

impl !UnwindSafe for Pool

§

impl Forget for Pool

§

impl Freeze for Pool

§

impl Move for Pool

§

impl Unpin for Pool

§

impl UnsafeUnpin for Pool

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.