Connecting
Every connection setting of the Rust client lives in one struct, Options, passed to Client::connect. This page covers addresses, logins, TLS, database selection, the connection count, timeouts and what happens when a connection drops.
Addresses
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
// A unix socket: the server's --rdb-socket path, prefixed with "unix:".
let local = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
// TCP: host:port of the native listener (--rdb-addr / --rdb-port, default port 61170).
let remote = Client::connect("db.internal:61170", Options::default()).await;
// Against a default server this fails: TCP logins need a password (see below).
let _ = (local, remote);
Ok(())
}| address form | transport | notes |
|---|---|---|
unix:/path/to/socket | unix socket | no TLS; who may connect is decided by the socket file's permissions (--socket-mode, default 600) and --rdb-socket-auth |
host:port | TCP | always TLS; the server's certificate is checked as Options::trust says |
Client::connect opens every connection and logs each in before it returns. A wrong path, a refused login, a missing database or a failed migration (when Options::migrations is set) is an error from connect.
Options reference
use rasterizeddb_client::{Client, Login, Options, Result};
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect(
"db.internal:61170",
Options {
login: Login::password("app", std::env::var("RDB_PASSWORD").unwrap_or_default()),
trust: rasterizeddb_client::load_ca("/etc/rdb/ca.pem")?,
database: Some("shop".into()),
connections: 4,
timeout: Some(Duration::from_secs(60)),
max_message_size: 64 * 1024 * 1024,
..Options::default()
},
)
.await?;
let _ = client;
Ok(())
}| field | type | default | what it does |
|---|---|---|---|
login | Login | Login::Trust | who the connections log in as; see Logging in |
trust | Trust | Trust::AcceptAny | how a TCP connection checks the server's certificate; see TLS |
database | Option<String> | None | the database every connection uses; None is the server's default database (--pg-default-db, postgres unless set); see Choosing a database |
connections | usize | 1 | connections opened and shared by every caller (at least one); each carries many statements at once |
timeout | Option<Duration> | 30 s | how long a statement waits for its answer, and a connection for its handshake; None waits for ever; see Timeouts |
max_message_size | usize | 8 MiB | the largest answer accepted, in bytes; a larger one fails whole and costs its connection |
idle_reconnect | Option<Duration> | 20 s | a connection quiet for this long is reopened before the next statement is sent on it; None never does; see Reconnects |
migrations | Option<Migrator> | None | migrations to handle when the client connects; see Migrations |
auto_migrate | AutoMigrate | Apply | what connect does with migrations: Apply, Verify or Off |
Write ..Options::default() after the fields you set, as above, so your code keeps compiling when fields are added.
Logging in
Login | use with | what happens |
|---|---|---|
Login::Trust | a unix socket under --rdb-socket-auth trust (or a listener under --rdb-auth trust) | no login exchange; a server that asks for a login refuses the connection |
Login::Peer | a unix socket under --rdb-socket-auth peer | logs in as the operating-system user this process runs as, with no password; a role of that name must exist and be allowed to log in |
Login::PeerAs(name) | a unix socket under --rdb-socket-auth peer | logs in as name; the server accepts it only when name is the operating-system user connecting |
Login::password(user, password) | TCP (the default --rdb-auth scram-sha-256), or a socket under --rdb-socket-auth scram-sha-256 | SCRAM-SHA-256, bound to the connection; the password never crosses the wire |
Login::password("app", "secret") builds Login::Password { user, password }. Debug output of a Login never prints the password.
A password login also checks the server: the server must prove it holds the role's verifier. A server that lets the connection in without the exchange (one running under trust) is refused at once, and the error tells you to use Login::Trust for it.
On a fresh data directory the server creates one role for the native protocol, named by --rdb-user (default rasterized), with the password from --rdb-password or the RASTERIZEDDB_PASSWORD environment variable:
use rasterizeddb_client::{Client, Login, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let password = std::env::var("RASTERIZEDDB_PASSWORD").expect("set RASTERIZEDDB_PASSWORD");
let client = Client::connect(
"127.0.0.1:61170",
Options { login: Login::password("rasterized", password), ..Options::default() },
)
.await?;
println!("{}", client.fetch_scalar::<String>("SELECT current_user", &[]).await?);
Ok(())
}Peer authentication on a socket needs no secret at all:
use rasterizeddb_client::{Client, Login, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
// Server: --rdb-socket /run/rdb/rdb.sock --rdb-socket-auth peer
let client = Client::connect(
"unix:/run/rdb/rdb.sock",
Options { login: Login::Peer, ..Options::default() },
)
.await?;
let _ = client;
Ok(())
}Roles, passwords and grants are created with SQL or the administration API; see Security.
Trust connections and roles
In 1.0.1, a Login::Trust connection ran as a superuser.
From server 1.1.0, a trust connection that names no role is no longer an administrator in a database that has roles. It keeps reading and writing the tables it created itself and whatever is granted to PUBLIC. A database opened by an earlier version gives PUBLIC every privilege on its existing tables, so plain reads and writes keep working. But it loses everything that needs a superuser or the table's owner: role statements (CREATE USER, ALTER USER…), server administration (BACKUP, STORAGE, CREATE DATABASE…), ALTER TABLE, DROP TABLE and GRANT on those tables (which includes a migration's DDL), and any table another role made since. A database with no roles at all is unchanged.
An application on a trust socket then names the role it runs as with Client::connect_as_role (rasterizeddb_client 1.1.0 and later), leaving options.login at Login::Trust:
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect_as_role("unix:/run/rdb/rdb.sock", Options::default(), "rasterized").await?;
let _ = client;
Ok(())
}The server checks that the role exists in the database the connection selects and may log in. connect_as_role with any login other than Login::Trust, or with an empty role name, fails before connecting. Against a server too old to name a role, connect fails rather than running as nobody.
TLS
Every TCP connection is encrypted. What Options::trust decides is whether the client believes the server it reached:
trust | how to build it | believes |
|---|---|---|
Trust::AcceptAny | the default | any server: encrypted, but not authenticated |
Trust::Pinned(…) | rasterizeddb_client::pin(&["<sha256 fingerprint>"])? | exactly the certificates with these SHA-256 fingerprints |
Trust::RootCa(…) | rasterizeddb_client::load_ca("/etc/rdb/ca.pem")? | certificates signed by a private certificate authority (PEM file, one or more certificates) |
Trust::WebPki | Trust::WebPki | certificates signed by the public web roots |
Trust is re-exported at the crate root (rasterizeddb_client::Trust).
Over a network you do not control, do not keep the default. A password login stays safe from replay under AcceptAny, because the proof is bound to the TLS session. But whoever answers in the server's place sees the proof, can guess passwords against it offline, and reads every statement and row.
The server presents the certificate given by --rdb-cert and --rdb-key. Without them it makes a new self-signed certificate at every start, which a client can encrypt to but never verify. To pin, give the server a certificate it keeps, then take its fingerprint:
openssl x509 -noout -fingerprint -sha256 -in server.pemsha256 Fingerprint=3A:9F:…:C2use rasterizeddb_client::{Client, Login, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect(
"db.internal:61170",
Options {
login: Login::password("app", std::env::var("RDB_PASSWORD").unwrap_or_default()),
// Colons and letter case as openssl prints them are fine.
trust: rasterizeddb_client::pin(&["3A:9F:…:C2"])?,
..Options::default()
},
)
.await?;
let _ = client;
Ok(())
}pin fails with Error::Param when given no fingerprint, or text that is not a SHA-256 fingerprint. Several fingerprints are allowed, which lets you roll a certificate over without downtime: pin the old and the new, change the server's certificate, then drop the old pin.
A unix socket has no TLS. Leave trust at its default for a unix: address.
Choosing a database
A server can hold several databases (see Databases). Options::database picks one for every connection the client opens: the shared ones, each reopened one, and each transaction's.
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let shop = Client::connect(
"unix:/run/rdb/rdb.sock",
Options { database: Some("shop".into()), ..Options::default() },
)
.await?;
let name: String = shop.fetch_scalar("SELECT current_database()", &[]).await?;
assert_eq!(name, "shop");
Ok(())
}- A password or peer login is checked against that database's roles, as a PostgreSQL login is: a role exists in the database it was created in.
- A database that does not exist, or one being imported, fails
connect. - A client is bound to one database. To work with two, make two clients.
- A server that predates database selection makes
connectfail; it never quietly serves the default database instead.Error::may_predate_database_selection()tells you that was the cause. If you can live with the default database, connect again withdatabase: Noneand checkSELECT current_database().
Connections and sharing
There is no separate pool to configure. A Client holds connections multiplexed connections (default one), and each carries many statements in flight at once, sent in turn across the connections. One connection is usually enough; raise it for heavy concurrent load from one process.
ClientisSend + Sync. Create one, wrap it in anArc, and clone theArcinto every task.- A transaction never uses the shared connections. It gets a plain connection of its own. When a transaction ends cleanly its connection is kept for the next transaction for up to 20 seconds (up to eight are kept); otherwise a new one is opened and logged in, which costs a TLS handshake and a SCRAM exchange over TCP.
client.is_connected()says whether every shared connection is open right now. It is not a health check: a connection retired after a quiet spell is closed until the next statement reopens it, which happens by itself.client.close().awaitcloses the shared connections and the kept transaction connections. A transaction still open keeps its own connection until it ends.
Timeouts
Options::timeout (default 30 s) is how long a statement waits for its answer on this side, and how long a connection waits for its handshake. A login has 10 seconds.
The server bounds a statement itself, at its request timeout: --rdb-request-timeout, 30 seconds by default. A statement that runs longer is stopped and fails with SQLSTATE 57014 (Error::is_statement_timeout()). Nothing of it took effect, the connection goes on, and a transaction on it is failed as by any failed statement (roll it back).
So that the server's answer, not the client's own timeout, is what you see when both are 30 seconds, the client waits ANSWER_GRACE (2 seconds) past timeout for each answer.
A timeout on this side ends the wait, not the statement. A statement whose timeout passes, or whose future is dropped, may still run to the end on the server. The error is Error::is_timeout(), and whether a write took effect is unknown.
To run a statement longer than 30 seconds (a large report, an import, a backup):
- Raise the server's limit with
--rdb-request-timeout, or run the statement in a transaction afterSET statement_timeout = '10min'(0means no limit). - Raise
Options::timeoutto match, or set it toNone.
use rasterizeddb_client::prelude::*;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect(
"unix:/run/rdb/rdb.sock",
Options { timeout: Some(Duration::from_secs(15 * 60)), ..Options::default() },
)
.await?;
let tx = client.begin().await?;
tx.run("SET statement_timeout = '10min'").await?;
let total: i64 = tx.fetch_scalar("SELECT count(*) FROM events", params![]).await?;
tx.commit().await?;
println!("{total}");
Ok(())
}Reconnects
The client never sends a statement twice. What it does instead:
- After a failure. A statement whose connection fails returns
Error::Transport; whether it ran is unknown. The next statement on that connection reconnects by itself. - Before a quiet connection is reused. The server closes a native connection that has been idle for its request timeout (30 s). A statement written in the instant it does so would be lost. With
idle_reconnect(default 20 s), a connection quiet for that long is reopened before the next statement is sent on it. This costs one handshake after a quiet spell and no traffic while idle. A connection with a statement in flight is never reopened under it. If you raise--rdb-request-timeouton the server you may raiseidle_reconnecttoo; keep it below the server's value. - Transactions are never moved. A transaction lives and dies with its connection: a transport failure ends it with
Error::TransactionLost. See Transactions.
Answer size
max_message_size (default 8 MiB) is the largest answer this side accepts. The server sends answers of any size. An answer past the limit fails whole (Error::is_message_too_large()), never arrives cut short, and costs the connection it came on; the next statement opens another. The statement itself ran. Raise the limit for a big read, or page it with ORDER BY … LIMIT, keyset pages or a row stream (The ORM).
Limits
- One
Clientserves one database with one login. Use several clients for several databases or roles. - There is no automatic retry of a statement whose connection failed; your code decides, because the statement may have run.
- A client-side timeout does not cancel the statement on the server. To stop a long statement, use the simple-query form with a cancel token (Queries) or the server's statement timeout.
Trust::AcceptAnydoes not authenticate the server. Usepin,load_caorTrust::WebPkiover any network you do not control.