flexpool 0.2.1

The flexpool command line: check portfolios, scenarios and alarm journals, make secrets and tokens, probe a daemon.
//! `flexpool`, the command line.
//!
//! Offline tools for the files an operator keeps (portfolio, scenarios, the alarm journal), the
//! secrets and tokens the configuration needs, and a health probe. It reads files through
//! `flexpool-files` and never links the daemon: `flexpoold` serves, `flexpoold check-config`
//! checks its configuration.
//!
//! Exit codes: 0 success, 1 unhealthy or no randomness, 2 a file has problems.

use std::io::{Read as _, Write as _};
use std::net::{TcpStream, ToSocketAddrs as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use base64::Engine as _;
use clap::{Parser, Subcommand};
use sha2::{Digest as _, Sha256};

/// A file has problems.
const EXIT_PROBLEMS: u8 = 2;

/// flexpool: the open market-side virtual power plant.
#[derive(Debug, Parser)]
#[command(name = "flexpool", version, about, propagate_version = true)]
struct Args {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Probe a running daemon's /healthz.
    Health {
        /// The health URL.
        #[arg(long, default_value = "http://127.0.0.1:8080/healthz")]
        url: String,
    },
    /// Check or run a scenario file.
    Scenario {
        #[command(subcommand)]
        action: ScenarioAction,
    },
    /// Check an alarm journal or make a webhook secret.
    Alarms {
        #[command(subcommand)]
        action: AlarmsAction,
    },
    /// Check, summarise or generate a portfolio directory.
    Portfolio {
        #[command(subcommand)]
        action: PortfolioAction,
    },
    /// API tokens for remote clients.
    Token {
        #[command(subcommand)]
        action: TokenAction,
    },
    /// Print version information.
    Version,
}

#[derive(Debug, Subcommand)]
enum PortfolioAction {
    /// Validate portfolio.toml and assets.csv, listing every problem with file and line.
    Check {
        /// Portfolio directory.
        dir: PathBuf,
    },
    /// Print pools with assets, MW and MWh.
    Summary {
        /// Portfolio directory.
        dir: PathBuf,
    },
    /// Write a demo portfolio with valid (fictitious) market identifiers.
    Demo {
        /// Target directory (created).
        dir: PathBuf,
        /// Number of assets.
        #[arg(long, default_value_t = 400)]
        assets: usize,
        /// Seed.
        #[arg(long, default_value_t = 2025)]
        seed: u64,
    },
}

#[derive(Debug, Subcommand)]
enum TokenAction {
    /// Generate a token: give the token to the client, put the hash in the configuration.
    New,
}

#[derive(Debug, Subcommand)]
enum AlarmsAction {
    /// Check a journal's hash chain; names the first altered, removed or reordered line.
    Verify {
        /// Journal file (JSON Lines).
        file: PathBuf,
    },
    /// Print a new Standard Webhooks secret for paging.
    Secret,
}

#[derive(Debug, Subcommand)]
enum ScenarioAction {
    /// Validate a scenario and its data, listing every problem.
    Check {
        /// Scenario file (TOML).
        file: PathBuf,
        /// Check the scenario's faults against this portfolio directory.
        #[arg(long)]
        portfolio: Option<PathBuf>,
    },
    /// Replay a scenario to its end and print a summary (deterministic).
    Run {
        /// Scenario file (TOML).
        file: PathBuf,
    },
}

fn main() -> ExitCode {
    match Args::parse().command {
        Command::Health { url } => health(&url),
        Command::Scenario {
            action: ScenarioAction::Check { file, portfolio },
        } => scenario_check(&file, portfolio.as_deref()),
        Command::Scenario {
            action: ScenarioAction::Run { file },
        } => scenario_run(&file),
        Command::Alarms {
            action: AlarmsAction::Verify { file },
        } => alarms_verify(&file),
        Command::Alarms {
            action: AlarmsAction::Secret,
        } => alarms_secret(),
        Command::Portfolio {
            action: PortfolioAction::Check { dir },
        } => portfolio_check(&dir, false),
        Command::Portfolio {
            action: PortfolioAction::Summary { dir },
        } => portfolio_check(&dir, true),
        Command::Portfolio {
            action: PortfolioAction::Demo { dir, assets, seed },
        } => portfolio_demo(&dir, assets, seed),
        Command::Token {
            action: TokenAction::New,
        } => token_new(),
        Command::Version => {
            println!(
                "flexpool {} ({} {})",
                env!("CARGO_PKG_VERSION"),
                std::env::consts::OS,
                std::env::consts::ARCH
            );
            ExitCode::SUCCESS
        }
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

fn random<const N: usize>() -> Result<[u8; N], ExitCode> {
    let mut bytes = [0_u8; N];
    getrandom::fill(&mut bytes).map_err(|e| {
        eprintln!("✗ no randomness available: {e}");
        ExitCode::FAILURE
    })?;
    Ok(bytes)
}

fn problems(what: &Path, problems: &[String]) -> ExitCode {
    let mut err = std::io::stderr().lock();
    let _ = writeln!(err, "✗ {}: {} problem(s):", what.display(), problems.len());
    for p in problems {
        let _ = writeln!(err, "  - {p}");
    }
    ExitCode::from(EXIT_PROBLEMS)
}

/// `health`: a plain HTTP/1.1 GET with a 3-second budget; healthy is `200` with `"status":"ok"`.
fn health(url: &str) -> ExitCode {
    let Some(rest) = url.strip_prefix("http://") else {
        eprintln!("✗ only http:// URLs are supported: {url}");
        return ExitCode::FAILURE;
    };
    let (authority, path) = rest.split_once('/').map_or((rest, ""), |(a, p)| (a, p));
    let budget = Duration::from_secs(3);
    let answer = (|| -> std::io::Result<String> {
        let addr = authority
            .to_socket_addrs()?
            .next()
            .ok_or(std::io::ErrorKind::NotFound)?;
        let mut stream = TcpStream::connect_timeout(&addr, budget)?;
        stream.set_read_timeout(Some(budget))?;
        stream.set_write_timeout(Some(budget))?;
        write!(
            stream,
            "GET /{path} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n"
        )?;
        let mut body = Vec::new();
        stream.take(64 * 1024).read_to_end(&mut body)?;
        Ok(String::from_utf8_lossy(&body).into_owned())
    })();
    match answer {
        Ok(text) if text.starts_with("HTTP/1.1 200") && text.contains("\"status\":\"ok\"") => {
            println!("✓ {url} ok");
            ExitCode::SUCCESS
        }
        Ok(text) => {
            eprintln!("✗ {url}: {}", text.lines().next().unwrap_or_default());
            ExitCode::FAILURE
        }
        Err(_) => {
            eprintln!("✗ {url}: unreachable");
            ExitCode::FAILURE
        }
    }
}

/// `scenario check`: validates a scenario and its data, printing every problem.
fn scenario_check(path: &Path, portfolio_dir: Option<&Path>) -> ExitCode {
    let portfolio = match portfolio_dir
        .map(flexpool_files::load_portfolio)
        .transpose()
    {
        Ok(p) => p.map(|(p, _)| p),
        Err(ps) => return problems(portfolio_dir.unwrap_or(path), &ps),
    };
    let loaded = flexpool_files::load_scenario(path).and_then(|r| {
        // Faults are checked against a portfolio only when one is given.
        let ps = flexpool_files::fault_problems(r.scenario(), portfolio.as_ref());
        if ps.is_empty() { Ok(r) } else { Err(ps) }
    });
    let replay = match loaded {
        Ok(r) => r,
        Err(ps) => return problems(path, &ps),
    };
    let s = replay.scenario();
    let source = match &s.market {
        flexpool_sim::MarketSource::Synthetic { seed, history_days } => {
            format!("synthetic, seed {seed}, {history_days} days of history")
        }
        flexpool_sim::MarketSource::File { path } => format!("file {}", path.display()),
    };
    println!(
        "✓ {} — day {}, {source}, clock {} → {}",
        s.name,
        s.day,
        flexpool_sim::replay::berlin(s.start),
        flexpool_sim::replay::berlin(s.end)
    );
    if !s.faults.is_empty() {
        let note = if portfolio.is_some() {
            ", every asset in the portfolio"
        } else {
            " — add --portfolio DIR to check their assets"
        };
        println!("  {} fault(s){note}", s.faults.len());
    }
    ExitCode::SUCCESS
}

/// `scenario run`: replays a scenario to its end and prints the deterministic summary.
fn scenario_run(path: &Path) -> ExitCode {
    match flexpool_files::load_scenario(path) {
        Ok(r) => {
            print!("{}", r.run_to_end());
            ExitCode::SUCCESS
        }
        Err(ps) => problems(path, &ps),
    }
}

/// `portfolio check` and `summary`: validates a portfolio directory and prints its pools.
fn portfolio_check(dir: &Path, summary_only: bool) -> ExitCode {
    let (p, edge) = match flexpool_files::load_portfolio(dir) {
        Ok(loaded) => loaded,
        Err(ps) => return problems(dir, &ps),
    };
    let s = p.summary();
    let mw = |kw: flexpool_core::Kw| kw.to_mw().round_dp(1);
    let mwh = |kwh: flexpool_core::Kwh| kwh.to_mwh().round_dp(1);
    for pool in &s.pools {
        let kinds: Vec<String> = pool.kinds.iter().map(|(k, n)| format!("{n} {k}")).collect();
        println!(
            "{:<12} {:>6} assets  {:>8} MW  {:>8} MWh  {} TU, {} RG  ({})",
            pool.id.as_str(),
            pool.assets,
            mw(pool.rated_kw),
            mwh(pool.energy_kwh),
            pool.technical_units,
            pool.reserve_groups.len(),
            kinds.join(", ")
        );
    }
    println!(
        "{:<12} {:>6} assets  {:>8} MW  {:>8} MWh  {} owners",
        "total",
        s.assets,
        mw(s.rated_kw),
        mwh(s.energy_kwh),
        s.owners
    );
    if !edge.is_empty() {
        let points: usize = edge.iec104.iter().map(|s| s.points.len()).sum();
        println!(
            "edge         {} SunSpec device(s), {} IEC 104 station(s) with {points} point(s)",
            edge.sunspec.len(),
            edge.iec104.len()
        );
    }
    if !summary_only {
        println!("✓ portfolio valid");
    }
    ExitCode::SUCCESS
}

/// `portfolio demo`: writes a generated portfolio, then checks it.
fn portfolio_demo(dir: &Path, assets: usize, seed: u64) -> ExitCode {
    let (toml, csv) = flexpool_portfolio::demo::generate(assets, seed);
    let written = std::fs::create_dir_all(dir)
        .and_then(|()| std::fs::write(dir.join(flexpool_portfolio::PORTFOLIO_FILE), toml))
        .and_then(|()| std::fs::write(dir.join(flexpool_portfolio::ASSETS_FILE), csv));
    match written {
        Ok(()) => portfolio_check(dir, false),
        Err(e) => {
            eprintln!("✗ cannot write {}: {e}", dir.display());
            ExitCode::FAILURE
        }
    }
}

/// `alarms verify FILE`: checks a journal's chain; 0 with the record count, 2 naming the first broken line.
fn alarms_verify(path: &Path) -> ExitCode {
    match flexpool_files::verify_journal(path) {
        Ok(n) => {
            println!("✓ {}: {n} records, chain intact", path.display());
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("✗ {e}");
            ExitCode::from(EXIT_PROBLEMS)
        }
    }
}

/// `alarms secret`: a new Standard Webhooks secret (`whsec_` and 32 random bytes in base64).
fn alarms_secret() -> ExitCode {
    let bytes = match random::<32>() {
        Ok(b) => b,
        Err(code) => return code,
    };
    let secret = format!(
        "whsec_{}",
        base64::engine::general_purpose::STANDARD.encode(bytes)
    );
    println!(
        "secret (give to the webhook receiver, shown once):\n  {secret}\n\nconfiguration:\n  [alarms]\n  webhook_secret = \"{secret}\""
    );
    ExitCode::SUCCESS
}

/// `token new`: 32 random bytes as hex for the client; only their SHA-256 goes in the configuration.
fn token_new() -> ExitCode {
    let token = match random::<32>() {
        Ok(b) => hex(&b),
        Err(code) => return code,
    };
    println!("token (give to the client, shown once):\n  {token}\n");
    println!("configuration (only the hash is stored; separate several with commas):");
    println!(
        "  [auth]\n  token_hashes = \"{}\"",
        hex(&Sha256::digest(token.as_bytes()))
    );
    ExitCode::SUCCESS
}