hazine 0.2.8

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! Running SQL on the lake from the imports (`hazine openalex`, `hazine
//! ror`): DuckDB as the service account, with the settings `hazine setup`
//! wrote, and reading what it prints.

use std::path::Path;

use crate::Error;
use crate::setup::{self, ETC, render};

/// The main database of hazine serve: the lake.
const LAKE: &str = render::DATABASE;

/// Makes the DuckDB CLI print results as CSV without headers. (`COPY TO
/// '/dev/stdout'` would not do: DuckDB runs as the service account and may
/// not reopen a pipe root created.)
pub(crate) const CSV: &str = ".mode csv\n.headers off\n";

/// The `CREATE SECRET hazine_data (...);` statement in `init.sql`, which
/// gives DuckDB the lake's object storage (the keys come from the env).
pub fn data_secret(init_sql: &str) -> Result<String, Error> {
    let start = init_sql
        .find("CREATE SECRET hazine_data (")
        .ok_or_else(|| Error::InvalidSetting {
            name: "init.sql",
            reason: "has no CREATE SECRET hazine_data; rerun hazine setup".into(),
        })?;
    let rest = &init_sql[start..];
    let end = rest.find(");").ok_or_else(|| Error::InvalidSetting {
        name: "init.sql",
        reason: "CREATE SECRET hazine_data does not end".into(),
    })?;
    Ok(rest[..end + 2].to_string())
}

/// The data secret of the installed `init.sql`.
pub(crate) fn installed_data_secret() -> Result<String, Error> {
    data_secret(&std::fs::read_to_string(Path::new(ETC).join("init.sql"))?)
}

/// Whether the installed data secret uses TLS (`USE_SSL false` turns it
/// off, as `hazine setup --s3-use-ssl false` writes it).
pub(crate) fn installed_use_ssl() -> Result<bool, Error> {
    Ok(!uses_plain_http(&installed_data_secret()?))
}

fn uses_plain_http(secret: &str) -> bool {
    secret.lines().any(|line| {
        line.trim()
            .trim_end_matches(',')
            .eq_ignore_ascii_case("USE_SSL false")
    })
}

/// What an import's DuckDB (and its converter) may use.
#[derive(Debug, Clone)]
pub struct Limits {
    pub threads: usize,
    /// e.g. `37GB`
    pub memory_limit: String,
}

impl Limits {
    /// As given, or half the CPUs and a fifth of RAM, so hazine serve and
    /// the rest of the host keep running.
    pub(crate) fn new(threads: Option<usize>, memory_limit: Option<String>) -> Result<Self, Error> {
        let threads = Self::threads(threads)?;
        let memory_limit = match memory_limit {
            Some(limit) => limit,
            None => format!("{}GB", (setup::memory_gb()? / 5).max(1)),
        };
        Ok(Limits {
            threads,
            memory_limit,
        })
    }

    /// Threads as given, or half the CPUs.
    pub(crate) fn threads(threads: Option<usize>) -> Result<usize, Error> {
        Ok(match threads {
            Some(threads) => threads.max(1),
            None => (std::thread::available_parallelism()?.get() / 2).max(1),
        })
    }
}

/// `name,value` lines of output, other lines ignored.
pub(crate) fn pairs(output: &str) -> Vec<(String, String)> {
    output
        .lines()
        .filter_map(|line| line.trim().split_once(','))
        .filter(|(a, b)| is_identifier(a) && !b.is_empty() && !b.contains(','))
        .map(|(a, b)| (a.to_string(), b.to_string()))
        .collect()
}

/// Lowercase letters, digits and `_`.
pub(crate) fn is_identifier(value: &str) -> bool {
    !value.is_empty()
        && value
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// The last line of output that is a number: what `SELECT count(*)`
/// printed.
pub(crate) fn last_count(output: &str) -> Option<u64> {
    output
        .lines()
        .rev()
        .find_map(|line| line.trim().parse().ok())
}

/// How DuckDB runs: as the service account on the lake, with the env file's
/// variables; or, for a dry run, as whoever runs hazine, without the lake.
pub(crate) enum Runner {
    Service {
        account: setup::Account,
        env: Vec<(String, String)>,
    },
    Local,
}

impl Runner {
    /// For real runs: as root on Linux, with the configuration `hazine
    /// setup` wrote. `linux_only` is the error off Linux.
    pub(crate) fn service(linux_only: &'static str) -> Result<Self, Error> {
        if !cfg!(target_os = "linux") {
            return Err(Error::Unsupported(linux_only));
        }
        if setup::effective_uid()? != 0 {
            return Err(Error::NotRoot);
        }
        let env = setup::read_env(&Path::new(ETC).join("hazine.env"), false)?;
        if env.is_empty() {
            return Err(Error::InvalidSetting {
                name: "hazine.env",
                reason: format!("{ETC}/hazine.env is missing; run hazine setup first"),
            });
        }
        Ok(Runner::Service {
            account: setup::service_account()?,
            env: env.into_iter().collect(),
        })
    }

    /// The service account DuckDB runs as; none for local runs.
    pub(crate) fn account(&self) -> Option<&setup::Account> {
        match self {
            Runner::Service { account, .. } => Some(account),
            Runner::Local => None,
        }
    }

    /// A variable of `hazine.env`; none for local runs.
    pub(crate) fn env(&self, name: &str) -> Option<&str> {
        match self {
            Runner::Service { env, .. } => env
                .iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.as_str()),
            Runner::Local => None,
        }
    }

    /// Run `sql`, on the lake if `lake`; returns stdout.
    pub(crate) fn run(&self, lake: bool, sql: &str) -> Result<String, Error> {
        match self {
            Runner::Service { account, env } => {
                setup::duckdb_on(account, lake.then_some(LAKE), sql, env)
            }
            Runner::Local => {
                let duckdb = if Path::new(setup::DUCKDB_BIN).exists() {
                    setup::DUCKDB_BIN
                } else {
                    "duckdb"
                };
                // SQL on stdin, not -c: it starts with dot commands.
                let mut child = std::process::Command::new(duckdb)
                    .args(["-no-agent", "-batch", "-bail", "-init", "/dev/null"])
                    .stdin(std::process::Stdio::piped())
                    .stdout(std::process::Stdio::piped())
                    .stderr(std::process::Stdio::piped())
                    .spawn()
                    .map_err(|source| Error::Spawn {
                        program: duckdb.into(),
                        source,
                    })?;
                if let Some(mut stdin) = child.stdin.take() {
                    use std::io::Write;
                    stdin.write_all(sql.as_bytes())?;
                }
                let output = child.wait_with_output()?;
                if output.status.success() {
                    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
                } else {
                    Err(Error::Command {
                        program: duckdb.into(),
                        status: output.status.to_string(),
                        detail: String::from_utf8_lossy(&output.stderr).trim().into(),
                    })
                }
            }
        }
    }
}

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

    #[test]
    fn the_data_secret_comes_from_init_sql() {
        let init = "LOAD httpfs;\n\nCREATE SECRET hazine_data (\n    TYPE s3,\n    \
                    SCOPE 's3://lake'\n);\n\nSELECT 1;\n";
        assert_eq!(
            data_secret(init).unwrap(),
            "CREATE SECRET hazine_data (\n    TYPE s3,\n    SCOPE 's3://lake'\n);"
        );
        assert!(data_secret("SELECT 1;").is_err());
    }

    #[test]
    fn plain_http_is_read_from_the_secret() {
        assert!(uses_plain_http("CREATE SECRET x (\n    USE_SSL false\n);"));
        assert!(!uses_plain_http("CREATE SECRET x (\n    USE_SSL true\n);"));
        assert!(!uses_plain_http("CREATE SECRET x (TYPE s3);"));
    }

    #[test]
    fn counts_and_pairs_are_parsed_from_output() {
        assert_eq!(last_count("│ true │\n42\n"), Some(42));
        assert_eq!(last_count("nothing"), None);
        assert_eq!(
            pairs("a_1,x\nBad,y\nb,\nc,d,e\n│ junk │\n"),
            [("a_1".to_string(), "x".to_string())]
        );
    }
}