hazine 0.2.4

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! Run the DuckDB CLI as a Quack server, and keep it running.

use std::future::Future;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{ExitStatus, Stdio};
use std::sync::Arc;
use std::time::Duration;

use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
use tokio::net::TcpStream;
use tokio::process::{Child, ChildStdin, Command};

use crate::Error;

/// The environment variable that tells the init file where Quack should
/// listen, e.g. `127.0.0.1:1294`. The init file passes it to `quack_serve`.
pub const QUACK_ADDR_ENV: &str = "HAZINE_QUACK_ADDR";

/// The environment variable holding the Quack access token.
pub const TOKEN_ENV: &str = "QUACK_TOKEN";

/// The oldest DuckDB major version hazine runs (for `-no-agent` and the
/// quack extension from the core repository).
pub const MIN_DUCKDB_MAJOR: u32 = 2;

/// The longest wait between restarts.
const MAX_BACKOFF: Duration = Duration::from_secs(60);

/// How often to look whether Quack is listening yet.
const READY_POLL: Duration = Duration::from_millis(250);

/// How hazine runs DuckDB.
#[derive(Debug, Clone)]
pub struct Config {
    /// The DuckDB CLI: a path, or a name looked up in `PATH`.
    pub duckdb: PathBuf,
    /// SQL run at start: settings, extensions, the DuckLake attach and
    /// `quack_serve`.
    pub init: PathBuf,
    /// A DuckDB database file to open; in memory without one.
    pub database: Option<PathBuf>,
    /// Where Quack listens. Must be a loopback address.
    pub quack_addr: SocketAddr,
    /// How long DuckDB may take to start listening before hazine warns.
    pub ready_timeout: Duration,
    /// How long DuckDB has to exit once its stdin is closed before it is killed.
    pub stop_timeout: Duration,
    /// The first wait before a restart; it doubles with each failed start.
    pub restart_delay: Duration,
    /// Give up after this many exits in a row before Quack was listening.
    pub max_failures: u32,
}

impl Config {
    /// Check what can be checked before DuckDB starts.
    pub fn validate(&self) -> Result<(), Error> {
        if !self.quack_addr.ip().is_loopback() {
            return Err(Error::NotLoopback {
                addr: self.quack_addr,
            });
        }
        let init_error = |source| Error::InitFile {
            path: self.init.clone(),
            source,
        };
        let meta = std::fs::metadata(&self.init).map_err(init_error)?;
        if !meta.is_file() {
            return Err(init_error(std::io::Error::other("not a file")));
        }
        Ok(())
    }

    fn command(&self) -> Command {
        let mut cmd = Command::new(&self.duckdb);
        // -no-agent: plain output even if AI_AGENT is set. -batch: stdin is a
        // pipe, not a terminal. -bail: a failing init statement ends the CLI,
        // so it is restarted rather than left half set up.
        cmd.args(["-no-agent", "-batch", "-bail", "-init"])
            .arg(&self.init);
        if let Some(database) = &self.database {
            cmd.arg(database);
        }
        cmd.env(QUACK_ADDR_ENV, self.quack_addr.to_string())
            // No ANSI colour codes in the log.
            .env("NO_COLOR", "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        cmd
    }
}

/// Check that `duckdb` is a DuckDB CLI of version 2.0 or later.
pub async fn check_version(duckdb: &Path) -> Result<String, Error> {
    let output = Command::new(duckdb)
        .arg("-version")
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .output()
        .await
        .map_err(|source| Error::Spawn {
            program: duckdb.to_path_buf(),
            source,
        })?;
    let text = String::from_utf8_lossy(&output.stdout);
    let version = text
        .split_whitespace()
        .find(|word| word.starts_with('v'))
        .unwrap_or_default()
        .to_string();
    match parse_major(&version) {
        Some(major) if output.status.success() && major >= MIN_DUCKDB_MAJOR => Ok(version),
        _ => Err(Error::UnsupportedVersion {
            program: duckdb.to_path_buf(),
            found: text.trim().to_string(),
        }),
    }
}

/// The major version in `v2.0.1`.
fn parse_major(version: &str) -> Option<u32> {
    version.strip_prefix('v')?.split('.').next()?.parse().ok()
}

/// How one run of DuckDB ended.
enum Outcome {
    /// Stopped by hazine on shutdown.
    Stopped,
    /// Exited on its own.
    Exited { status: ExitStatus, ready: bool },
}

/// Run DuckDB until `shutdown` completes, restarting it whenever it exits.
///
/// Returns an error if DuckDB cannot be started, if the Quack address is
/// taken, or if DuckDB exits `max_failures` times in a row before Quack is
/// listening — so that a service manager sees the failure.
pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(), Error> {
    config.validate()?;
    let version = check_version(&config.duckdb).await?;
    tracing::info!(%version, duckdb = %config.duckdb.display(), "found DuckDB");
    // hazine reads the secrets only to blank them out of DuckDB's output.
    let secrets: Arc<[String]> = crate::setup::render::SECRET_ENVS
        .iter()
        .filter_map(|name| std::env::var(name).ok())
        .filter(|value| !value.is_empty())
        .collect();
    let mut shutdown = std::pin::pin!(shutdown);
    let mut failures = 0;
    let mut backoff = config.restart_delay;
    loop {
        if is_listening(config.quack_addr).await {
            return Err(Error::AddrInUse {
                addr: config.quack_addr,
            });
        }
        let (status, ready) = match run_once(&config, &secrets, shutdown.as_mut()).await? {
            Outcome::Stopped => return Ok(()),
            Outcome::Exited { status, ready } => (status, ready),
        };
        if ready {
            failures = 0;
            backoff = config.restart_delay;
        } else {
            failures += 1;
            if failures >= config.max_failures {
                return Err(Error::GaveUp { count: failures });
            }
        }
        tracing::warn!(
            %status,
            failures,
            restart_in = ?backoff,
            "DuckDB exited; restarting"
        );
        tokio::select! {
            () = tokio::time::sleep(backoff) => {}
            () = shutdown.as_mut() => return Ok(()),
        }
        backoff = (backoff * 2).min(MAX_BACKOFF);
    }
}

/// Start DuckDB once and wait for it to exit or for `shutdown`.
async fn run_once(
    config: &Config,
    secrets: &Arc<[String]>,
    mut shutdown: Pin<&mut impl Future<Output = ()>>,
) -> Result<Outcome, Error> {
    let mut child = config.command().spawn().map_err(|source| Error::Spawn {
        program: config.duckdb.clone(),
        source,
    })?;
    tracing::info!(
        pid = child.id(),
        duckdb = %config.duckdb.display(),
        init = %config.init.display(),
        quack_addr = %config.quack_addr,
        "DuckDB started"
    );
    // Held, never written to: the CLI serves until its stdin closes.
    let stdin = child.stdin.take();
    forward(child.stdout.take(), "stdout", secrets.clone());
    forward(child.stderr.take(), "stderr", secrets.clone());

    let mut listening = std::pin::pin!(wait_listening(config.quack_addr));
    let mut ready = false;
    let deadline = tokio::time::sleep(config.ready_timeout);
    let mut deadline = std::pin::pin!(deadline);
    let mut warned = false;
    loop {
        tokio::select! {
            status = child.wait() => {
                return Ok(Outcome::Exited { status: status?, ready });
            }
            () = &mut listening, if !ready => {
                ready = true;
                let port = config.quack_addr.port();
                tracing::info!(
                    quack_addr = %config.quack_addr,
                    tunnel = %format!("ssh -N -L {port}:{} <host>", config.quack_addr),
                    "Quack is listening"
                );
            }
            () = &mut deadline, if !ready && !warned => {
                warned = true;
                tracing::warn!(
                    quack_addr = %config.quack_addr,
                    waited = ?config.ready_timeout,
                    "Quack is not listening yet; does the init file call quack_serve \
                     on getenv('{QUACK_ADDR_ENV}')?"
                );
            }
            () = shutdown.as_mut() => {
                let status = stop(&mut child, stdin, config.stop_timeout).await?;
                tracing::info!(%status, "DuckDB stopped");
                return Ok(Outcome::Stopped);
            }
        }
    }
}

/// Close DuckDB's stdin and wait for it to exit; kill it after `timeout`.
async fn stop(
    child: &mut Child,
    stdin: Option<ChildStdin>,
    timeout: Duration,
) -> std::io::Result<ExitStatus> {
    drop(stdin);
    match tokio::time::timeout(timeout, child.wait()).await {
        Ok(status) => status,
        Err(_) => {
            tracing::warn!(?timeout, "DuckDB did not exit in time; killing it");
            child.kill().await?;
            child.wait().await
        }
    }
}

/// Log each line DuckDB writes to `stream`, with `secrets` blanked out.
fn forward(
    reader: Option<impl AsyncRead + Unpin + Send + 'static>,
    stream: &'static str,
    secrets: Arc<[String]>,
) {
    let Some(reader) = reader else { return };
    tokio::spawn(async move {
        let mut lines = BufReader::new(reader).lines();
        loop {
            let line = lines
                .next_line()
                .await
                .map(|line| line.map(|line| redact(line, &secrets)));
            match line {
                Ok(Some(line)) if stream == "stderr" => {
                    tracing::warn!(target: "duckdb", stream, "{line}");
                }
                Ok(Some(line)) => tracing::info!(target: "duckdb", stream, "{line}"),
                Ok(None) => break,
                Err(error) => {
                    tracing::debug!(stream, %error, "stopped reading DuckDB output");
                    break;
                }
            }
        }
    });
}

/// `line` with every occurrence of each secret replaced.
fn redact(line: String, secrets: &[String]) -> String {
    secrets.iter().fold(line, |line, secret| {
        if line.contains(secret.as_str()) {
            line.replace(secret.as_str(), "[REDACTED]")
        } else {
            line
        }
    })
}

/// Whether something accepts connections on `addr`.
async fn is_listening(addr: SocketAddr) -> bool {
    matches!(
        tokio::time::timeout(READY_POLL, TcpStream::connect(addr)).await,
        Ok(Ok(_))
    )
}

/// Complete once something accepts connections on `addr`.
async fn wait_listening(addr: SocketAddr) {
    let mut poll = tokio::time::interval(READY_POLL);
    loop {
        poll.tick().await;
        if is_listening(addr).await {
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config(init: PathBuf, quack_addr: &str) -> Config {
        Config {
            duckdb: "duckdb".into(),
            init,
            database: None,
            quack_addr: quack_addr.parse().unwrap(),
            ready_timeout: Duration::from_secs(30),
            stop_timeout: Duration::from_secs(30),
            restart_delay: Duration::from_secs(1),
            max_failures: 5,
        }
    }

    #[test]
    fn only_loopback_addresses_are_served() {
        let init = tempfile::NamedTempFile::new().unwrap();
        let path = init.path().to_path_buf();
        for addr in ["127.0.0.1:1294", "127.0.0.2:1294", "[::1]:1294"] {
            assert!(config(path.clone(), addr).validate().is_ok(), "{addr}");
        }
        for addr in ["0.0.0.0:1294", "[::]:1294", "192.168.1.10:1294"] {
            assert!(
                matches!(
                    config(path.clone(), addr).validate(),
                    Err(Error::NotLoopback { .. })
                ),
                "{addr}"
            );
        }
    }

    #[test]
    fn major_versions_are_parsed() {
        for (version, major) in [
            ("v2.0.1", Some(2)),
            ("v10.1.0", Some(10)),
            ("v1.5.4", Some(1)),
            ("2.0.1", None),
            ("", None),
        ] {
            assert_eq!(parse_major(version), major, "{version}");
        }
    }

    #[test]
    fn the_token_is_redacted() {
        let line = "| quack:127.0.0.1:1294 | s3cr3t |".to_string();
        let secrets = ["s3cr3t".to_string(), "1294".to_string()];
        assert_eq!(
            redact(line.clone(), &secrets),
            "| quack:127.0.0.1:[REDACTED] | [REDACTED] |"
        );
        assert_eq!(redact(line.clone(), &[]), line);
    }

    #[test]
    fn the_init_file_must_exist() {
        let dir = tempfile::tempdir().unwrap();
        for path in [dir.path().join("missing.sql"), dir.path().to_path_buf()] {
            assert!(matches!(
                config(path, "127.0.0.1:1294").validate(),
                Err(Error::InitFile { .. })
            ));
        }
    }
}