midas-migrate-cli 0.8.2

Do painless migration 🦀
Documentation
//! Phase 7 CLI coverage: process concurrency, kill recovery, and lock timeouts.

mod common;

use std::fs;
use std::path::{
  Path,
  PathBuf,
};
use std::process::{
  Child,
  Command,
  Output,
  Stdio,
};
use std::time::{
  Duration,
  Instant,
};

use midas::config::Config;
use midas::sequel::{
  self,
};
use postgres::{
  Client,
  NoTls,
};
use predicates::prelude::*;

fn temp_dir(prefix: &str) -> PathBuf {
  let path = std::env::temp_dir().join(common::unique_name(prefix));
  fs::create_dir_all(&path).expect("temp dir");
  path
}

fn spawn(args: &[String], cwd: &Path) -> Child {
  let mut command = Command::new(assert_cmd::cargo::cargo_bin!("midas"));
  command.args(args).current_dir(cwd);
  for key in common::ENV_KEYS {
    command.env_remove(key);
  }
  command
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn()
    .expect("spawn midas")
}

fn wait(child: Child) -> Output {
  child.wait_with_output().expect("wait for midas")
}

#[test]
fn two_processes_apply_each_migration_once() {
  let root = temp_dir("phase7-processes");
  let migrations = root.join("migrations");
  fs::create_dir_all(&migrations).expect("migrations");
  fs::write(
    migrations.join("1_init.sql"),
    "-- !UP\ncreate table concurrent (id integer);\n-- !DOWN\ndrop table concurrent;\n",
  )
  .expect("write migration");
  let database = root.join("app.db3");

  let args = vec![
    "--database".to_string(),
    database.to_string_lossy().into_owned(),
    "--source".to_string(),
    migrations.to_string_lossy().into_owned(),
    "run".to_string(),
  ];
  let children = vec![spawn(&args, &root), spawn(&args, &root)];
  for output in children.into_iter().map(wait) {
    assert!(
      output.status.success(),
      "concurrent run failed: {}",
      String::from_utf8_lossy(&output.stderr)
    );
  }

  let config = Config {
    database_url: Some(database.to_string_lossy().into_owned()),
    ..Config::default()
  };
  let mut backend = sequel::connect(&config).expect("connect");
  let records = backend.list_migrations().expect("records");
  assert_eq!(records.len(), 1, "migration must be recorded exactly once");
  assert!(records[0].success);

  fs::remove_dir_all(root).expect("cleanup");
}

struct PgDatabase {
  admin_url: String,
  name: String,
}

impl PgDatabase {
  fn create(prefix: &str) -> Option<Self> {
    let admin_url = std::env::var("MIDAS_TEST_POSTGRES_URL").ok()?;
    let name = common::unique_name(prefix);
    let mut client = Client::connect(&admin_url, NoTls).expect("admin connect");
    client
      .batch_execute(&format!("create database \"{name}\""))
      .expect("create database");
    Some(Self { admin_url, name })
  }

  fn url(&self) -> String {
    let base = self
      .admin_url
      .rsplit_once('/')
      .map_or(self.admin_url.as_str(), |(base, _)| base);
    format!("{base}/{}", self.name)
  }
}

impl Drop for PgDatabase {
  fn drop(&mut self) {
    if let Ok(mut client) = Client::connect(&self.admin_url, NoTls) {
      let _ = client.batch_execute(&format!("drop database if exists \"{}\" with (force)", self.name));
    }
  }
}

fn write_postgres_migrations(root: &Path, contents: &str) -> PathBuf {
  let migrations = root.join("migrations");
  fs::create_dir_all(&migrations).expect("migrations");
  fs::write(migrations.join("1_slow.sql"), contents).expect("write migration");
  migrations
}

#[test]
#[ignore = "requires a PostgreSQL database in MIDAS_TEST_POSTGRES_URL"]
fn second_process_times_out_on_the_advisory_lock() {
  let Some(database) = PgDatabase::create("phase7_lock") else {
    return;
  };
  let target = database.url();
  let root = temp_dir("phase7-lock");
  let migrations = write_postgres_migrations(&root, "-- !UP\nselect 1;\n-- !DOWN\nselect 1;\n");

  let config = Config {
    database_url: Some(target.clone()),
    lock_timeout: Duration::from_secs(5),
    ..Config::default()
  };
  let mut holder = sequel::connect(&config).expect("holder");
  holder.as_mut().lock().expect("hold lock");

  let args = vec![
    "--database".to_string(),
    target.clone(),
    "--source".to_string(),
    migrations.to_string_lossy().into_owned(),
    "run".to_string(),
  ];
  let output = wait(spawn(&args, &root));

  holder.as_mut().unlock().expect("unlock");
  assert_eq!(output.status.code(), Some(2), "lock timeout must exit 2");
  assert!(
    String::from_utf8_lossy(&output.stderr)
      .to_lowercase()
      .contains("lock"),
    "stderr must name the lock failure: {}",
    String::from_utf8_lossy(&output.stderr)
  );

  drop(database);
  fs::remove_dir_all(root).expect("cleanup");
}

#[test]
#[ignore = "requires a PostgreSQL database in MIDAS_TEST_POSTGRES_URL"]
fn killed_migration_leaves_a_dirty_row_and_resolve_works() {
  let Some(database) = PgDatabase::create("phase7_kill") else {
    return;
  };
  let target = database.url();
  let root = temp_dir("phase7-kill");
  let migrations = write_postgres_migrations(
    &root,
    "-- no-transaction\ncreate table partial_kill (id integer);\nselect pg_sleep(60);\n",
  );

  let args = vec![
    "--database".to_string(),
    target.clone(),
    "--source".to_string(),
    migrations.to_string_lossy().into_owned(),
    "run".to_string(),
  ];
  let mut child = spawn(&args, &root);

  let deadline = Instant::now() + Duration::from_secs(20);
  let mut probe = Client::connect(&target, NoTls).expect("probe");
  loop {
    let dirty = probe
      .query_one(
        "select exists(select 1 from midas.__schema_migrations where success = false)",
        &[],
      )
      .map(|row| row.get::<_, bool>(0))
      .unwrap_or(false);
    if dirty {
      break;
    }
    assert!(
      Instant::now() < deadline,
      "migration did not become dirty before the deadline"
    );
    std::thread::sleep(Duration::from_millis(25));
  }

  let backend_pid: i32 = probe
    .query_one(
      "select pid from pg_stat_activity where datname = current_database() \
       and query ilike '%pg_sleep%' and pid <> pg_backend_pid() limit 1",
      &[],
    )
    .expect("migration backend pid")
    .get(0);

  child.kill().expect("kill midas");
  let _ = child.wait().expect("reap midas");
  // Postgres does not poll for a dead client socket during `pg_sleep`, so ask
  // the server to reap the orphaned backend exactly as a crashed process would.
  probe
    .execute("select pg_terminate_backend($1)", &[&backend_pid])
    .expect("terminate orphaned backend");

  // PostgreSQL releases a session advisory lock when it notices the dead
  // connection. Wait for that bounded condition instead of sleeping blindly.
  let deadline = Instant::now() + Duration::from_secs(20);
  loop {
    let held: i64 = probe
      .query_one("select count(*) from pg_locks where locktype = 'advisory'", &[])
      .expect("lock query")
      .get(0);
    if held == 0 {
      break;
    }
    assert!(
      Instant::now() < deadline,
      "advisory lock was not released after killing the migration process"
    );
    std::thread::sleep(Duration::from_millis(25));
  }

  let dirty = probe
    .query_one(
      "select exists(select 1 from midas.__schema_migrations where success = false)",
      &[],
    )
    .expect("dirty query")
    .get::<_, bool>(0);
  assert!(dirty, "killed process must leave a dirty row");

  common::run_midas(
    &[
      "--database",
      &target,
      "--source",
      &migrations.to_string_lossy(),
      "resolve",
      "--rolled-back",
    ],
    &root,
  )
  .success();

  let dirty = probe
    .query_one(
      "select exists(select 1 from midas.__schema_migrations where success = false)",
      &[],
    )
    .expect("dirty query")
    .get::<_, bool>(0);
  assert!(!dirty, "resolve must clear the dirty row");

  drop(database);
  fs::remove_dir_all(root).expect("cleanup");
}

#[test]
fn schema_sql_rejects_unsupported_dialects() {
  let root = temp_dir("phase7-dialect");
  let schema = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../midas/tests/fixtures/offline/schema.toml");
  common::run_midas(
    &["schema", "sql", &schema.to_string_lossy(), "--dialect", "sqlite"],
    &root,
  )
  .failure()
  .stderr(predicate::str::contains("for sqlite"));
  fs::remove_dir_all(root).expect("cleanup");
}

#[test]
fn status_redacts_database_passwords() {
  let root = temp_dir("phase7-redact");
  // A failing connection prints the error chain; the configured URL must never
  // leak the password in that output.
  common::run_midas(
    &[
      "--database",
      "postgres://user:super-secret@127.0.0.1:1/app",
      "run",
    ],
    &root,
  )
  .failure()
  .stderr(predicate::str::contains("super-secret").not());
  fs::remove_dir_all(root).expect("cleanup");
}