troll 0.4.0

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::io::Write;

use serde::Serialize;
use troll_core::{
    HISTORY_RETENTION_DAYS, HistoryEntry, HistoryKind, HistoryReason, Refused, Restored,
    SystemClock,
};

use crate::{
    cli::HistoryCommand,
    error::CliError,
    output::{self, SCHEMA, TaggedLease, TaggedPermanent},
    style::{Cell, Style, Table, display},
};

use super::Context;

#[derive(Serialize)]
pub(crate) struct HistoryListOutput {
    pub schema: u32,
    pub retention_days: i64,
    pub entries: Vec<HistoryEntry>,
}

#[derive(Serialize)]
pub(crate) struct HistoryShowOutput {
    pub schema: u32,
    pub entry: HistoryEntry,
}

#[derive(Serialize)]
#[serde(tag = "tier", rename_all = "lowercase")]
pub(crate) enum RestoredEntries {
    Permanent { entries: Vec<TaggedPermanent> },
    Lease { entries: Vec<TaggedLease> },
}

#[derive(Serialize)]
pub(crate) struct HistoryRestoreOutput {
    pub schema: u32,
    pub history_id: String,
    pub project: String,
    pub kind: HistoryKind,
    #[serde(flatten)]
    pub restored: RestoredEntries,
}

pub(crate) fn build_history_list(context: &Context) -> Result<HistoryListOutput, CliError> {
    let entries = troll_core::list_history(&context.store, &SystemClock)?;
    Ok(HistoryListOutput {
        schema: SCHEMA,
        retention_days: HISTORY_RETENTION_DAYS,
        entries,
    })
}

pub(crate) fn build_history_show(
    context: &Context,
    id: &str,
) -> Result<HistoryShowOutput, CliError> {
    let entry = troll_core::show_history(&context.store, &SystemClock, id)?
        .ok_or_else(|| Refused::HistoryNotFound { id: id.to_owned() })?;
    Ok(HistoryShowOutput {
        schema: SCHEMA,
        entry,
    })
}

pub(crate) fn build_history_restore(
    context: &Context,
    id: &str,
) -> Result<HistoryRestoreOutput, CliError> {
    context.ensure_registry_home()?;
    let (record, restored) =
        troll_core::restore_history(&context.store, &context.config.policy, &SystemClock, id)?;
    let restored = match restored {
        Restored::Permanent(entries) => RestoredEntries::Permanent {
            entries: entries.into_iter().map(Into::into).collect(),
        },
        Restored::Lease(entries) => RestoredEntries::Lease {
            entries: entries.into_iter().map(Into::into).collect(),
        },
    };
    Ok(HistoryRestoreOutput {
        schema: SCHEMA,
        history_id: record.id,
        project: record.project,
        kind: record.kind,
        restored,
    })
}

pub(super) fn run(
    context: &Context,
    action: Option<HistoryCommand>,
    json: bool,
    style: Style,
) -> Result<(), CliError> {
    match action.unwrap_or(HistoryCommand::List) {
        HistoryCommand::List => {
            let result = build_history_list(context)?;
            output::write(json, &result, |out| write_list(out, &result, style))
        }
        HistoryCommand::Show { id } => {
            let result = build_history_show(context, &id)?;
            output::write(json, &result, |out| write_entry(out, &result.entry, style))
        }
        HistoryCommand::Restore { id } => {
            let result = build_history_restore(context, &id)?;
            output::write(json, &result, |out| write_restore(out, &result, style))
        }
    }
}

fn kind_label(kind: HistoryKind) -> &'static str {
    match kind {
        HistoryKind::Claim => "claim",
        HistoryKind::Component => "component",
        HistoryKind::App => "app",
        HistoryKind::Lease => "lease",
        HistoryKind::LeaseGroup => "stack",
    }
}

fn reason_label(reason: HistoryReason) -> &'static str {
    match reason {
        HistoryReason::Released => "released",
        HistoryReason::ComponentRemoved => "component removed",
        HistoryReason::AppReleased => "app released",
        HistoryReason::GroupReleased => "stack released",
        HistoryReason::Swept => "swept",
    }
}

fn ports_summary(entry: &HistoryEntry) -> String {
    let mut ports: Vec<String> = entry
        .permanent
        .iter()
        .map(|claim| match &claim.component {
            Some(component) => format!("{} ({component})", claim.port),
            None => claim.port.to_string(),
        })
        .chain(entry.lease.iter().map(|lease| match &lease.component {
            Some(component) => format!("{} ({component})", lease.port),
            None => lease.port.to_string(),
        }))
        .collect();
    if ports.is_empty() {
        ports.push("-".into());
    }
    ports.join(", ")
}

fn write_list(
    out: &mut dyn Write,
    result: &HistoryListOutput,
    style: Style,
) -> Result<(), CliError> {
    if result.entries.is_empty() {
        writeln!(
            out,
            "No removed apps or ports in the last {} days.",
            result.retention_days
        )?;
        return Ok(());
    }
    if style.is_human() {
        writeln!(
            out,
            "{}",
            style.heading(&format!(
                "Removal history (last {} days)",
                result.retention_days
            ))
        )?;
        let mut table = Table::new(&["ID", "KIND", "PROJECT", "PORTS", "REASON", "REMOVED AT"]);
        for entry in &result.entries {
            let removed = output::timestamp(entry.removed_at)?;
            let ports = ports_summary(entry);
            table.row(vec![
                Cell::styled(&entry.id, style.accent(&entry.id)),
                Cell::plain(kind_label(entry.kind)),
                Cell::plain(display(&entry.project)),
                Cell::styled(&ports, style.accent(&ports)),
                Cell::styled(
                    reason_label(entry.reason),
                    style.dim(reason_label(entry.reason)),
                ),
                Cell::styled(&removed, style.dim(&removed)),
            ]);
        }
        write!(out, "{}", table.render(style, ""))?;
        writeln!(
            out,
            "{}",
            style.dim("Restore any entry with: troll history restore <ID>")
        )?;
    } else {
        writeln!(
            out,
            "ID              KIND       PROJECT           PORTS  REASON  REMOVED AT"
        )?;
        for entry in &result.entries {
            let removed = output::timestamp(entry.removed_at)?;
            writeln!(
                out,
                "{:<14}  {:<9}  {:<16}  {}  {}  {}",
                entry.id,
                kind_label(entry.kind),
                display(&entry.project),
                ports_summary(entry),
                reason_label(entry.reason),
                removed
            )?;
        }
    }
    Ok(())
}

fn write_entry(out: &mut dyn Write, entry: &HistoryEntry, style: Style) -> Result<(), CliError> {
    let removed = output::timestamp(entry.removed_at)?;
    let expires = output::timestamp(entry.expires_at)?;
    writeln!(
        out,
        "{} {} ({}) — {}",
        style.accent(&entry.id),
        display(&entry.project),
        kind_label(entry.kind),
        reason_label(entry.reason)
    )?;
    writeln!(out, "  Removed: {removed}")?;
    writeln!(out, "  Restorable until: {expires}")?;
    for claim in &entry.permanent {
        writeln!(
            out,
            "  Permanent port {} ({}) — {}",
            style.accent(&claim.port.to_string()),
            claim.bind,
            display(&claim.service)
        )?;
    }
    for lease in &entry.lease {
        writeln!(
            out,
            "  Lease port {} ({}) — {}",
            style.accent(&lease.port.to_string()),
            lease.bind,
            display(&lease.purpose)
        )?;
    }
    Ok(())
}

fn write_restore(
    out: &mut dyn Write,
    result: &HistoryRestoreOutput,
    style: Style,
) -> Result<(), CliError> {
    let count = match &result.restored {
        RestoredEntries::Permanent { entries } => entries.len(),
        RestoredEntries::Lease { entries } => entries.len(),
    };
    writeln!(
        out,
        "Restored {} ({}) for {} ({} {}).",
        style.accent(&result.history_id),
        kind_label(result.kind),
        display(&result.project),
        count,
        if count == 1 { "port" } else { "ports" }
    )?;
    match &result.restored {
        RestoredEntries::Permanent { entries } => {
            for claim in entries {
                writeln!(
                    out,
                    "  {}  {}  {}",
                    style.accent(&claim.entry.port.to_string()),
                    claim.entry.bind,
                    display(&claim.entry.service)
                )?;
            }
        }
        RestoredEntries::Lease { entries } => {
            for lease in entries {
                let expiry = output::timestamp(lease.entry.expires_at)?;
                writeln!(
                    out,
                    "  {}  {}  until {expiry}",
                    style.accent(&lease.entry.port.to_string()),
                    lease.entry.bind
                )?;
            }
        }
    }
    Ok(())
}