minato_conn (minato v1.2.0)

View Source

One connection to a PostgreSQL server, owned by the process that opened it.

connect/1 performs the whole opening exchange - TCP, optionally TLS, the StartupMessage, authentication through minato_auth, and then the parameters and the BackendKeyData the server volunteers - and hands back a connection the calling process owns outright.

There is no connection process. The socket is {active, false} and belongs to the caller, so a query is a send and a read on the caller's own scheduler slot rather than a message to a gen_server that puts every caller behind the slowest one. The PostgreSQL protocol is FIFO per connection, so a single owning process is an unpreemptable queue: one slow query stalls every other caller of that process, and no timeout on the caller's side can take the connection back. Caller ownership also gives session pinning, which transactions, advisory locks, SET ROLE and LISTEN all need to be correct rather than merely fast.

That is why conn/0 is threaded through next/1 rather than being a handle with hidden state: bytes that have arrived but have not been read yet live in the connection, so a caller that drops the returned connection drops the buffer with it.

Reading

next/1 answers with the next message, reading from the socket only when nothing already decoded is waiting. A read frames everything that arrived, so one recv yields as many messages as the server sent - which is the whole point of minato_protocol:frame/1 - without the caller ever seeing the buffer.

Every read passes an explicit timeout. A read that times out leaves the connection with an unknown number of bytes still to come, so the connection is no longer usable and next/1 says so with {error, {socket, timeout}}; the owner closes it. Recovering the stream would mean knowing how far through a message the far end was, which is exactly what a timeout means we do not know.

TLS

ssl => true upgrades the socket before the startup message, and refuses to continue when the server answers that it will not do TLS. There is no prefer mode. A mode that continues in the clear when the server declines is a mode the man in the middle chooses, because declining is the one message an attacker sitting on the connection can always produce.

Verification is on by default: verify_peer against the OS trust store, with the hostname checked and server_name_indication set, which OTP needs to be told explicitly on a socket upgrade. Anything passed in ssl_options replaces the default for that option and nothing else, so turning verification off is possible and has to be written down.

{server_name_indication, disable} is not a way to write it down. It keeps the name out of the handshake, and the certificate is still checked for host, which ssl alone would stop doing. The check is made when the handshake is over and before anything is sent in the session, and one that fails is {error, {tls, {bad_cert, hostname_check_failed}}}. {verify, verify_none}, a verify_fun or a customize_hostname_check is what changes the check.

Every handshake is a full one. ssl keeps the TLS 1.2 sessions of all the clients on a node in one place and resumes one for a later connection to the same address without the server presenting a certificate again, so what a resumed connection trusts is whatever the connection that opened the session was willing to accept. minato neither leaves a session there nor takes one from there: {reuse_sessions, false} and {session_tickets, disabled} are defaults, and ssl_options that ask for anything else are refused as {invalid_option, ssl_options}. A connection is opened once and kept, so there is nothing a resumed handshake would have saved.

Under TLS the SCRAM exchange is bound to the session by default: SCRAM-SHA-256-PLUS with tls-server-end-point, which puts the hash of the server's certificate inside the material the client proof covers. A man in the middle holding a certificate the client accepts can otherwise relay the whole exchange and keep the session; with binding, the hash it bound to is not the one the real server sees, and the proof is refused. channel_binding => require refuses to connect without it, whatever the server asks for instead.

A refusal that arrives as a closed socket

A server that refuses the startup exchange writes why and then the backend exits. On Windows a socket closed with anything still unread is reset rather than shut down, and a reset discards what the far end had already received, so the reason can be gone before it can be read: connect/1 answers {error, {socket, closed}} or {error, {socket, econnreset}} where the same call on Linux answers {error, {pgsql_error, #{code := <<"3D000">>}}}. The connection is refused either way, and the server's log has the reason. Nothing on this side can recover a message the kernel threw away.

Cleartext passwords

A server may ask for the password in the clear. minato answers only when the transport is TLS, and refuses otherwise with {error, cleartext_password_refused}. The password is the credential for every future connection too, so handing it to whoever is on the wire is worse than failing to connect. auth => [Method] narrows what is acceptable further, down to SCRAM alone.

Cancelling

cancel/1 opens a second connection and sends CancelRequest with the BackendKeyData from this one, because that is the only way the protocol offers to interrupt a running query: the connection running it is busy. Cancellation is a request. The server may finish first, and a caller still has to read whatever the query produced.

The password is not kept after the exchange that used it, so cancel/1 works without one, which is what CancelRequest documents: possession of the secret the server issued is the whole of the authorisation.

Summary

Types

An open connection. Owned by the process that called connect/1.

What went wrong. pgsql_error is the server refusing, everything else is local.

What CancelRequest needs: the process id and secret the server issued.

An authentication method the server may ask for.

How to reach a server and who to be.

Where a connection goes: what it was asked to reach, and the pool holding it.

The map carried by an error({minato_conn, Report}) exception.

Functions

Ask for the next bytes to arrive as a message instead of a read.

How long this connection has been open, in milliseconds.

The key cancel/1 needs, for a caller that wants to cancel from elsewhere.

Ask the server to cancel whatever this connection is running.

The tls-server-end-point binding data for this connection, or undefined.

Take the next statement name this connection has room for, or undefined.

Close a connection.

Open a connection and complete the opening exchange.

Go back to reading, after activate/1.

Give the statement that runs next this long, then cancel it.

Decode data rows as they are framed, with Decoder, or stop doing so.

Build a decoder from each RowDescription that arrives, with Opts, or stop.

Drop what was kept under this SQL.

Hand the socket to another process.

Turn a socket message into the protocol messages it carried.

next/2 with the connection's own timeout.

Read the next message the server sent.

Where a connection goes, for the metadata of an event: host, port and database as they were asked for, and pool when a pool holds it.

One reported parameter, or undefined.

Every parameter the server has reported, by name.

What this connection has parsed on the server under this SQL, or undefined.

Keep a parsed statement under its SQL, if there is room.

Write one frontend message, or a list of them in order.

How many statements this connection is keeping, and how many it may keep.

The per read timeout this connection was opened with.

What the server last said about the transaction on this connection.

Whether this connection is still worth handing to a caller.

Whether every option is one minato has, and those that decide how a connection is secured say something it knows.

The same connection with a different read timeout.

Types

conn()

-opaque conn()

An open connection. Owned by the process that called connect/1.

error()

-type error() ::
          {pgsql_error, minato_protocol:fields()} |
          {socket, term()} |
          {tls, term()} |
          tls_refused | cleartext_password_refused |
          {auth_method_refused, method()} |
          {channel_binding_required, method()}.

What went wrong. pgsql_error is the server refusing, everything else is local.

key()

-type key() :: {Pid :: integer(), Secret :: integer()}.

What CancelRequest needs: the process id and secret the server issued.

method()

-type method() :: scram_sha_256 | md5 | cleartext | none.

An authentication method the server may ask for.

none is a server that asks for nothing, which is trust in pg_hba.conf.

opts()

-type opts() ::
          #{host => inet:socket_address() | inet:hostname(),
            port => inet:port_number(),
            user := binary(),
            password => binary() | string() | fun(() -> binary() | string()),
            database => binary(),
            parameters => #{binary() => binary()},
            ssl => boolean(),
            ssl_options => [ssl:tls_client_option()],
            channel_binding => minato_auth:channel_binding(),
            auth => [method()],
            connect_timeout => timeout(),
            timeout => timeout(),
            socket_options => [gen_tcp:connect_option()],
            transport => inet | socket,
            prepared_statements => non_neg_integer(),
            cancel_timeout => timeout(),
            frame_opts => minato_protocol:frame_opts()}.

How to reach a server and who to be.

#{host => inet:socket_address() | inet:hostname(),
  port => inet:port_number(),
  user := binary(),
  password => binary() | string() | fun(() -> binary() | string()),
  database => binary(),
  parameters => #{binary() => binary()},
  ssl => boolean(),
  ssl_options => [ssl:tls_client_option()],
  channel_binding => minato_auth:channel_binding(),
  auth => [method()],
  connect_timeout => timeout(),
  timeout => timeout(),
  socket_options => [gen_tcp:connect_option()],
  transport => inet | socket,
  prepared_statements => non_neg_integer(),
  cancel_timeout => timeout(),
  frame_opts => minato_protocol:frame_opts()}

user is the only one that has to be given. database defaults to user, as PostgreSQL itself does.

password may be a fun, which is called once per connection attempt and never stored. That is what a rotating credential needs: a password read at start up and held in a pool's configuration for a month is a password that expires while the pool holds it. Prefer a named function, fun my_app:db_password/0, to a closure: it prints as its name, and it survives a reload of the module that made it, where a closure from a module reloaded twice raises badfun. A password given as a string, or returned as one by the fun, is converted to a binary, and one that is not valid text raises {minato_conn, #{reason := not_text}} without the password.

user, database and everything in parameters go into the StartupMessage as null terminated strings, so none of them may hold a null byte: connect/1 raises {minato_conn, #{reason := null_byte_in_parameter}} naming the parameter before it opens a socket.

parameters are added to the StartupMessage and are how application_name gets set. Two are sent unless they are given here: client_encoding is UTF8, because the codecs decode text as UTF-8 and a server sending LATIN1 would put mojibake in a binary rather than raise; and DateStyle is ISO, MDY, because the text format for dates and timestamps is only unambiguous under ISO. Neither affects the binary format.

channel_binding decides whether SCRAM is tied to the TLS session. It defaults to prefer under ssl => true and disable without it, since there is nothing to bind to on a plain socket. require connects through SCRAM-SHA-256-PLUS or not at all: a server that asks for a cleartext or MD5 password, or for nothing, or that offers SCRAM without -PLUS, is refused with {error, {channel_binding_required, Method}} before anything is answered, and so is any server on a connection without TLS, where there is nothing to bind to. Those are the semantics of channel_binding=require in libpq.

auth is the list of methods the server may ask for, and it defaults to all four. It is what require_auth is in libpq, with scram_sha_256 for scram-sha-256, md5 for md5, cleartext for password and none for none. A method outside the list is refused with {error, {auth_method_refused, Method}} before it is answered, so auth => [scram_sha_256] is a connection that never sends a password or an MD5 digest of one, and never accepts a server that asks for nothing.

transport is socket, which is minato_socket over the socket NIFs, or inet, the driver every BEAM program uses. socket is the default: it does everything the driver does on every machine minato runs on, costs about a quarter less per query and about half less per pooled one, and holds more throughput at the same CPU once a pool is deep enough for per-operation cost to show. inet is there for a machine or a workload that disagrees. See minato_socket.

prepared_statements is how many statements this connection will keep parsed on the server for minato_query:cached/4. It defaults to 64, and 0 turns caching off. See minato_query for what fills it.

timeout is the per read timeout and applies for the life of the connection. It is also how long the opening exchange may take as a whole, from the startup message to ReadyForQuery, so that a server answering each read in time but never finishing is given up on: {error, {socket, timeout}}. connect_timeout covers the TCP connect, the answer to the TLS request and the TLS handshake together, not each of them. Either can be infinity.

A write is bounded too. Unless socket_options says otherwise, send_timeout is timeout and send_timeout_close is true, so a server that stops reading costs one timeout and the connection, where it used to hold the caller for as long as it liked. The bound is on a whole write, not on each part of it, so a value of hundreds of megabytes over a slow link wants {send_timeout, _} set to what that takes, or to infinity. A TLS session on the socket transport is written by ssl, which takes no deadline of its own; there the socket under the session is shut down when the time runs out, by minato_overdue, whether or not the minato application is running, and the connection is closed whatever send_timeout_close says, since a session cut off in the middle of a record cannot be written to again. Windows does not end a write ssl has started when the socket under it is shut down, so a TLS write on the socket transport has no bound there, and a close/1 behind one waits with it; with transport => inet both have the driver's.

The server's ParameterStatus messages are kept for parameters/1, up to 64 of them and 4096 bytes each; one beyond that is not kept. cancel_timeout is how long a cancelled statement is given to come back before the connection is given up on; see deadline/2. On Windows it also bounds how long closing a TLS connection waits for the server to close first, to at most a second; see close/1.

origin()

-type origin() ::
          #{host := inet:socket_address() | inet:hostname(),
            port := inet:port_number(),
            database := binary(),
            pool => atom()}.

Where a connection goes: what it was asked to reach, and the pool holding it.

report()

-type report() :: #{message := term(), reason := term(), data := term()}.

The map carried by an error({minato_conn, Report}) exception.

Functions

activate/1

-spec activate(conn()) -> {ok, conn()} | {error, error()}.

Ask for the next bytes to arrive as a message instead of a read.

Exactly one message arrives and the owner asks again. That is the arrangement a process which has to wait for the server without a query outstanding needs - LISTEN is the only one there is - because next/1 blocks, and a process blocked in a read answers nothing else.

{active, once} on the driver transport; on the socket transport a read that either hands back what is already here, in which case the message is sent from here, or registers this process for one select. Either way it is one message to whoever called, which is why the connection comes back: what it is waiting for is part of it.

The connection is unusable for next/1 until the messages stop coming, and the two must not be mixed on one connection.

age/1

-spec age(conn()) -> non_neg_integer().

How long this connection has been open, in milliseconds.

For a pool deciding whether to keep lending it. A connection to PostgreSQL itself can live for months; one that goes through a proxy, a load balancer or a NAT is on a clock somebody else set, and finding out where that clock ran out by having a query fail is the expensive way.

backend_key/1

-spec backend_key(conn()) -> key() | undefined.

The key cancel/1 needs, for a caller that wants to cancel from elsewhere.

cancel(Conn)

-spec cancel(conn()) -> ok | {error, error()}.

Ask the server to cancel whatever this connection is running.

Opens a second connection to the same server, sends CancelRequest and closes it. No answer is defined by the protocol: the server either cancels the query or does not, and this connection finds out by reading what its query returned.

channel_binding/1

-spec channel_binding(conn()) -> binary() | undefined.

The tls-server-end-point binding data for this connection, or undefined.

The hash of the server's certificate, taken with the hash the certificate was signed with, which is what RFC 5929 defines and what PostgreSQL computes on its side. SHA-1 and MD5 signatures are hashed with SHA-256 instead, because the binding must not be weaker than the mechanism it is bound to.

There is nothing to bind to on a plain socket, so it is undefined there.

claim/1

-spec claim(conn()) -> {binary() | undefined, conn()}.

Take the next statement name this connection has room for, or undefined.

Room is counted in statements kept, so a name whose statement was never kept, because the server refused to parse it, or is kept no longer, after forget/2, takes none. A connection that has renewed or dropped statements any number of times still keeps as many as prepared_statements allows.

Names never repeat, even after forget/2, because the statement a forgotten name refers to may still be parsed on the server, and parsing a second one under the same name is an error rather than a replacement.

The name carries a random per-connection prefix, so it is unique to this connection rather than to a position in a sequence. A bare counter is only unique within one connection, which is enough exactly as long as one connection means one backend - and behind a transaction pooler it does not. PgBouncer and friends multiplex many connections onto few backends, so two connections both counting from zero hand the same backend minato_30 twice and the second one is refused with 42P05, prepared statement already exists.

That failure is vicious in the field: which query dies depends on which server connection the pooler handed out, so it looks random, it moves between deployments sharing a pooler, and it clears and returns on its own. It cost a real production investigation (Taure/minato#40, widgrensit/asobi#419). Eight random bytes make it impossible instead of unlikely - a counter that only has to be unique per connection stays a counter, and the prefix does the rest.

close(Conn)

-spec close(conn()) -> ok.

Close a connection.

Terminate is sent first so the server tears the backend down rather than discovering a closed socket, and a failure to send it is not reported: the socket is being closed either way. The send waits no longer than send_timeout and never more than a second, whatever send_timeout is, so a server that has stopped reading does not hold a close up. A close answers ok and does not raise, whatever state the socket or the TLS session is in.

With transport => inet the bound on a write is the driver's, and a driver still holding bytes the server has not taken is not written to at all: the socket is closed and what it held is dropped. A TLS session on that transport then says its own goodbye through ssl, which gives up on a server that is not reading after its own timeouts, about ten seconds.

On Windows a TLS session waits for the server's own close before it is closed, for no longer than cancel_timeout and never more than a second. ssl keeps a read outstanding on a socket from socket, and there a socket:close/1 that races the server's close against that read can wait forever for the read to be given back, which leaves the caller of ssl:close/1 waiting with it (#58). Once the server has closed, the read has finished and there is nothing left to race. A server busy with a statement reads Terminate only when the statement ends, so the second is what closing a busy TLS connection costs there. Everywhere else the session is closed at once.

connect/1

-spec connect(opts()) -> {ok, conn()} | {error, error()}.

Open a connection and complete the opening exchange.

Answers once the server has sent ReadyForQuery, so a connection that is returned is one that can be used, not merely one that is open.

Raises error({minato_auth, _}) for a server that asks for something it cannot be answered with, and error({minato_scram, _}) for a server that fails to prove itself. The socket is closed before either is re-raised.

{ok, Conn} = minato_conn:connect(#{user => ~"minato", password => ~"minato",
                                   database => ~"minato_test"}).

deactivate/1

-spec deactivate(conn()) -> {ok, conn()} | {error, error()}.

Go back to reading, after activate/1.

Whatever the socket already delivered to the mailbox is taken back into the buffer, because those bytes have left the socket and next/1 would otherwise wait for bytes it already has. A connection that has been switched back can be read with next/1 as usual.

Bytes that were waited for but never arrived are not lost on the socket transport: cancelling the wait drops the message, not the socket's own buffer, so the next next/1 reads them.

deadline/2

-spec deadline(conn(), timeout()) -> conn().

Give the statement that runs next this long, then cancel it.

A read timeout on its own can only end the wait, not the statement: the server carries on running the query, and the connection is left with an answer coming that nobody is reading, which makes it fit for closing and nothing else. A deadline sends CancelRequest when it expires and then goes on reading, so what arrives is the server's own 57014 and the ReadyForQuery after it. A cancelled statement therefore comes back as an ordinary failed statement with the connection still usable, which is the difference between a slow query costing one query and costing a connection.

The cancelled statement gets cancel_timeout to acknowledge it. A server that does not answer even that has stopped talking, and the connection really is finished: {error, {socket, timeout}}, with no connection handed back.

The deadline is looked at before every read, so it ends an answer that is still arriving as well as one that has stopped: rows a server sends without a pause are read until the deadline, then for cancel_timeout more, and no longer. That is a bound on how long a call reads and not on how much: what arrives in that time is held. With infinity for the deadline or for cancel_timeout there is no bound, and rows that keep arriving are read for as long as they come.

It lasts until it is cleared with infinity, which the query layer does before handing a connection back, so a deadline belongs to one call rather than to the connection. It covers everything that call does, including the Describe round trip a first-time statement needs, because a caller asking for 300 milliseconds means the answer, not one leg of it.

decoding/2

-spec decoding(conn(), minato_protocol:decoder() | undefined) -> conn().

Decode data rows as they are framed, with Decoder, or stop doing so.

A result set arrives as a run of DataRow messages, and framing them into a list only for the layer above to walk that list again costs an allocation and a traversal per row. With a decoder set, a contiguous run comes back as one {rows, Rows} message with the rows already decoded.

The decoder belongs to one statement's result, so it must be cleared before the connection is used for anything else. A decoder left behind would be applied to the next statement's rows, which is wrong data rather than an error.

decoding_opts/2

-spec decoding_opts(conn(), minato_protocol:opts() | undefined) -> conn().

Build a decoder from each RowDescription that arrives, with Opts, or stop.

decoding/2 is for a statement whose columns are known before its rows are read. A simple query is not that: it may carry several statements, each describing its own columns partway through the stream. Setting a decoder from the layer above cannot work there, because the rows of the next statement may already have been framed by the time that layer sees the description. Framing therefore rebuilds the decoder itself as it passes each one, and drops it at the CommandComplete that ends the statement.

forget/2

-spec forget(conn(), binary()) -> conn().

Drop what was kept under this SQL.

For a statement the server has stopped accepting, which is what a schema change under a cached plan looks like.

give_away/2

-spec give_away(conn(), pid()) -> ok | {error, error()}.

Hand the socket to another process.

The connection term is data and can be sent anywhere; the socket underneath it cannot. It belongs to one process, and a process that is handed a connection without being handed the socket gets {error, {socket, einval}} on its first read. A pool checking a connection out has to call this, and so does the borrower checking it back in.

handle_message/2

-spec handle_message(conn(), term()) ->
                        {messages, [minato_protocol:backend()], conn()} | {closed, term()} | ignore.

Turn a socket message into the protocol messages it carried.

For a connection under activate/1. Anything that is not this connection's socket answers ignore, so an owner with other messages of its own can pass everything through.

{closed, Reason} is the socket going away, and there is no connection in it: the socket is gone, and what is left of the buffer belongs to a message that will never finish arriving.

next/1

-spec next(conn()) -> {ok, minato_protocol:backend(), conn()} | {error, error()}.

next/2 with the connection's own timeout.

next/2

-spec next(conn(), timeout()) -> {ok, minato_protocol:backend(), conn()} | {error, error()}.

Read the next message the server sent.

Reads from the socket only when no already decoded message is waiting, so a result set of five thousand rows costs as many reads as the network chose to split it into rather than one per row.

ParameterStatus is not handled here even though the server may send it at any time. It is a message like any other and the layer above decides what to do with it, because a connection that quietly swallowed SET TIME ZONE taking effect would be hiding the one thing the message exists to announce.

A pooled connection read this way goes back with minato_pool:checkin/2 only once its last ReadyForQuery has been read, and is otherwise discarded with minato_pool:discard/2.

With a decoder set by decoding/2 or decoding_opts/2, a value that will not decode raises error({minato_codec, _}) from here. The rest of that statement's answer is read first, undecoded, up to its ReadyForQuery, so the connection the caller passed in is ready for the next statement when the raise arrives. One that could not be read that far is closed.

origin/1

-spec origin(conn()) -> origin().

Where a connection goes, for the metadata of an event: host, port and database as they were asked for, and pool when a pool holds it.

Built once when the connection opens, so a query event that carries it pays for one small map and not for reading the options again.

parameter/2

-spec parameter(conn(), binary()) -> binary() | undefined.

One reported parameter, or undefined.

server_version, client_encoding and integer_datetimes are always among them; which others a server volunteers is the server's choice.

parameters/1

-spec parameters(conn()) -> #{binary() => binary()}.

Every parameter the server has reported, by name.

recall/2

-spec recall(conn(), binary()) -> dynamic().

What this connection has parsed on the server under this SQL, or undefined.

The value is whatever the query layer put there, which is why it is untyped here: the connection keeps statements without knowing what a statement is.

The cache belongs to the connection because the statement does: a name is meaningful only to the session that parsed it, so a cache anywhere else would hand out names another session does not have.

remember/3

-spec remember(conn(), binary(), term()) -> conn().

Keep a parsed statement under its SQL, if there is room.

Room is claim/1's to give: a connection that is keeping as many statements as it is allowed answers undefined there, and the caller runs the statement unnamed. An unbounded workload therefore gets the uncached path rather than an unbounded pile of parsed statements in the backend.

send/2

-spec send(conn(), minato_protocol:frontend() | [minato_protocol:frontend()]) -> ok | {error, error()}.

Write one frontend message, or a list of them in order.

A list is written as a single send, which is what the extended query protocol wants: Parse, Bind, Execute and Sync in one write is one round trip rather than four.

A message too long for the protocol's length field raises error({minato_protocol, _}) before any of the list is written; see minato_protocol_frontend.

A pooled connection used this way has to have every answer read before it goes back with minato_pool:checkin/2. One with answers still unread is closed by the next checkout, so discard it with minato_pool:discard/2 instead.

statements/1

-spec statements(conn()) -> {non_neg_integer(), non_neg_integer()}.

How many statements this connection is keeping, and how many it may keep.

timeout/1

-spec timeout(conn()) -> timeout().

The per read timeout this connection was opened with.

transaction_status/1

-spec transaction_status(conn()) -> minato_protocol:transaction_status().

What the server last said about the transaction on this connection.

Taken from the status byte of every ReadyForQuery as it is read, so it is only as current as the last message the caller read. failed is a transaction in which a statement has already errored, and everything further is rejected until it is rolled back.

usable/1

-spec usable(conn()) -> boolean().

Whether this connection is still worth handing to a caller.

A pooled connection can die while nobody is holding it: the server restarts, an administrator ends the backend, a failover moves the database. Nothing tells the pool, so without asking it lends a connection that is already gone and the caller gets a socket error for a statement that never reached a server.

Asking costs one non-blocking read, or on Windows a count of the bytes waiting (see minato_socket:quiet/1). A connection under activate/1 answers false without the socket being asked. No bytes waiting means the connection is idle and healthy, which is the answer for a pooled connection. A closed socket is the case this exists for. Bytes waiting, on the socket or already read into the connection, mean the server said something nobody read, so the session is not in the state a caller would assume, and it is cheaper to open a new connection than to work out what it said.

validate(Opts)

-spec validate(opts()) -> ok | {error, {invalid_option, atom()}}.

Whether every option is one minato has, and those that decide how a connection is secured say something it knows.

A key that is not in opts/0 is refused, whatever its value: sslmode, tls, or channel_binding misspelt would otherwise be skipped, and the connection opened with the default the caller meant to change. ssl_options are refused without ssl => true, because options for a TLS session nobody asked for are a session the caller believes it has.

host is a name as a string or an atom, an address as a tuple, or {local, Path}, and not a binary; channel_binding is prefer, require or disable; ssl is a boolean; auth is a list of at least one of scram_sha_256, md5, cleartext and none; password is a binary, a string or a fun that answers one; ssl_options is a list of options, in which verify is verify_peer or verify_none, the handshake is not paused with {handshake, hello}, and no session is kept for another connection or resumed from one: reuse_sessions is false, session_tickets is disabled, and there is no reuse_session or use_ticket; and connect_timeout, timeout and cancel_timeout are each a number of milliseconds, an integer that is not negative, or infinity.

Anything else answers {error, {invalid_option, Key}} for the first key that is wrong, a key that is not an option before a value that is not one, without the value. A value minato did not know used to be read as the default, which is the weaker one: channel_binding => required, or ~"require" out of a configuration file, was prefer. A time that was not one, ~"5000" out of the environment, was found by the first statement that ran out of it, as a badarith.

A key that is not an option and is not an atom either is not repeated in the reason: {error, {invalid_option, not_an_atom}}. A map read from a file of secrets the wrong way round has them as its keys, and the reason goes into an exception, a telemetry event and whatever logs why a pool did not start.

connect/1 raises error({minato_conn, #{message := options, reason := {invalid_option, Key}}}) before it opens a socket, and a pool or a listener does not start: {error, {invalid_option, Key}}.

with_timeout(Conn, Timeout)

-spec with_timeout(conn(), timeout()) -> conn().

The same connection with a different read timeout.

For work that should be given less time than the connection's own budget - a health check that has to answer inside a probe interval - or more, for a query that is known to be slow. The change lasts as long as the connection term the caller keeps.