troll 0.3.2

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{
    fs, io,
    path::{Component, Path, PathBuf},
    process,
};

use serde::{Deserialize, Serialize};
use troll_core::ProbeError;
use troll_probe::SystemProbe;

use crate::{output::SCHEMA, platform};

pub(crate) const FILE_NAME: &str = "serve.status";

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ServiceStatus {
    schema: u32,
    pid: u32,
    start_time: u64,
    boot_id: String,
    port: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    registry_home: Option<PathBuf>,
}

impl ServiceStatus {
    pub(crate) fn read(path: &Path) -> io::Result<Option<Self>> {
        // Avoid opening a special file, such as a FIFO left at this path.
        let metadata = match fs::symlink_metadata(path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        if !metadata.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "expected a regular file",
            ));
        }
        let contents = match fs::read(path) {
            Ok(contents) => contents,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let value: serde_json::Value =
            serde_json::from_slice(&contents).map_err(io::Error::other)?;
        if !value.is_object() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "expected a JSON object",
            ));
        }
        // Decode the original bytes so Serde can still reject duplicate fields.
        let status: Self = serde_json::from_slice(&contents).map_err(io::Error::other)?;
        if status.schema != SCHEMA || status.pid == 0 || status.port == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid service status schema, PID, or port",
            ));
        }
        Ok(Some(status))
    }

    pub(crate) fn live_port(&self, probe: &SystemProbe) -> Result<Option<u16>, ProbeError> {
        let matches = probe.boot_id()? == self.boot_id
            && probe.process_start_time(self.pid)? == Some(self.start_time);
        Ok(matches.then_some(self.port))
    }

    pub(crate) fn pid(&self) -> u32 {
        self.pid
    }

    /// Older status files have no startup registry to compare.
    pub(crate) fn matches_registry(&self, home: &Path) -> Option<bool> {
        self.registry_home
            .as_ref()
            .map(|recorded| canonical_registry_home(home).as_ref() == Some(recorded))
    }
}

fn canonical_registry_home(home: &Path) -> Option<PathBuf> {
    // A fresh service can start before the registry directory is created.
    // Resolve existing ancestors and append only ordinary missing components.
    for ancestor in home.ancestors() {
        let mut resolved = match ancestor.canonicalize() {
            Ok(path) => path,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                // A dangling symlink does not tell us the canonical directory.
                if ancestor
                    .symlink_metadata()
                    .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
                {
                    continue;
                }
                return None;
            }
            Err(_) => return None,
        };
        let suffix = home.strip_prefix(ancestor).expect("ancestor is a prefix");
        for part in suffix.components() {
            let Component::Normal(name) = part else {
                return None;
            };
            resolved.push(name);
        }
        return Some(resolved);
    }
    None
}

pub(super) struct PublishedStatus(PathBuf);

impl PublishedStatus {
    /// Publish while holding the service lock and keep the guard until the listener stops.
    pub(super) fn write(dir: &Path, port: u16, registry_home: &Path) -> io::Result<Self> {
        let pid = process::id();
        let probe = SystemProbe::new();
        let start_time = probe
            .current_process_start_time()
            .map_err(io::Error::other)?;
        let boot_id = probe.boot_id().map_err(io::Error::other)?;
        let status = ServiceStatus {
            schema: SCHEMA,
            pid,
            start_time,
            boot_id,
            port,
            // JSON paths need UTF-8. An unrepresentable path leaves the registry unknown.
            registry_home: canonical_registry_home(registry_home)
                .filter(|path| path.to_str().is_some()),
        };
        let contents = serde_json::to_vec(&status).map_err(io::Error::other)?;
        platform::write_private_state_file(dir, FILE_NAME, &contents)?;
        Ok(Self(dir.join(FILE_NAME)))
    }
}

impl Drop for PublishedStatus {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.0);
    }
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use std::os::unix::fs::PermissionsExt;

    use serde_json::{Value, json};

    use super::*;

    #[test]
    fn status_is_private_atomically_replaces_stale_file_and_is_removed() {
        let fixture = crate::test_support::TempDir::new();
        let dir = fixture.path().join("state");
        let path = dir.join(FILE_NAME);
        fs::create_dir_all(&dir).unwrap();
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
        fs::write(&path, b"stale file").unwrap();
        let previous = fs::File::open(&path).unwrap();

        let registry_home = fixture.path().join("missing/registry");
        let guard = PublishedStatus::write(&dir, 8123, &registry_home).unwrap();
        let pid = process::id();
        let probe = SystemProbe::new();
        let start_time = probe.process_start_time(pid).unwrap().unwrap();
        let boot_id = probe.boot_id().unwrap();
        let current: Value = serde_json::from_reader(fs::File::open(&path).unwrap()).unwrap();
        assert_eq!(
            current,
            json!({"schema": 1, "pid": pid, "start_time": start_time, "boot_id": boot_id, "port": 8123,
                "registry_home": fixture.path().canonicalize().unwrap().join("missing/registry")})
        );
        assert!(!registry_home.exists());
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(io::read_to_string(previous).unwrap(), "stale file");
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);

        drop(guard);
        assert!(ServiceStatus::read(&path).unwrap().is_none());
    }
}