minato_pool (minato v1.2.0)
View SourceA pool of connections, handed out one caller at a time.
The pool holds connections and lends them; it does not run queries. That follows
from the caller owning the socket: a pool that ran the query would be back to
one process serialising every caller, which is the arrangement the whole client
is written to avoid. checkout/2 hands over the socket as well as the
connection term, checkin/2 hands it back, and minato wraps both so that
the ordinary case is one call.
Waiting
A checkout with no connection free waits in a FIFO queue until one is checked in or the timeout runs out. First in, first served, and a caller that gives up is taken out of the queue rather than handed a connection nobody is waiting for.
The queue is deliberately plain. A CoDel queue, which drops from the head when the minimum delay over a window stays above target, is the thing to build here when there is a load to measure it against; a bounded FIFO with a timeout is what that will replace, and it is honest in the meantime.
Connections come and go
Connecting happens in the background and is retried with exponential backoff, so
a pool started before its database is a pool that fills up when the database
arrives rather than a supervisor that gives up. Each wait is a random time in
the upper half of what the backoff allows, so the pools of many nodes do not
return to a restarted database at the same instant. checkout/2 waits for that
exactly as it waits for a busy connection.
Nothing is opened during a wait, whoever asks: a caller that arrives then is queued and served by the connect the wait ends in. While connects are failing there is one in flight at a time, so a database that is down, or coming back, is asked as often as the backoff says and not as often as callers arrive.
A borrower that dies takes the socket with it, because the socket belongs to the process that holds it: the pool notices through its monitor and starts a replacement.
What a connection is like when it comes back
Checked in with a transaction open, it is rolled back before it is lent again.
A caller that returns a connection mid-transaction has already made a mistake,
and the alternative is the next borrower silently joining a transaction it did
not open. The pool sends ROLLBACK ahead of the reset below rather than waiting
on it, and a connection it does not succeed on is closed and replaced by the
borrower that reads the answer.
The rest of the session is reset as well: settings made with SET or
set_config/3, the session user and role, advisory locks, LISTENs, temporary
tables, cursors opened WITH HOLD and sequence state. Each of those outlives a
transaction, and a borrower would otherwise run with a role, a search_path, a
lock or a tenant setting left behind by somebody else. Statements minato has
prepared are kept, since they are the connection's own cache. A connection with
a statement prepared with SQL PREPARE is closed instead, because such a
statement can take the name of one minato has cached and run in its place for
every later borrower.
Some session state is not reset: the seed set with setseed/1, and whatever an
extension keeps per session, such as dblink connections, the postgres_fdw
connection cache and libraries loaded with LOAD. RESET ALL returns each
setting to its value when the connection opened, which includes defaults set on
the role or database with ALTER ROLE ... SET. A setting the application relies
on for security, such as search_path, therefore belongs in the connection's
parameters, where a role able to alter itself cannot change it.
The reset is sent when the connection comes back and its answer is read by the
next borrower, as the first thing checkout/2 does. The pool therefore never
waits on a socket for it, and a connection that sat idle for longer than a round
trip costs the borrower nothing extra. Only the reset's own answer is accepted:
its command tags in order, ending with a value chosen afresh each time the
connection comes back, then an idle ReadyForQuery. A connection on which
something else answers first, because the last borrower gave it back with
answers it never read, is closed, and so is one the server refuses the reset on
and one whose answer does not come back because the server ended it while it
sat in the pool. The checkout then tries the next connection, up to the pool's
size and once more, before it returns {error, {session_reset, Why}}. A server
error in Why carries only its SQLSTATE code, since the rest of it may quote
what the last borrower ran.
A connection driven with minato_conn:send/2 and minato_conn:next/2 therefore
costs a reconnect if it is checked in with answers unread. Discard it instead.
The reset is a defence against SQL a borrower ran, not against Erlang code that
holds the connection. Such code can, for one, parse a statement with
minato_query:prepare/3 under the name of one minato cached after a SQL
DEALLOCATE, and the reset cannot tell that statement from minato's own.
Extended-protocol messages written with minato_conn:send/2 and not yet
followed by Sync are sent ahead of the reset, so the reset's own Sync can
commit them. Discard a connection given back like that.
The pool writes the reset itself, and minato_conn:close/1 writes Terminate.
Both wait as long as the connection's send_timeout allows, which is the
connection's timeout unless socket_options says otherwise.
Summary
Types
How the pool is registered and asked for.
What to open, and how many.
What the pool has been doing since it started.
Functions
Give a connection back.
checkout/2 with the default timeout of five seconds.
Borrow a connection, waiting for one if they are all out.
Give a connection back to be closed rather than lent again.
Hand a borrowed connection to another process, which then owes it back.
Start a pool under a supervisor.
What the pool holds and what it has done.
Stop the pool and close every connection it holds.
Types
-type cast() :: {checkin, pid(), minato_conn:conn()} | {unlent, pid(), minato_conn:conn(), [expected()]} | {discard, pid(), minato_conn:conn()} | {gave_up, pid()} | timed_out.
-type expected() :: minato_protocol:tag() | {row, binary()}.
-type idle() :: {minato_conn:conn(), Since :: integer(), [expected()]}.
-type info() :: {connected, minato_conn:conn()} | {server_limit, non_neg_integer() | unknown} | {connect_failed, term()} | retry | sweep | {'DOWN', reference(), process, pid(), term()}.
-type name() :: atom().
How the pool is registered and asked for.
-type opts() :: #{size => pos_integer(), min_size => non_neg_integer(), max_age => timeout(), max_idle => timeout(), disconnected => fail | wait, connection := minato_conn:opts()}.
What to open, and how many.
#{size => pos_integer(),
connection => minato_conn:opts()}connection is passed to minato_conn:connect/1 unchanged. size is how many
connections the pool keeps. How long to wait for a free one is the caller's to
say, in checkout/2.
min_size is how many connections the pool opens before anybody asks, and it
defaults to one. The rest are opened when a caller finds none free, so a node
with twenty pools does not want a hundred connections the moment it boots, while
a pool that cannot connect at all still says so at start up rather than at the
first query. 0 opens nothing until asked.
Every caller waiting has a connection on its way while the pool is below
size: one is opened for each, side by side, and never more than size allows.
While the last attempt to connect failed there is one attempt at a time however
many are waiting, so a server that is down is not asked size times over.
A size that is not a positive integer, or a min_size that is not a
non-negative integer, stops the pool before it connects, and start_link/2
returns {error, {invalid_size, Size}} or {error, {invalid_min_size, MinSize}}.
A min_size above size is lowered to size. max_idle and max_age must be
infinity or a non-negative integer, and disconnected fail or wait, or the
pool stops the same way with {invalid_max_idle, _}, {invalid_max_age, _} or
{invalid_disconnected, _}. A connection that is missing, not a map, or has no
user stops it with invalid_connection, and options that are not a map with
invalid_opts. A connection whose channel_binding, ssl, auth,
ssl_options or password is not something minato knows, or whose
connect_timeout, timeout or cancel_timeout is not a time, stops it with
{invalid_option, Key}, as minato_conn:validate/1 answers, so a pool that
could not be secured as asked does not start and retry. So does a key that is
not an option at all, here or in connection. None of these reasons carries
the options, and a key that is not an atom is not named in one:
{invalid_option, not_an_atom}.
The options are also the pool's child spec under minato_sup, and a supervisor
prints its child specs: in its progress report when the pool starts, when a
pool declared in the application environment fails to start at boot, each time
a running pool exits abnormally and is restarted, and in
sys:get_status(minato_sup). The password, when given as a binary or a
string, and ssl_options, which can hold a private key, are therefore put in the
child spec as funs that return them, which print as #Fun<...>. The pool keeps
them the same way, so sys:get_status/1, a crash report and the processes that
open connections do not show them either. This keeps them out of logs and
reports; it is not protection from code running on the node, which can read
them. A pool started with start_link/2 under a supervisor of your own has that
supervisor's child spec, which holds the options exactly as given.
disconnected decides what a checkout gets when the pool holds no connections
and the last attempt to open one failed. fail is the default and answers
{error, disconnected} at once, because a caller that cannot be served should
find out in microseconds rather than after the whole checkout timeout - during
an outage the alternative is every caller in the system holding a process for
five seconds to learn the same thing. wait queues anyway, for work that would
rather be slow than fail.
max_idle closes a connection that has sat unused for that many milliseconds,
down to min_size. A pool that grew to meet a busy hour otherwise holds that
hour's connections until the process dies, which is a cost the server pays and
nobody sees. It is one minute by default, and infinity keeps whatever the pool
has grown to.
max_age retires a connection when it is checked in older than that many
milliseconds, and opens a replacement. It is infinity by default, because a
connection to PostgreSQL itself is good indefinitely and churning them would be
work nobody asked for. Set it when something sits in the middle - a proxy, a
load balancer, a NAT - since those have idle and lifetime limits of their own,
and a connection cut by one of them is discovered by a query failing.
-type stats() :: #{size := non_neg_integer(), idle := non_neg_integer(), borrowed := non_neg_integer(), waiting := non_neg_integer(), checkouts := non_neg_integer(), waits := non_neg_integer(), timeouts := non_neg_integer(), disconnects := non_neg_integer(), retired := non_neg_integer()}.
What the pool has been doing since it started.
disconnects is connections lost: a connect that failed, a borrower that died,
a connection given back in a state it could not be reset from. retired is
connections closed on purpose because they reached max_age. The two are
separate because one of them is a problem and the other is the pool working.
-type waiter() :: {gen_server:from(), pid(), reference(), integer() | infinity}.
Functions
-spec checkin(name(), minato_conn:conn()) -> ok.
Give a connection back.
The socket goes back to the pool first, because the pool cannot read a socket it does not own. A connection with a transaction open is rolled back before it is lent again, and one that cannot be is closed and replaced. The rest of the session is reset as the module documentation describes.
-spec checkout(name()) -> {ok, minato_conn:conn()} | {error, term()}.
checkout/2 with the default timeout of five seconds.
-spec checkout(name(), timeout()) -> {ok, minato_conn:conn()} | {error, term()}.
Borrow a connection, waiting for one if they are all out.
The socket is handed over with it, so the calling process can read and write it.
Give it back with checkin/2; a caller that dies instead is noticed, and the
connection is replaced rather than leaked.
The timeout covers reading the answer to the connection's reset as well as
waiting for one. A checkout that runs out of time while the pool has not yet
answered waits up to a further 100 milliseconds for that answer, so that a
connection lent at the last moment goes back to the pool. One that finds every
connection it tries left unusable, the pool's size and one more, returns
{error, {session_reset, Why}}.
-spec discard(name(), minato_conn:conn()) -> ok.
Give a connection back to be closed rather than lent again.
For a borrower that knows the connection is no longer trustworthy: a read that timed out, an exception part way through a result set, anything that leaves the stream at an offset nobody knows. The pool closes it and opens another.
-spec give_away(name(), minato_conn:conn(), pid()) -> ok | {error, term()}.
Hand a borrowed connection to another process, which then owes it back.
Two things move and both have to: the socket, which belongs to whoever holds it, and the pool's idea of who to watch. The pool stops watching the caller and starts watching the new owner, so the connection is replaced if that process dies rather than the one that borrowed it.
The connection term itself is the caller's to send on. Sending it without calling this leaves the receiver holding a term whose socket belongs to somebody else, and the pool waiting on a process that has moved on.
For a worker that borrows a connection and hands it to the process that will use
it, and for LISTEN on a connection taken out of the pool.
-spec handle_call(request(), gen_server:from(), #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}) -> {reply, term(), #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}} | {noreply, #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}}.
-spec handle_cast(cast(), #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}) -> {noreply, #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}}.
-spec handle_info(info(), #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}) -> {noreply, #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}}.
-spec init({name(), dynamic()}) -> {ok, #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}} | {stop, refused()}.
-spec start_link(name(), opts()) -> gen_server:start_ret().
Start a pool under a supervisor.
What the pool holds and what it has done.
-spec stop(name()) -> ok.
Stop the pool and close every connection it holds.
-spec terminate(term(), #state{name :: name(), opts :: minato_conn:opts(), size :: pos_integer(), min_size :: non_neg_integer(), max_age :: timeout(), disconnected :: fail | wait, max_idle :: timeout(), failures :: non_neg_integer(), measured :: boolean(), idle :: [idle()], borrowed :: #{pid() => #borrowed{monitor :: reference(), count :: pos_integer(), last :: {minato_conn:conn(), [expected()]} | undefined}}, waiting :: queue:queue(waiter()), connecting :: non_neg_integer(), connectors :: #{reference() => pid()}, backoff :: pos_integer(), retry :: reference() | undefined, counters :: counters:counters_ref()}) -> ok.