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

            
15
use std::net::TcpListener;
16
use std::os::unix::process::CommandExt;
17
use std::path::{Path, PathBuf};
18
use std::process::Command;
19

            
20
use anyhow::{Context, Result, bail};
21
use 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.
26
static 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.
31
const 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.
41
const 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.
49
const 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.
55
const 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.
68
const SETUP_DURATIONS_SINCE: u32 = 18;
69

            
70
/// Longest unix socket path the kernel accepts, `sun_path` less its NUL.
71
const SOCKET_PATH_MAX: usize = 107;
72

            
73
/// A running cluster that stops itself when dropped.
74
pub 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

            
83
impl Postgres {
84
14
    pub fn database_url(&self) -> String {
85
14
        format!("postgres://postgres@127.0.0.1:{}/nomisync", self.port)
86
14
    }
87
}
88

            
89
impl Drop for Postgres {
90
7
    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
7
        let _ = Command::new("pg_ctl")
94
7
            .process_group(0)
95
7
            .args([
96
7
                "-D",
97
7
                &self.data_dir.to_string_lossy(),
98
7
                "-m",
99
7
                "immediate",
100
7
                "stop",
101
7
            ])
102
7
            .status();
103
7
    }
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.
108
7
fn run(program: &str, args: &[&str]) -> Result<()> {
109
7
    let status = Command::new(program)
110
7
        .args(args)
111
7
        .process_group(0)
112
7
        .status()
113
        .with_context(|| format!("failed to run {program}"))?;
114
7
    if !status.success() {
115
        bail!("{program} exited with {status}");
116
7
    }
117
7
    Ok(())
118
7
}
119

            
120
mod sweep;
121

            
122
const 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.
128
const RAM_DISK: &str = "/dev/shm";
129

            
130
/// A full workspace run peaks well under this.
131
const RAM_DISK_MIN_FREE: u64 = 4 << 30;
132

            
133
9
fn ram_disk_has_room() -> bool {
134
9
    nix::sys::statvfs::statvfs(RAM_DISK).is_ok_and(|fs| {
135
9
        fs.blocks_available().saturating_mul(fs.fragment_size()) >= RAM_DISK_MIN_FREE
136
9
    })
137
9
}
138

            
139
8
fn cluster_root() -> std::io::Result<tempfile::TempDir> {
140
8
    sweep::sweep_stale_clusters(Path::new(RAM_DISK));
141
8
    match ram_disk_has_room() {
142
        true => tempfile::TempDir::with_prefix_in(CLUSTER_PREFIX, RAM_DISK),
143
8
        false => tempfile::TempDir::with_prefix(CLUSTER_PREFIX),
144
    }
145
8
}
146

            
147
/// initdb, start, create the database, migrate it.
148
7
pub 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
7
    let root = cluster_root().context("could not make a temp dir")?;
152
7
    let lock = sweep::hold(root.path()).context("could not lock the temp dir")?;
153
7
    let data_dir = root.path().join("pgdata");
154
7
    let socket_dir = data_dir.join("sockets");
155

            
156
7
    run(
157
7
        "initdb",
158
7
        &[
159
7
            "-D",
160
7
            &data_dir.to_string_lossy(),
161
7
            "-U",
162
7
            "postgres",
163
7
            "--auth=trust",
164
7
            // As prod: without it the container's C locale yields SQL_ASCII.
165
7
            "--encoding=UTF8",
166
7
            "--locale=C",
167
7
        ],
168
7
    )
169
7
    .context("initdb failed")?;
170
7
    std::fs::create_dir_all(&socket_dir).context("could not make the socket dir")?;
171
7
    check_socket_path(&socket_dir)?;
172

            
173
7
    let log = root.path().join("postgres.log");
174
7
    let port = start_on_free_port(&data_dir, &socket_dir, &log)?;
175
7
    let postgres = Postgres {
176
7
        data_dir,
177
7
        port,
178
7
        _lock: lock,
179
7
        _root: root,
180
7
    };
181

            
182
7
    println!(">> postgres: listening on 127.0.0.1:{port}");
183
7
    create_and_migrate(&postgres).await?;
184
7
    Ok(postgres)
185
7
}
186

            
187
7
fn start_on_free_port(data_dir: &Path, socket_dir: &Path, log: &Path) -> Result<u16> {
188
7
    let major = server_major()?;
189
7
    first_started(PORT_RANGE, port_is_free, |port| {
190
7
        let options = server_options(major, port, socket_dir);
191
7
        let status = Command::new("pg_ctl")
192
7
            .process_group(0)
193
7
            .args([
194
7
                "-D",
195
7
                &data_dir.to_string_lossy(),
196
7
                "-l",
197
7
                &log.to_string_lossy(),
198
7
                "-w",
199
7
                "-o",
200
7
                &options,
201
7
                "start",
202
7
            ])
203
7
            .status()
204
7
            .context("failed to run pg_ctl")?;
205
7
        Ok(status.success())
206
7
    })
207
    .with_context(|| format!("postgres log {}:\n{}", log.display(), log_tail(log)))
208
7
}
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.
213
11
fn first_started(
214
11
    ports: impl Iterator<Item = u16>,
215
11
    probe: impl Fn(u16) -> bool,
216
11
    mut attempt: impl FnMut(u16) -> Result<bool>,
217
11
) -> Result<u16> {
218
11
    let mut free = 0;
219
25
    for port in ports.filter(|&port| probe(port)) {
220
14
        free += 1;
221
14
        if attempt(port)? {
222
9
            return Ok(port);
223
5
        }
224
    }
225
2
    match free {
226
1
        0 => bail!("no free port in {PORT_RANGE:?}"),
227
1
        _ => bail!("postgres failed to start on every free port in {PORT_RANGE:?}"),
228
    }
229
11
}
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.
233
9
fn server_options(major: u32, port: u16, socket_dir: &Path) -> String {
234
9
    let diagnostics: &[&str] = match major >= SETUP_DURATIONS_SINCE {
235
1
        true => &["-c", "log_connections=setup_durations"],
236
8
        false => &[],
237
    };
238
9
    format!(
239
9
        "-p {port} -c listen_addresses=127.0.0.1 -c unix_socket_directories={} {}",
240
9
        socket_dir.display(),
241
9
        [DURABILITY_OFF, TIMEOUTS, CONNECTIONS, diagnostics]
242
9
            .concat()
243
9
            .join(" ")
244
    )
245
9
}
246

            
247
7
fn server_major() -> Result<u32> {
248
7
    let output = Command::new("pg_ctl")
249
7
        .arg("--version")
250
7
        .output()
251
7
        .context("failed to run pg_ctl --version")?;
252
7
    if !output.status.success() {
253
        bail!("pg_ctl --version exited with {}", output.status);
254
7
    }
255
7
    parse_major(&String::from_utf8_lossy(&output.stdout))
256
7
}
257

            
258
11
fn parse_major(version: &str) -> Result<u32> {
259
11
    version
260
11
        .split_whitespace()
261
11
        .nth(2)
262
10
        .and_then(|number| number.split('.').next())
263
10
        .and_then(|major| major.parse().ok())
264
2
        .with_context(|| format!("cannot read a major version from {version:?}"))
265
11
}
266

            
267
fn 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

            
273
9
fn check_socket_path(socket_dir: &Path) -> Result<()> {
274
9
    let longest = socket_dir.join(format!(".s.PGSQL.{}", PORT_RANGE.end));
275
9
    let length = longest.as_os_str().len();
276
9
    if length > SOCKET_PATH_MAX {
277
1
        bail!(
278
1
            "the socket path {longest:?} is {length} bytes, over the {SOCKET_PATH_MAX} a unix socket allows; use a shorter TMPDIR"
279
        );
280
8
    }
281
8
    Ok(())
282
9
}
283

            
284
15
fn port_is_free(port: u16) -> bool {
285
15
    TcpListener::bind(("127.0.0.1", port)).is_ok()
286
15
}
287

            
288
7
async fn create_and_migrate(postgres: &Postgres) -> Result<()> {
289
    use sqlx::{Connection, Executor, PgConnection};
290

            
291
7
    let admin = format!("postgres://postgres@127.0.0.1:{}/postgres", postgres.port);
292
7
    let mut conn = PgConnection::connect(&admin)
293
7
        .await
294
7
        .context("could not connect to the new cluster")?;
295
7
    conn.execute("CREATE DATABASE nomisync")
296
7
        .await
297
7
        .context("could not create the nomisync database")?;
298
7
    conn.close().await.ok();
299

            
300
7
    let mut conn = PgConnection::connect(&postgres.database_url())
301
7
        .await
302
7
        .context("could not connect to the nomisync database")?;
303
7
    MIGRATOR.run(&mut conn).await.context("migrations failed")?;
304
7
    conn.close().await.ok();
305

            
306
7
    println!(
307
        ">> postgres: migrated ({} migrations)",
308
7
        MIGRATOR.iter().count()
309
    );
310
7
    Ok(())
311
7
}
312

            
313
#[cfg(test)]
314
mod tests;