Lines
94.15 %
Functions
87.93 %
Branches
100 %
//! A throwaway Postgres for the lifetime of one command.
//!
//! Replaces the `sqlx-cli` shell-out: the database is created and migrated
//! in-process through `sqlx`, using the *same* `migrations/` directory the
//! server embeds via `server::db::MIGRATOR`. One set of migrations, one
//! migrator, no second implementation that can drift.
//! `initdb` and `pg_ctl` remain external programs because they are external
//! programs; there is no library form of them.
//! The cluster inherits the scheduling priority of `xtask postgres` itself, and
//! a non-root process cannot lower its nice value again. Callers must not nice
//! `xtask postgres`, only the command it runs.
use std::net::TcpListener;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use sqlx::migrate::Migrator;
/// The project's migrations, embedded at compile time from the same directory
/// `server::db::MIGRATOR` reads. Embedding needs no database, which is what
/// lets this binary be built before the server it goes on to test.
static MIGRATOR: Migrator = sqlx::migrate!("../migrations");
/// Ports tried in order. No allocator to lean on: a port that cannot be bound is
/// skipped without starting a server, and `pg_ctl -w` exiting non-zero covers a
/// port taken between the probe and the start.
const PORT_RANGE: std::ops::Range<u16> = 54320..54340;
/// Bounds on how long the server will let a client misbehave.
///
/// NOT a fix for the hang seen on 2026-08-28, and worth saying so: there the
/// server sat `idle / ClientRead` — it had answered and was waiting for the
/// client, so there was no statement to time out. These bound the failures they
/// can bound: a runaway query, and a transaction abandoned mid-flight holding
/// locks. Both otherwise sit until the job's own deadline kills it, an hour
/// later, with no indication of which test was responsible.
const TIMEOUTS: &[&str] = &[
"-c",
"statement_timeout=120s",
"idle_in_transaction_session_timeout=300s",
];
/// A full workspace test run at default parallelism holds well over the stock 100 connections.
const CONNECTIONS: &[&str] = &["-c", "max_connections=400"];
/// Durability is off on purpose. This cluster is initdb'd moments earlier and
/// dies with the container, so there is nothing for it to protect — every fsync
/// is pure cost, paid on cloud block storage, and 275 of the tests create and
/// migrate a database of their own. Measured worth ~2m30s of a test run.
const DURABILITY_OFF: &[&str] = &[
"fsync=off",
"synchronous_commit=off",
"full_page_writes=off",
"autovacuum=off",
/// First server major version whose `log_connections` accepts `setup_durations`;
/// earlier ones take only a boolean and refuse to start on the string.
const SETUP_DURATIONS_SINCE: u32 = 18;
/// Longest unix socket path the kernel accepts, `sun_path` less its NUL.
const SOCKET_PATH_MAX: usize = 107;
/// A running cluster that stops itself when dropped.
pub struct Postgres {
data_dir: PathBuf,
port: u16,
/// Tells the sweep of other runs that the cluster is in use; the kernel releases it on death.
_lock: nix::fcntl::Flock<std::fs::File>,
/// Kept so the temp dir outlives the cluster.
_root: tempfile::TempDir,
}
impl Postgres {
pub fn database_url(&self) -> String {
format!("postgres://postgres@127.0.0.1:{}/nomisync", self.port)
impl Drop for Postgres {
fn drop(&mut self) {
// Best effort: the container is about to vanish anyway, but leaving a
// server holding a port breaks a second invocation in the same job.
let _ = Command::new("pg_ctl")
.process_group(0)
.args([
"-D",
&self.data_dir.to_string_lossy(),
"-m",
"immediate",
"stop",
])
.status();
/// Children run in their own group so a terminal Ctrl-C cannot kill them half-way
/// and be mistaken for a failure; xtask's own termination handling decides instead.
fn run(program: &str, args: &[&str]) -> Result<()> {
let status = Command::new(program)
.args(args)
.status()
.with_context(|| format!("failed to run {program}"))?;
if !status.success() {
bail!("{program} exited with {status}");
Ok(())
mod sweep;
const CLUSTER_PREFIX: &str = "nomisync-ci-pg";
/// Where the cluster lives when there is room: in RAM. Every test database is
/// created and dropped, and each `DROP DATABASE` waits for an immediate
/// checkpoint; on a disk shared with other runs one such checkpoint was seen
/// to spend 17 s in `write()` while every new connection queued behind it.
const RAM_DISK: &str = "/dev/shm";
/// A full workspace run peaks well under this.
const RAM_DISK_MIN_FREE: u64 = 4 << 30;
fn ram_disk_has_room() -> bool {
nix::sys::statvfs::statvfs(RAM_DISK).is_ok_and(|fs| {
fs.blocks_available().saturating_mul(fs.fragment_size()) >= RAM_DISK_MIN_FREE
})
fn cluster_root() -> std::io::Result<tempfile::TempDir> {
sweep::sweep_stale_clusters(Path::new(RAM_DISK));
match ram_disk_has_room() {
true => tempfile::TempDir::with_prefix_in(CLUSTER_PREFIX, RAM_DISK),
false => tempfile::TempDir::with_prefix(CLUSTER_PREFIX),
/// initdb, start, create the database, migrate it.
pub async fn start() -> Result<Postgres> {
// initdb refuses to run as root, and under a uid with no passwd entry it
// dies inside getpwuid — the builder image supplies a named non-root user.
let root = cluster_root().context("could not make a temp dir")?;
let lock = sweep::hold(root.path()).context("could not lock the temp dir")?;
let data_dir = root.path().join("pgdata");
let socket_dir = data_dir.join("sockets");
run(
"initdb",
&[
&data_dir.to_string_lossy(),
"-U",
"postgres",
"--auth=trust",
// As prod: without it the container's C locale yields SQL_ASCII.
"--encoding=UTF8",
"--locale=C",
],
)
.context("initdb failed")?;
std::fs::create_dir_all(&socket_dir).context("could not make the socket dir")?;
check_socket_path(&socket_dir)?;
let log = root.path().join("postgres.log");
let port = start_on_free_port(&data_dir, &socket_dir, &log)?;
let postgres = Postgres {
data_dir,
port,
_lock: lock,
_root: root,
};
println!(">> postgres: listening on 127.0.0.1:{port}");
create_and_migrate(&postgres).await?;
Ok(postgres)
fn start_on_free_port(data_dir: &Path, socket_dir: &Path, log: &Path) -> Result<u16> {
let major = server_major()?;
first_started(PORT_RANGE, port_is_free, |port| {
let options = server_options(major, port, socket_dir);
let status = Command::new("pg_ctl")
"-l",
&log.to_string_lossy(),
"-w",
"-o",
&options,
"start",
.context("failed to run pg_ctl")?;
Ok(status.success())
.with_context(|| format!("postgres log {}:\n{}", log.display(), log_tail(log)))
/// Tries each probed-free port in order. A port refused by `probe` costs no
/// server start; one that `attempt` fails on (taken since the probe, or a server
/// that cannot start at all) moves on to the next.
fn first_started(
ports: impl Iterator<Item = u16>,
probe: impl Fn(u16) -> bool,
mut attempt: impl FnMut(u16) -> Result<bool>,
) -> Result<u16> {
let mut free = 0;
for port in ports.filter(|&port| probe(port)) {
free += 1;
if attempt(port)? {
return Ok(port);
match free {
0 => bail!("no free port in {PORT_RANGE:?}"),
_ => bail!("postgres failed to start on every free port in {PORT_RANGE:?}"),
/// The socket directory lives inside PGDATA: a shared /tmp is not writable the
/// same way in every container, and its lock file is where that first shows up.
fn server_options(major: u32, port: u16, socket_dir: &Path) -> String {
let diagnostics: &[&str] = match major >= SETUP_DURATIONS_SINCE {
true => &["-c", "log_connections=setup_durations"],
false => &[],
format!(
"-p {port} -c listen_addresses=127.0.0.1 -c unix_socket_directories={} {}",
socket_dir.display(),
[DURABILITY_OFF, TIMEOUTS, CONNECTIONS, diagnostics]
.concat()
.join(" ")
fn server_major() -> Result<u32> {
let output = Command::new("pg_ctl")
.arg("--version")
.output()
.context("failed to run pg_ctl --version")?;
if !output.status.success() {
bail!("pg_ctl --version exited with {}", output.status);
parse_major(&String::from_utf8_lossy(&output.stdout))
fn parse_major(version: &str) -> Result<u32> {
version
.split_whitespace()
.nth(2)
.and_then(|number| number.split('.').next())
.and_then(|major| major.parse().ok())
.with_context(|| format!("cannot read a major version from {version:?}"))
fn log_tail(log: &Path) -> String {
let text = std::fs::read_to_string(log).unwrap_or_default();
let lines: Vec<_> = text.lines().rev().take(10).collect();
lines.into_iter().rev().collect::<Vec<_>>().join("\n")
fn check_socket_path(socket_dir: &Path) -> Result<()> {
let longest = socket_dir.join(format!(".s.PGSQL.{}", PORT_RANGE.end));
let length = longest.as_os_str().len();
if length > SOCKET_PATH_MAX {
bail!(
"the socket path {longest:?} is {length} bytes, over the {SOCKET_PATH_MAX} a unix socket allows; use a shorter TMPDIR"
);
fn port_is_free(port: u16) -> bool {
TcpListener::bind(("127.0.0.1", port)).is_ok()
async fn create_and_migrate(postgres: &Postgres) -> Result<()> {
use sqlx::{Connection, Executor, PgConnection};
let admin = format!("postgres://postgres@127.0.0.1:{}/postgres", postgres.port);
let mut conn = PgConnection::connect(&admin)
.await
.context("could not connect to the new cluster")?;
conn.execute("CREATE DATABASE nomisync")
.context("could not create the nomisync database")?;
conn.close().await.ok();
let mut conn = PgConnection::connect(&postgres.database_url())
.context("could not connect to the nomisync database")?;
MIGRATOR.run(&mut conn).await.context("migrations failed")?;
println!(
">> postgres: migrated ({} migrations)",
MIGRATOR.iter().count()
#[cfg(test)]
mod tests;