troll 0.4.0

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use serde::{Deserialize, Deserializer};
use time::SignedDuration;
use troll_core::{
    Permanent, PermanentChanges, Protocol, Refused, SystemClock, edit_lease_proto,
    edit_permanent_proto,
};

use crate::{
    cli::{EditArgs, WebArgs},
    error::CliError,
    output::{self, EditOutput, LeaseEditOutput, SCHEMA, format_port},
};

use super::Context;

#[derive(Default)]
pub(crate) struct EditChanges {
    pub(crate) fields: PermanentChanges,
    pub(crate) web: WebArgs,
}

/// Field omitted keeps the current value, explicit null clears it.
pub(crate) fn deserialize_nullable_string<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Option<String>>, D::Error> {
    Option::<String>::deserialize(deserializer).map(Some)
}

impl TryFrom<EditArgs> for EditChanges {
    type Error = CliError;

    fn try_from(args: EditArgs) -> Result<Self, Self::Error> {
        if args.clear_used_by && args.used_by.is_some() {
            return Err(CliError::invalid_request(
                "used_by conflicts with clear_used_by",
            ));
        }
        if args.no_web && (args.web.web.is_some() || args.web.web_scheme.is_some()) {
            return Err(CliError::invalid_request(
                "no_web conflicts with web and web_scheme",
            ));
        }
        if args.no_component && args.component.is_some() {
            return Err(CliError::invalid_request(
                "component conflicts with no_component",
            ));
        }
        Ok(Self {
            fields: PermanentChanges {
                service: args.service,
                role: args.role.map(Into::into),
                bind: args.bind,
                used_by: if args.clear_used_by {
                    Some(Vec::new())
                } else {
                    args.used_by
                },
                container: if args.clear_container {
                    Some(None)
                } else {
                    args.container.map(Some)
                },
                web: args.no_web.then_some(None),
                component: if args.no_component {
                    Some(None)
                } else {
                    args.component.map(Some)
                },
            },
            web: args.web,
        })
    }
}

pub(crate) fn build_edit(
    context: &Context,
    port: u16,
    protocol: Protocol,
    expected_tag: Option<&str>,
    changes: EditChanges,
) -> Result<EditOutput, CliError> {
    let registry = context.store.load()?;
    let mut entries = registry
        .permanent
        .iter()
        .filter(|entry| entry.port == port && entry.protocol == protocol);
    let entry = entries.next().ok_or(Refused::NotFound { port })?;
    // Check the entire (port, protocol), including leases, before choosing a snapshot.
    if entries.next().is_some()
        || registry
            .lease
            .iter()
            .any(|entry| entry.port == port && entry.protocol == protocol)
    {
        return Err(Refused::Ambiguous { port }.into());
    }
    edit_snapshot(context, entry, expected_tag, changes)
}

pub(super) fn edit_snapshot(
    context: &Context,
    entry: &Permanent,
    expected_tag: Option<&str>,
    mut changes: EditChanges,
) -> Result<EditOutput, CliError> {
    let port = entry.port;
    let tag = entry.entry_tag();
    if expected_tag.is_some_and(|expected| expected != tag) {
        return Err(Refused::Stale { port }.into());
    }
    if let Some(web) = changes.web.apply(entry.web.as_ref()) {
        changes.fields.web = Some(Some(web));
    }
    // A change after the snapshot, including a component move, is checked by
    // the core under the registry lock before the port can be edited.
    let entry = edit_permanent_proto(&context.store, port, entry.protocol, &tag, changes.fields)?;
    Ok(EditOutput {
        schema: SCHEMA,
        claim: entry.into(),
    })
}

pub(crate) fn build_lease_edit(
    context: &Context,
    port: u16,
    protocol: Protocol,
    expected_tag: Option<&str>,
    purpose: Option<String>,
    duration: Option<SignedDuration>,
) -> Result<LeaseEditOutput, CliError> {
    let tag;
    let expected_tag = if let Some(tag) = expected_tag {
        tag
    } else {
        let registry = context.store.load()?;
        tag = registry
            .lease
            .iter()
            .find(|entry| entry.port == port && entry.protocol == protocol)
            .ok_or(Refused::NotFound { port })?
            .entry_tag();
        &tag
    };
    // A missing home is equivalent to an empty registry for reads.
    context.ensure_registry_home()?;
    let entry = edit_lease_proto(
        &context.store,
        &context.config.policy,
        &SystemClock,
        port,
        protocol,
        expected_tag,
        purpose,
        duration,
    )?;
    Ok(LeaseEditOutput {
        schema: SCHEMA,
        lease: entry.into(),
    })
}

pub(super) fn run_edit(
    context: &Context,
    port: u16,
    protocol: Protocol,
    mut args: EditArgs,
    json: bool,
) -> Result<(), CliError> {
    let tag = args.tag.take();
    print_edit(
        build_edit(context, port, protocol, tag.as_deref(), args.try_into()?)?,
        json,
    )
}

pub(super) fn print_edit(result: EditOutput, json: bool) -> Result<(), CliError> {
    output::write(json, &result, |out| {
        writeln!(
            out,
            "Edited claim on port {} (tag {}).",
            format_port(result.claim.entry.port, result.claim.entry.protocol),
            result.claim.tag
        )?;
        if let Some(link) = &result.claim.link {
            writeln!(out, "  {link}")?;
        }
        Ok(())
    })
}

pub(super) fn run_lease_edit(
    context: &Context,
    port: u16,
    protocol: Protocol,
    tag: Option<&str>,
    purpose: Option<String>,
    duration: Option<SignedDuration>,
    json: bool,
) -> Result<(), CliError> {
    let result = build_lease_edit(context, port, protocol, tag, purpose, duration)?;
    let expiry = output::timestamp(result.lease.entry.expires_at)?;
    output::write(json, &result, |out| {
        writeln!(
            out,
            "Edited lease on port {} until {expiry} (tag {}).",
            format_port(port, protocol),
            result.lease.tag
        )?;
        Ok(())
    })
}