hazine 0.2.2

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! The supervisor, run against shell scripts that stand in for the DuckDB CLI.
#![cfg(unix)]

use std::net::SocketAddr;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use hazine::{Config, Error, supervisor};
use tokio::sync::oneshot;

/// An executable `sh` script with `body`, standing in for `duckdb`. It
/// answers `-version` like DuckDB `version` does.
fn stub_version(dir: &Path, version: &str, body: &str) -> PathBuf {
    let path = dir.join("duckdb");
    std::fs::write(
        &path,
        format!(
            "#!/bin/sh\nif [ \"$1\" = -version ]; then echo '{version} (Cyanoptera) 8d78114e90'; exit 0; fi\n{body}\n"
        ),
    )
    .unwrap();
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
    path
}

/// A DuckDB 2.0.1 stand-in running `body`.
fn stub(dir: &Path, body: &str) -> PathBuf {
    stub_version(dir, "v2.0.1", body)
}

/// A loopback address nothing listens on.
fn free_addr() -> SocketAddr {
    std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
}

fn config(dir: &Path, duckdb: PathBuf) -> Config {
    let init = dir.join("init.sql");
    std::fs::write(&init, "SELECT 1;\n").unwrap();
    Config {
        duckdb,
        init,
        database: Some(dir.join("lake.duckdb")),
        quack_addr: free_addr(),
        ready_timeout: Duration::from_secs(30),
        stop_timeout: Duration::from_secs(5),
        restart_delay: Duration::from_millis(10),
        max_failures: 3,
    }
}

/// Wait until `path` exists, for at most a few seconds.
async fn wait_for(path: &Path) {
    let start = Instant::now();
    while !path.exists() {
        assert!(
            start.elapsed() < Duration::from_secs(5),
            "{path:?} never appeared"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

#[tokio::test]
async fn starts_duckdb_with_the_init_file_and_stops_it_by_closing_stdin() {
    let dir = tempfile::tempdir().unwrap();
    let seen = dir.path().join("seen");
    // Record the arguments and address, then serve until stdin closes, as the
    // DuckDB CLI does.
    let duckdb = stub(
        dir.path(),
        &format!(
            "echo \"$* $HAZINE_QUACK_ADDR\" > {seen}.tmp && mv {seen}.tmp {seen}\nexec cat",
            seen = seen.display()
        ),
    );
    let config = config(dir.path(), duckdb);
    let expected = format!(
        "-no-agent -batch -bail -init {} {} {}\n",
        config.init.display(),
        config.database.as_ref().unwrap().display(),
        config.quack_addr
    );
    let (stop, stopped) = oneshot::channel::<()>();
    let server = tokio::spawn(supervisor::run(config, async {
        let _ = stopped.await;
    }));

    wait_for(&seen).await;
    assert_eq!(std::fs::read_to_string(&seen).unwrap(), expected);

    stop.send(()).unwrap();
    let result = tokio::time::timeout(Duration::from_secs(5), server)
        .await
        .expect("DuckDB stops once its stdin closes")
        .unwrap();
    assert!(result.is_ok(), "{result:?}");
}

#[tokio::test]
async fn gives_up_when_duckdb_keeps_failing_before_it_listens() {
    let dir = tempfile::tempdir().unwrap();
    let runs = dir.path().join("runs");
    let duckdb = stub(
        dir.path(),
        &format!("echo run >> {}\nexit 3", runs.display()),
    );
    let result = supervisor::run(config(dir.path(), duckdb), std::future::pending()).await;
    assert!(
        matches!(result, Err(Error::GaveUp { count: 3 })),
        "{result:?}"
    );
    assert_eq!(std::fs::read_to_string(&runs).unwrap().lines().count(), 3);
}

#[tokio::test]
async fn kills_duckdb_that_does_not_exit_when_stdin_closes() {
    let dir = tempfile::tempdir().unwrap();
    let started = dir.path().join("started");
    let duckdb = stub(
        dir.path(),
        &format!("touch {}\nexec sleep 60", started.display()),
    );
    let mut config = config(dir.path(), duckdb);
    config.stop_timeout = Duration::from_millis(200);
    let (stop, stopped) = oneshot::channel::<()>();
    let server = tokio::spawn(supervisor::run(config, async {
        let _ = stopped.await;
    }));

    wait_for(&started).await;
    stop.send(()).unwrap();
    let result = tokio::time::timeout(Duration::from_secs(5), server)
        .await
        .expect("DuckDB is killed after the stop timeout")
        .unwrap();
    assert!(result.is_ok(), "{result:?}");
}

#[tokio::test]
async fn refuses_an_address_another_process_serves() {
    let dir = tempfile::tempdir().unwrap();
    let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let mut config = config(dir.path(), stub(dir.path(), "exec cat"));
    config.quack_addr = taken.local_addr().unwrap();
    let result = supervisor::run(config, std::future::pending()).await;
    assert!(matches!(result, Err(Error::AddrInUse { .. })), "{result:?}");
}

#[tokio::test]
async fn reports_a_duckdb_that_cannot_be_started() {
    let dir = tempfile::tempdir().unwrap();
    let config = config(dir.path(), dir.path().join("no-such-duckdb"));
    let result = supervisor::run(config, std::future::pending()).await;
    assert!(matches!(result, Err(Error::Spawn { .. })), "{result:?}");
}

#[tokio::test]
async fn refuses_duckdb_older_than_2() {
    let dir = tempfile::tempdir().unwrap();
    let started = dir.path().join("started");
    let duckdb = stub_version(
        dir.path(),
        "v1.5.4",
        &format!("touch {}\nexec cat", started.display()),
    );
    let result = supervisor::run(config(dir.path(), duckdb), std::future::pending()).await;
    assert!(
        matches!(result, Err(Error::UnsupportedVersion { .. })),
        "{result:?}"
    );
    assert!(!started.exists(), "an old DuckDB is never started to serve");
}