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::{fs, io, ops::RangeInclusive, path::Path};

use troll_core::{Config, ProbeError, Store};
use troll_probe::{ClassifierConfig, SystemProbe};

use crate::{
    cli::{Color, Command, Integration},
    error::CliError,
    mcp, platform, serve, setup, wizard,
};

pub(crate) mod app;
mod doctor;
pub(crate) mod edit;
pub(crate) mod history;
mod import;
pub(crate) mod inspect;
pub(crate) mod list;
pub(crate) mod registry;
pub(crate) mod sync;
pub(crate) mod timestamp;
mod with;
pub(crate) mod zone;

pub(crate) struct Context {
    pub(crate) config: Config,
    store: Store,
    probe: SystemProbe,
    ephemeral_range: Option<RangeInclusive<u16>>,
    range_error: Option<ProbeError>,
}

impl Context {
    pub(crate) fn load() -> Result<Self, CliError> {
        Self::load_from(&platform::config_home()?, platform::proc_probe())
    }

    pub(crate) fn load_from(config_home: &Path, probe: SystemProbe) -> Result<Self, CliError> {
        let path = config_home.join("config.toml");
        let text = read_config(&path)?;
        let (range, range_error) = match probe.ephemeral_range() {
            Ok(range) => (range, None),
            Err(error) => (None, Some(error)),
        };
        let mut config = Config::parse(config_home, &text, range.clone())
            .map_err(|error| CliError::Config(path, error))?;
        if let Ok(excluded) = probe.excluded_ranges() {
            config.policy.excluded_ranges = excluded;
        }
        if let Ok(excluded_udp) = probe.excluded_udp_ranges() {
            config.policy.excluded_udp_ranges = excluded_udp;
        }
        if range_error.is_none()
            && let Some(notice) = config.app_range_notice()
        {
            eprintln!("{notice}");
        }
        let mut ctx = Self::from_config(config, probe, range_error);
        ctx.ephemeral_range = range;
        Ok(ctx)
    }

    pub(crate) fn from_config(
        config: Config,
        probe: SystemProbe,
        range_error: Option<ProbeError>,
    ) -> Self {
        let store = platform::open_store(&config.registry_home);
        Self {
            config,
            store,
            probe,
            ephemeral_range: None,
            range_error,
        }
    }

    fn load_for_allocation() -> Result<Self, CliError> {
        let context = Self::load()?;
        context.require_ephemeral_range()?;
        Ok(context)
    }

    fn require_ephemeral_range(&self) -> Result<(), CliError> {
        match &self.range_error {
            Some(error) => Err(CliError::EphemeralRange(error.clone())),
            None => Ok(()),
        }
    }

    fn probe(&self) -> Result<&SystemProbe, ProbeError> {
        platform::require_listener_probe(&self.probe)?;
        Ok(&self.probe)
    }

    fn ensure_registry_home(&self) -> Result<(), CliError> {
        let home = &self.config.registry_home;
        fs::create_dir_all(home).map_err(|error| CliError::RegistryHome(home.clone(), error))
    }

    fn classifier(&self, probe: &SystemProbe) -> Result<ClassifierConfig, ProbeError> {
        let mut classifier = ClassifierConfig::new(probe.current_uid()?);
        if let Some(roots) = &self.config.project_roots {
            classifier.project_roots.clone_from(roots);
        }
        if let Some(patterns) = &self.config.third_party {
            classifier.third_party.clone_from(patterns);
        }
        Ok(classifier)
    }
}

fn read_config(path: &Path) -> Result<String, CliError> {
    let result = match fs::symlink_metadata(path) {
        Ok(_) => fs::read_to_string(path),
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(String::new()),
        Err(error) => Err(error),
    };
    result.map_err(|error| CliError::ReadConfig(path.to_owned(), error))
}

pub fn run(command: Command, json: bool, color: Color) -> Result<i32, CliError> {
    let style = crate::style::Style::detect(crate::style::Stream::Stdout, color, json);
    match command {
        Command::Init { yes, service } => wizard::run(yes, service, json, color),
        Command::Setup { integration } => match integration {
            Integration::Claude { force } => setup::plugins::run("claude", force, json),
            Integration::Codex { force } => setup::plugins::run("codex", force, json),
            Integration::Service { force } => setup::run(force, json),
        },
        Command::Doctor => return doctor::run(json, style),
        Command::With {
            project,
            purpose,
            command,
        } => {
            return with::run(
                &Context::load_for_allocation()?,
                project,
                purpose,
                &command,
                json,
            );
        }
        Command::ImportLegacy { dir, apply, .. } => {
            return import::run(&Context::load()?, &dir, apply, json);
        }
        Command::Serve { port, bind } => serve::run(port, bind, json),
        Command::Mcp => mcp::run(),
        Command::List {
            drift: true,
            kind,
            role,
            proto,
            include_ephemeral_udp,
        } => list::run(
            &Context::load()?,
            kind.map(Into::into),
            role.map(Into::into),
            proto.into_option(),
            include_ephemeral_udp,
            json,
            style,
        ),
        Command::Claim(args) => registry::claim(&Context::load()?, args, json),
        Command::Edit {
            port,
            proto,
            changes,
        } => edit::run_edit(&Context::load()?, port, proto.into(), changes, json),
        Command::Lease { args, group } => registry::lease(&Context::load()?, args, group, json),
        Command::LeaseEdit {
            port,
            proto,
            tag,
            purpose,
            duration,
        } => edit::run_lease_edit(
            &Context::load()?,
            port,
            proto.into(),
            tag.as_deref(),
            purpose,
            duration,
            json,
        ),
        Command::Renew { target, duration } => {
            registry::renew(&Context::load()?, target, duration, json)
        }
        Command::Release {
            target,
            force_shared,
        } => registry::release(&Context::load()?, target, force_shared, json),
        Command::History { action } => history::run(&Context::load()?, action, json, style),
        Command::Zone { action } => zone::run(&Context::load()?, action, json),
        Command::App { action } => app::run(&Context::load()?, action, json),
        Command::Env { app, write } => app::env(&Context::load()?, &app, write.as_deref(), json),
        Command::Sync {
            file,
            dry_run,
            write_env,
        } => sync::run(
            &Context::load()?,
            &file,
            dry_run,
            write_env.as_deref(),
            json,
        ),
        Command::Check { port, proto } => {
            inspect::check(&Context::load()?, port, proto.into(), json, style)
        }
        Command::Explain { port, proto } => {
            inspect::explain(&Context::load()?, port, proto.into(), json, style)
        }
        Command::List {
            kind,
            role,
            proto,
            include_ephemeral_udp,
            drift: false,
        } => inspect::list(
            &Context::load()?,
            kind.map(Into::into),
            role.map(Into::into),
            proto.into_option(),
            include_ephemeral_udp,
            json,
            style,
        ),
        Command::Sweep { dry_run } => registry::sweep(&Context::load()?, dry_run, json),
    }?;
    Ok(0)
}

#[cfg(test)]
mod tests {
    use troll_core::{StoreError, UpdateError, Zone};

    use crate::test_support::TempDir;

    use super::*;

    #[test]
    fn invalid_registry_update_stays_invalid_after_repair() {
        let home = TempDir::new();
        let config = Config::parse(home.path(), "", None).unwrap();
        let context = Context::from_config(config, platform::proc_probe(), None);
        let path = home.path().join("registry.toml");
        fs::write(
            &path,
            "schema = 2\n[[zone]]\nlabel = 'broken'\nports = []\nenabled = true\n",
        )
        .unwrap();
        let result = troll_core::add_zone(
            &context.store,
            Zone {
                label: "development".into(),
                reason: None,
                ports: vec!["8123".into()],
                protocol: None,
                enabled: true,
            },
        );
        assert!(matches!(
            &result,
            Err(UpdateError::Store(StoreError::Invalid { .. }))
        ));

        // Repair the registry after the update failed but before mapping its error.
        fs::write(&path, "schema = 2\n").unwrap();
        assert!(context.store.load().unwrap().zone.is_empty());
        let error = CliError::from(result.unwrap_err());
        assert_eq!(error.kind_and_code(), ("InvalidRegistry", 1));
        let canonical_path = fs::canonicalize(&path).unwrap();
        assert!(
            matches!(error, CliError::Store(StoreError::Invalid { path: reported, .. }) if reported == canonical_path)
        );
    }
}