Skip to main content

xtask/
postgres.rs

1//! A throwaway Postgres for the lifetime of one command.
2//!
3//! Replaces the `sqlx-cli` shell-out: the database is created and migrated
4//! in-process through `sqlx`, using the *same* `migrations/` directory the
5//! server embeds via `server::db::MIGRATOR`. One set of migrations, one
6//! migrator, no second implementation that can drift.
7//!
8//! `initdb` and `pg_ctl` remain external programs because they are external
9//! programs; there is no library form of them.
10//!
11//! The cluster inherits the scheduling priority of `xtask postgres` itself, and
12//! a non-root process cannot lower its nice value again. Callers must not nice
13//! `xtask postgres`, only the command it runs.
14
15use std::net::TcpListener;
16use std::os::unix::process::CommandExt;
17use std::path::{Path, PathBuf};
18use std::process::Command;
19
20use anyhow::{Context, Result, bail};
21use sqlx::migrate::Migrator;
22
23/// The project's migrations, embedded at compile time from the same directory
24/// `server::db::MIGRATOR` reads. Embedding needs no database, which is what
25/// lets this binary be built before the server it goes on to test.
26static MIGRATOR: Migrator = sqlx::migrate!("../migrations");
27
28/// Ports tried in order. No allocator to lean on: a port that cannot be bound is
29/// skipped without starting a server, and `pg_ctl -w` exiting non-zero covers a
30/// port taken between the probe and the start.
31const PORT_RANGE: std::ops::Range<u16> = 54320..54340;
32
33/// Bounds on how long the server will let a client misbehave.
34///
35/// NOT a fix for the hang seen on 2026-08-28, and worth saying so: there the
36/// server sat `idle / ClientRead` — it had answered and was waiting for the
37/// client, so there was no statement to time out. These bound the failures they
38/// can bound: a runaway query, and a transaction abandoned mid-flight holding
39/// locks. Both otherwise sit until the job's own deadline kills it, an hour
40/// later, with no indication of which test was responsible.
41const TIMEOUTS: &[&str] = &[
42    "-c",
43    "statement_timeout=120s",
44    "-c",
45    "idle_in_transaction_session_timeout=300s",
46];
47
48/// A full workspace test run at default parallelism holds well over the stock 100 connections.
49const CONNECTIONS: &[&str] = &["-c", "max_connections=400"];
50
51/// Durability is off on purpose. This cluster is initdb'd moments earlier and
52/// dies with the container, so there is nothing for it to protect — every fsync
53/// is pure cost, paid on cloud block storage, and 275 of the tests create and
54/// migrate a database of their own. Measured worth ~2m30s of a test run.
55const DURABILITY_OFF: &[&str] = &[
56    "-c",
57    "fsync=off",
58    "-c",
59    "synchronous_commit=off",
60    "-c",
61    "full_page_writes=off",
62    "-c",
63    "autovacuum=off",
64];
65
66/// First server major version whose `log_connections` accepts `setup_durations`;
67/// earlier ones take only a boolean and refuse to start on the string.
68const SETUP_DURATIONS_SINCE: u32 = 18;
69
70/// Longest unix socket path the kernel accepts, `sun_path` less its NUL.
71const SOCKET_PATH_MAX: usize = 107;
72
73/// A running cluster that stops itself when dropped.
74pub struct Postgres {
75    data_dir: PathBuf,
76    port: u16,
77    /// Tells the sweep of other runs that the cluster is in use; the kernel releases it on death.
78    _lock: nix::fcntl::Flock<std::fs::File>,
79    /// Kept so the temp dir outlives the cluster.
80    _root: tempfile::TempDir,
81}
82
83impl Postgres {
84    pub fn database_url(&self) -> String {
85        format!("postgres://postgres@127.0.0.1:{}/nomisync", self.port)
86    }
87}
88
89impl Drop for Postgres {
90    fn drop(&mut self) {
91        // Best effort: the container is about to vanish anyway, but leaving a
92        // server holding a port breaks a second invocation in the same job.
93        let _ = Command::new("pg_ctl")
94            .process_group(0)
95            .args([
96                "-D",
97                &self.data_dir.to_string_lossy(),
98                "-m",
99                "immediate",
100                "stop",
101            ])
102            .status();
103    }
104}
105
106/// Children run in their own group so a terminal Ctrl-C cannot kill them half-way
107/// and be mistaken for a failure; xtask's own termination handling decides instead.
108fn run(program: &str, args: &[&str]) -> Result<()> {
109    let status = Command::new(program)
110        .args(args)
111        .process_group(0)
112        .status()
113        .with_context(|| format!("failed to run {program}"))?;
114    if !status.success() {
115        bail!("{program} exited with {status}");
116    }
117    Ok(())
118}
119
120mod sweep;
121
122const CLUSTER_PREFIX: &str = "nomisync-ci-pg";
123
124/// Where the cluster lives when there is room: in RAM. Every test database is
125/// created and dropped, and each `DROP DATABASE` waits for an immediate
126/// checkpoint; on a disk shared with other runs one such checkpoint was seen
127/// to spend 17 s in `write()` while every new connection queued behind it.
128const RAM_DISK: &str = "/dev/shm";
129
130/// A full workspace run peaks well under this.
131const RAM_DISK_MIN_FREE: u64 = 4 << 30;
132
133fn ram_disk_has_room() -> bool {
134    nix::sys::statvfs::statvfs(RAM_DISK).is_ok_and(|fs| {
135        fs.blocks_available().saturating_mul(fs.fragment_size()) >= RAM_DISK_MIN_FREE
136    })
137}
138
139fn cluster_root() -> std::io::Result<tempfile::TempDir> {
140    sweep::sweep_stale_clusters(Path::new(RAM_DISK));
141    match ram_disk_has_room() {
142        true => tempfile::TempDir::with_prefix_in(CLUSTER_PREFIX, RAM_DISK),
143        false => tempfile::TempDir::with_prefix(CLUSTER_PREFIX),
144    }
145}
146
147/// initdb, start, create the database, migrate it.
148pub async fn start() -> Result<Postgres> {
149    // initdb refuses to run as root, and under a uid with no passwd entry it
150    // dies inside getpwuid — the builder image supplies a named non-root user.
151    let root = cluster_root().context("could not make a temp dir")?;
152    let lock = sweep::hold(root.path()).context("could not lock the temp dir")?;
153    let data_dir = root.path().join("pgdata");
154    let socket_dir = data_dir.join("sockets");
155
156    run(
157        "initdb",
158        &[
159            "-D",
160            &data_dir.to_string_lossy(),
161            "-U",
162            "postgres",
163            "--auth=trust",
164            // As prod: without it the container's C locale yields SQL_ASCII.
165            "--encoding=UTF8",
166            "--locale=C",
167        ],
168    )
169    .context("initdb failed")?;
170    std::fs::create_dir_all(&socket_dir).context("could not make the socket dir")?;
171    check_socket_path(&socket_dir)?;
172
173    let log = root.path().join("postgres.log");
174    let port = start_on_free_port(&data_dir, &socket_dir, &log)?;
175    let postgres = Postgres {
176        data_dir,
177        port,
178        _lock: lock,
179        _root: root,
180    };
181
182    println!(">> postgres: listening on 127.0.0.1:{port}");
183    create_and_migrate(&postgres).await?;
184    Ok(postgres)
185}
186
187fn start_on_free_port(data_dir: &Path, socket_dir: &Path, log: &Path) -> Result<u16> {
188    let major = server_major()?;
189    first_started(PORT_RANGE, port_is_free, |port| {
190        let options = server_options(major, port, socket_dir);
191        let status = Command::new("pg_ctl")
192            .process_group(0)
193            .args([
194                "-D",
195                &data_dir.to_string_lossy(),
196                "-l",
197                &log.to_string_lossy(),
198                "-w",
199                "-o",
200                &options,
201                "start",
202            ])
203            .status()
204            .context("failed to run pg_ctl")?;
205        Ok(status.success())
206    })
207    .with_context(|| format!("postgres log {}:\n{}", log.display(), log_tail(log)))
208}
209
210/// Tries each probed-free port in order. A port refused by `probe` costs no
211/// server start; one that `attempt` fails on (taken since the probe, or a server
212/// that cannot start at all) moves on to the next.
213fn first_started(
214    ports: impl Iterator<Item = u16>,
215    probe: impl Fn(u16) -> bool,
216    mut attempt: impl FnMut(u16) -> Result<bool>,
217) -> Result<u16> {
218    let mut free = 0;
219    for port in ports.filter(|&port| probe(port)) {
220        free += 1;
221        if attempt(port)? {
222            return Ok(port);
223        }
224    }
225    match free {
226        0 => bail!("no free port in {PORT_RANGE:?}"),
227        _ => bail!("postgres failed to start on every free port in {PORT_RANGE:?}"),
228    }
229}
230
231/// The socket directory lives inside PGDATA: a shared /tmp is not writable the
232/// same way in every container, and its lock file is where that first shows up.
233fn server_options(major: u32, port: u16, socket_dir: &Path) -> String {
234    let diagnostics: &[&str] = match major >= SETUP_DURATIONS_SINCE {
235        true => &["-c", "log_connections=setup_durations"],
236        false => &[],
237    };
238    format!(
239        "-p {port} -c listen_addresses=127.0.0.1 -c unix_socket_directories={} {}",
240        socket_dir.display(),
241        [DURABILITY_OFF, TIMEOUTS, CONNECTIONS, diagnostics]
242            .concat()
243            .join(" ")
244    )
245}
246
247fn server_major() -> Result<u32> {
248    let output = Command::new("pg_ctl")
249        .arg("--version")
250        .output()
251        .context("failed to run pg_ctl --version")?;
252    if !output.status.success() {
253        bail!("pg_ctl --version exited with {}", output.status);
254    }
255    parse_major(&String::from_utf8_lossy(&output.stdout))
256}
257
258fn parse_major(version: &str) -> Result<u32> {
259    version
260        .split_whitespace()
261        .nth(2)
262        .and_then(|number| number.split('.').next())
263        .and_then(|major| major.parse().ok())
264        .with_context(|| format!("cannot read a major version from {version:?}"))
265}
266
267fn log_tail(log: &Path) -> String {
268    let text = std::fs::read_to_string(log).unwrap_or_default();
269    let lines: Vec<_> = text.lines().rev().take(10).collect();
270    lines.into_iter().rev().collect::<Vec<_>>().join("\n")
271}
272
273fn check_socket_path(socket_dir: &Path) -> Result<()> {
274    let longest = socket_dir.join(format!(".s.PGSQL.{}", PORT_RANGE.end));
275    let length = longest.as_os_str().len();
276    if length > SOCKET_PATH_MAX {
277        bail!(
278            "the socket path {longest:?} is {length} bytes, over the {SOCKET_PATH_MAX} a unix socket allows; use a shorter TMPDIR"
279        );
280    }
281    Ok(())
282}
283
284fn port_is_free(port: u16) -> bool {
285    TcpListener::bind(("127.0.0.1", port)).is_ok()
286}
287
288async fn create_and_migrate(postgres: &Postgres) -> Result<()> {
289    use sqlx::{Connection, Executor, PgConnection};
290
291    let admin = format!("postgres://postgres@127.0.0.1:{}/postgres", postgres.port);
292    let mut conn = PgConnection::connect(&admin)
293        .await
294        .context("could not connect to the new cluster")?;
295    conn.execute("CREATE DATABASE nomisync")
296        .await
297        .context("could not create the nomisync database")?;
298    conn.close().await.ok();
299
300    let mut conn = PgConnection::connect(&postgres.database_url())
301        .await
302        .context("could not connect to the nomisync database")?;
303    MIGRATOR.run(&mut conn).await.context("migrations failed")?;
304    conn.close().await.ok();
305
306    println!(
307        ">> postgres: migrated ({} migrations)",
308        MIGRATOR.iter().count()
309    );
310    Ok(())
311}
312
313#[cfg(test)]
314mod tests;