haematite-cli 0.21.7

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
Documentation
//! The foreground door and its read-only configuration check share one loader.

use std::io::Read;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Instant;

use super::config::Config;
use super::listen::serve;
use super::lys::LysSignIn;
use super::signin::Door;

const CONFIG_BYTES: u64 = 1_048_576;
const USAGE: &str = "usage: haematite door [--check] --config <absolute door.json>";

/// Run the door command, reporting check refusals with exit 78.
pub fn dispatch(args: impl Iterator<Item = String>) -> ExitCode {
    let started = Instant::now();
    let (path, checking) = match arguments(args) {
        Ok(arguments) => arguments,
        Err(message) => {
            eprintln!("{message}");
            return ExitCode::FAILURE;
        }
    };
    match run_config(&path, checking, started) {
        Ok(()) => ExitCode::SUCCESS,
        Err(message) => {
            eprintln!("{message}");
            if checking {
                ExitCode::from(78)
            } else {
                ExitCode::FAILURE
            }
        }
    }
}

/// Check the configuration or run the door until its listener stops accepting.
///
/// # Errors
///
/// The usage, or the named reason the door could not check or start.
pub fn run(args: impl Iterator<Item = String>) -> Result<(), String> {
    let started = Instant::now();
    let (path, checking) = arguments(args)?;
    run_config(&path, checking, started)
}

fn run_config(path: &Path, checking: bool, started: Instant) -> Result<(), String> {
    let config = load(path, checking)?;
    if checking {
        super::check::configuration(&config)?;
        println!(
            "door_check_ok: {} children, {} stores",
            config.children.len(),
            config.stores.len()
        );
        return Ok(());
    }
    let issuer = LysSignIn::connect(&config.lys)?;
    let door = Arc::new(Door::new(issuer));
    let assistant = super::assistant_socket::Listener::start(&door, &config)
        .map_err(|error| format!("{}: {}", error.code, error.message))?;
    let children = super::children::Children::start(&config.children)?;
    let site = Arc::new(config.site());
    let limits = config.limits();
    let listener = TcpListener::bind(config.listen)
        .map_err(|error| format!("the door could not listen on {}: {error}", config.listen))?;
    eprintln!(
        "haematite door: listening on {} for {} elapsed_ms={}",
        config.listen,
        config.origin,
        started.elapsed().as_millis()
    );
    serve(&listener, &door, &site, &limits);
    drop(assistant);
    drop(children);
    Ok(())
}

fn arguments(mut args: impl Iterator<Item = String>) -> Result<(PathBuf, bool), String> {
    let mut checking = false;
    let mut path = None;
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--check" if !checking => checking = true,
            "--config" if path.is_none() => path = Some(PathBuf::from(args.next().ok_or(USAGE)?)),
            _ => return Err(USAGE.to_owned()),
        }
    }
    let path = path.ok_or(USAGE)?;
    if !path.is_absolute() {
        return Err(USAGE.to_owned());
    }
    Ok((path, checking))
}

fn load(path: &Path, checking: bool) -> Result<Config, String> {
    let file = super::config_upgrade::open_source(path)?;
    let mut bytes = Vec::new();
    file.take(CONFIG_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| format!("the door configuration could not be read: {error}"))?;
    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > CONFIG_BYTES {
        return Err("the door configuration exceeds its byte limit".to_owned());
    }
    let plan = super::config_upgrade::plan(path, &bytes)?;
    if checking {
        super::config_upgrade::check_apply(path, &plan)?;
    } else {
        super::config_upgrade::apply(path, &bytes, &plan)?;
    }
    let config = Config::parse(&plan.bytes)?;
    if checking && !plan.names.is_empty() {
        println!(
            "door_config_upgrade_needed: give_up_after=3 for {}",
            plan.names.join(", ")
        );
    }
    Ok(config)
}