troll 0.3.1

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

use troll_core::{AppRequest, Permanent, Refused, Registry, SystemClock, parse_component_spec};

use crate::{
    cli::{AppAllocationArgs, AppCommand},
    error::CliError,
    output::{
        self, AppAllocationOutput, AppEntries, AppListOutput, AppOutput, EditOutput, EnvOutput,
        SCHEMA, TaggedPermanent,
    },
};

use super::{
    Context,
    edit::{self, EditChanges},
    inspect::allocation_snapshot,
    registry::holder,
};

pub(crate) fn build_app_reserve(
    context: &Context,
    args: AppAllocationArgs,
) -> Result<AppAllocationOutput, CliError> {
    build_allocation(context, args, true)
}

pub(crate) fn build_app_add(
    context: &Context,
    args: AppAllocationArgs,
) -> Result<AppAllocationOutput, CliError> {
    build_allocation(context, args, false)
}

fn build_allocation(
    context: &Context,
    args: AppAllocationArgs,
    reserve: bool,
) -> Result<AppAllocationOutput, CliError> {
    let mut components = args
        .components
        .iter()
        .map(|spec| parse_component_spec(spec))
        .collect::<Result<Vec<_>, _>>()?;
    for pin in &args.pins {
        let (name, port) = pin
            .split_once('=')
            .and_then(|(name, port)| {
                port.parse::<NonZeroU16>()
                    .ok()
                    .map(|port| (name, port.get()))
            })
            .ok_or_else(|| {
                CliError::invalid_request(format!(
                    "invalid port pin {pin:?}, expected COMPONENT=PORT"
                ))
            })?;
        let component = components
            .iter_mut()
            .find(|component| component.name == name)
            .ok_or_else(|| {
                CliError::invalid_request(format!("port pin {pin:?} names an unlisted component"))
            })?;
        if component.pinned_port.replace(port).is_some() {
            return Err(CliError::invalid_request(format!(
                "component {name:?} has more than one port pin"
            )));
        }
    }
    context.require_ephemeral_range()?;
    let probe = context.probe()?;
    context.ensure_registry_home()?;
    let request = AppRequest {
        app: args.app.clone(),
        claimed_by: holder(),
        bind: args.bind,
        components,
    };
    let allocate = if reserve {
        troll_core::reserve_app
    } else {
        troll_core::add_components
    };
    let result = allocate(
        &context.store,
        &context.config.policy,
        &|| allocation_snapshot(probe),
        &SystemClock,
        request,
    )?;
    Ok(AppAllocationOutput {
        schema: SCHEMA,
        app: app_entries(args.app, result.entries, false),
        contiguous: result.contiguous,
    })
}

pub(crate) fn build_app_list(context: &Context) -> Result<AppListOutput, CliError> {
    let registry = context.store.load()?;
    let apps = registry
        .apps()
        .into_iter()
        .map(|(app, entries)| app_entries(app, entries.into_iter().cloned(), true))
        .collect();
    Ok(AppListOutput {
        schema: SCHEMA,
        apps,
    })
}

pub(crate) fn build_app_show(context: &Context, app: &str) -> Result<AppOutput, CliError> {
    let registry = context.store.load()?;
    let entries = registry.app(app).ok_or_else(|| app_not_found(app))?;
    Ok(AppOutput {
        schema: SCHEMA,
        app: app_entries(app, entries.into_iter().cloned(), true),
    })
}

pub(crate) fn build_app_remove(
    context: &Context,
    app: &str,
    component: &str,
    force_shared: bool,
    expected_tag: Option<&str>,
) -> Result<AppOutput, CliError> {
    context.ensure_registry_home()?;
    let entry =
        troll_core::remove_component(&context.store, app, component, force_shared, expected_tag)?;
    Ok(AppOutput {
        schema: SCHEMA,
        app: app_entries(app, [entry], false),
    })
}

pub(crate) fn build_app_edit(
    context: &Context,
    app: &str,
    component: &str,
    expected_tag: Option<&str>,
    changes: EditChanges,
) -> Result<EditOutput, CliError> {
    let registry = context.store.load()?;
    let entries = registry.app(app).ok_or_else(|| app_not_found(app))?;
    let entry = entries
        .into_iter()
        .find(|entry| entry.component.as_deref() == Some(component))
        .ok_or_else(|| Refused::ComponentNotFound {
            app: app.into(),
            component: component.into(),
        })?;
    edit::edit_snapshot(context, entry, expected_tag, changes)
}

pub(crate) fn build_app_release(
    context: &Context,
    app: &str,
    confirm: &str,
    expected_tag: Option<&str>,
) -> Result<AppOutput, CliError> {
    context.ensure_registry_home()?;
    let entries = troll_core::release_app(&context.store, app, confirm, expected_tag)?;
    Ok(AppOutput {
        schema: SCHEMA,
        app: app_entries(app, entries, false),
    })
}

pub(crate) fn build_env(context: &Context, app: &str) -> Result<EnvOutput, CliError> {
    let registry = context.store.load()?;
    let env = registry.app_env(app).ok_or_else(|| app_not_found(app))?;
    Ok(EnvOutput {
        schema: SCHEMA,
        variables: env.variables,
        unlabeled: env.unlabeled.iter().map(|entry| entry.port).collect(),
    })
}

fn app_not_found(app: &str) -> Refused {
    Refused::AppNotFound { app: app.into() }
}

fn app_entries(
    app: impl Into<String>,
    entries: impl IntoIterator<Item = Permanent>,
    include_tag: bool,
) -> AppEntries {
    let entries: Vec<TaggedPermanent> = entries.into_iter().map(Into::into).collect();
    let tag =
        include_tag.then(|| Registry::app_tag(entries.iter().map(|claim| claim.tag.as_str())));
    AppEntries {
        app: app.into(),
        tag,
        entries,
    }
}

pub(super) fn run(context: &Context, action: AppCommand, json: bool) -> Result<(), CliError> {
    match action {
        AppCommand::Reserve(args) => print_allocation(build_app_reserve(context, args)?, json),
        AppCommand::Add(args) => print_allocation(build_app_add(context, args)?, json),
        AppCommand::List => {
            let result = build_app_list(context)?;
            output::write(json, &result, |out| {
                if result.apps.is_empty() {
                    writeln!(out, "No apps.")?;
                }
                for app in &result.apps {
                    print_app(out, app)?;
                }
                Ok(())
            })
        }
        AppCommand::Show { app } => print_result(build_app_show(context, &app)?, "", json),
        AppCommand::Remove {
            app,
            component,
            force_shared,
            if_tag,
        } => print_result(
            build_app_remove(context, &app, &component, force_shared, if_tag.as_deref())?,
            "Removed from ",
            json,
        ),
        AppCommand::Edit {
            app,
            component,
            mut changes,
        } => {
            let tag = changes.tag.take();
            edit::print_edit(
                build_app_edit(
                    context,
                    &app,
                    &component,
                    tag.as_deref(),
                    changes.try_into()?,
                )?,
                json,
            )
        }
        AppCommand::Release {
            app,
            confirm,
            if_tag,
        } => print_result(
            build_app_release(context, &app, &confirm, if_tag.as_deref())?,
            "Released ",
            json,
        ),
    }
}

pub(super) fn env(context: &Context, app: &str, json: bool) -> Result<(), CliError> {
    let result = build_env(context, app)?;
    for port in &result.unlabeled {
        writeln!(
            io::stderr().lock(),
            "App {app:?} port {port} has no component label."
        )?;
    }
    output::write(json, &result, |out| {
        for (name, port) in &result.variables {
            writeln!(out, "{name}={port}")?;
        }
        Ok(())
    })
}

fn print_allocation(result: AppAllocationOutput, json: bool) -> Result<(), CliError> {
    output::write(json, &result, |out| {
        print_app(out, &result.app)?;
        let layout = if result.contiguous {
            "contiguous"
        } else {
            "non-contiguous"
        };
        writeln!(out, "Automatically allocated ports: {layout}.")?;
        Ok(())
    })
}

fn print_result(result: AppOutput, prefix: &str, json: bool) -> Result<(), CliError> {
    output::write(json, &result, |out| {
        write!(out, "{prefix}")?;
        print_app(out, &result.app)
    })
}

fn print_app(out: &mut dyn Write, app: &AppEntries) -> Result<(), CliError> {
    write!(out, "App {}", app.app)?;
    if let Some(tag) = &app.tag {
        write!(out, " (tag {tag})")?;
    }
    writeln!(out)?;
    for claim in &app.entries {
        let entry = &claim.entry;
        let component = entry.component.as_deref().unwrap_or("(unlabeled)");
        let role = match entry.role {
            troll_core::Role::App => "app",
            troll_core::Role::Service => "service",
        };
        write!(
            out,
            "  {}  {component}  {role}  {}  {}  tag {}",
            entry.port, entry.bind, entry.service, claim.tag
        )?;
        if let Some(link) = &claim.link {
            write!(out, "  {link}")?;
        }
        writeln!(out)?;
    }
    Ok(())
}