chyabrung-cli 0.2.5

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy down` / `chy up`: maintenance mode.

use crate::util::{config, ok, CliResult};
use base64::Engine;
use chyabrung_core::maintenance::{self, DownState, DEFAULT_FILE};
use rand::RngCore;
use std::path::Path;

/// Options for `chy down`.
pub struct DownOptions {
    pub message: Option<String>,
    pub retry: Option<u64>,
    pub secret: Option<String>,
    pub no_secret: bool,
    pub allow: Vec<String>,
}

fn random_secret() -> String {
    let mut b = [0u8; 18];
    rand::thread_rng().fill_bytes(&mut b);
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
}

/// `chy down`
pub fn down(o: DownOptions) -> CliResult {
    for ip in &o.allow {
        ip.parse::<std::net::IpAddr>().map_err(|_| format!("--allow {ip}: not an IP address"))?;
    }
    let secret = if o.no_secret {
        None
    } else {
        let s = o.secret.unwrap_or_else(random_secret);
        let s = s.trim_matches('/').to_string();
        if s.is_empty() || s.contains('/') || !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
            return Err("--secret may only contain letters, digits, `-` and `_`".into());
        }
        Some(s)
    };
    let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
    let state = DownState { message: o.message, retry: o.retry, secret: secret.clone(), allow: o.allow, since };
    maintenance::down(Path::new(DEFAULT_FILE), &state).map_err(|e| format!("cannot write {DEFAULT_FILE}: {e}"))?;

    ok("the app is now in maintenance mode (503 \"back soon\" page)");
    if let Some(s) = secret {
        let cfg = config();
        let app = cfg.get("app");
        let _ = dotenvy::dotenv();
        let host = app.and_then(|a| a.get("host")).and_then(|h| h.as_str()).map(chyabrung_core::config::interpolate);
        let host = host.filter(|h| !h.is_empty() && h != "0.0.0.0").unwrap_or_else(|| "127.0.0.1".into());
        let port = app.and_then(|a| a.get("port")).and_then(|p| p.as_integer()).unwrap_or(2007);
        println!("  bypass: open /{s} once (e.g. http://{host}:{port}/{s}) to use the site normally");
    }
    if !state.allow.is_empty() {
        println!("  allowed IPs: {}", state.allow.join(", "));
    }
    println!("  apps built with App::new() pick this up within a second; `chy up` ends it");
    if !Path::new("Cargo.toml").exists() {
        println!("  note: run this in the app's folder (where the server runs), so it finds {DEFAULT_FILE}");
    }
    Ok(())
}

/// `chy up`
pub fn up() -> CliResult {
    if maintenance::up(Path::new(DEFAULT_FILE)).map_err(|e| format!("cannot remove {DEFAULT_FILE}: {e}"))? {
        ok("the app is live again");
    } else {
        ok("the app was not in maintenance mode");
    }
    Ok(())
}