cgd 0.1.0-alpha.2

Official command-line interface for Coragrid source-linked private-market data infrastructure
Documentation
use std::fmt;
use std::io;

use crate::client::Problem;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ExitStatus {
    Success = 0,
    Usage = 2,
    Authentication = 3,
    Permission = 4,
    NotFound = 5,
    Conflict = 6,
    RateLimit = 7,
    Unavailable = 8,
    Timeout = 9,
    // Reserved by the published CLI exit taxonomy for future partial-result
    // operations even though the current alpha has no such command.
    #[allow(dead_code)]
    Partial = 10,
    Internal = 70,
    Interrupted = 130,
}

impl ExitStatus {
    pub const fn code(self) -> u8 {
        self as u8
    }
}

#[derive(Debug)]
pub enum CgdError {
    Usage(String),
    Configuration(String),
    Authentication(String),
    Permission(String),
    NotFound(String),
    Conflict(String),
    RateLimited(String),
    Unavailable(String),
    Timeout(String),
    Api(Box<Problem>),
    Transport(String),
    Decode(String),
    Io(io::Error),
    BrokenPipe,
    Interrupted,
    Internal(String),
}

impl CgdError {
    pub fn exit_status(&self) -> ExitStatus {
        match self {
            Self::Usage(_) | Self::Configuration(_) => ExitStatus::Usage,
            Self::Authentication(_) => ExitStatus::Authentication,
            Self::Permission(_) => ExitStatus::Permission,
            Self::NotFound(_) => ExitStatus::NotFound,
            Self::Conflict(_) => ExitStatus::Conflict,
            Self::RateLimited(_) => ExitStatus::RateLimit,
            Self::Unavailable(_) | Self::Transport(_) => ExitStatus::Unavailable,
            Self::Timeout(_) => ExitStatus::Timeout,
            Self::Api(problem) => match problem.status {
                400 | 413 | 422 => ExitStatus::Usage,
                401 => ExitStatus::Authentication,
                403 => ExitStatus::Permission,
                404 => ExitStatus::NotFound,
                409 => ExitStatus::Conflict,
                429 => ExitStatus::RateLimit,
                408 | 504 => ExitStatus::Timeout,
                500..=503 => ExitStatus::Unavailable,
                _ => ExitStatus::Internal,
            },
            Self::Decode(_) | Self::Io(_) | Self::Internal(_) => ExitStatus::Internal,
            Self::BrokenPipe => ExitStatus::Success,
            Self::Interrupted => ExitStatus::Interrupted,
        }
    }

    pub fn request_id(&self) -> Option<&str> {
        match self {
            Self::Api(problem) => Some(problem.request_id.as_str()),
            _ => None,
        }
    }
}

impl fmt::Display for CgdError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Usage(message)
            | Self::Configuration(message)
            | Self::Authentication(message)
            | Self::Permission(message)
            | Self::NotFound(message)
            | Self::Conflict(message)
            | Self::RateLimited(message)
            | Self::Unavailable(message)
            | Self::Timeout(message)
            | Self::Transport(message)
            | Self::Decode(message)
            | Self::Internal(message) => formatter.write_str(message),
            Self::Api(problem) => write!(formatter, "{}: {}", problem.title, problem.detail),
            Self::Io(error) => write!(formatter, "I/O error: {error}"),
            Self::BrokenPipe => formatter.write_str("output pipe closed"),
            Self::Interrupted => formatter.write_str("interrupted"),
        }
    }
}

impl std::error::Error for CgdError {}

impl From<io::Error> for CgdError {
    fn from(error: io::Error) -> Self {
        if error.kind() == io::ErrorKind::BrokenPipe {
            Self::BrokenPipe
        } else {
            Self::Io(error)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rfc9457_statuses_map_to_the_stable_exit_taxonomy() {
        let cases = [
            (400, ExitStatus::Usage),
            (413, ExitStatus::Usage),
            (422, ExitStatus::Usage),
            (401, ExitStatus::Authentication),
            (403, ExitStatus::Permission),
            (404, ExitStatus::NotFound),
            (409, ExitStatus::Conflict),
            (429, ExitStatus::RateLimit),
            (408, ExitStatus::Timeout),
            (504, ExitStatus::Timeout),
            (500, ExitStatus::Unavailable),
            (502, ExitStatus::Unavailable),
            (503, ExitStatus::Unavailable),
            (418, ExitStatus::Internal),
        ];

        for (status, expected) in cases {
            let error = CgdError::Api(Box::new(Problem {
                r#type: "https://coragrid.com/problems/fixture".to_owned(),
                title: "Fixture".to_owned(),
                status,
                detail: "fixture".to_owned(),
                instance: "/fixture".to_owned(),
                request_id: "req_014d2pf2dbsqqg28t5cy4tqkff".to_owned(),
                code: "fixture".to_owned(),
                retryable: false,
            }));
            assert_eq!(error.exit_status(), expected, "HTTP status {status}");
        }
    }
}