capsid-protocol 0.1.0-alpha.1

Versioned, size-bounded messages between the Capsid host and its guest agent.
Documentation
use std::{collections::BTreeMap, fmt, io};

use serde::{Deserialize, Serialize};

use crate::{ErrorReport, reason, truncate};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageDefaults {
    pub entrypoint: Vec<String>,

    pub command: Vec<String>,

    pub environment: BTreeMap<String, String>,

    pub working_directory: String,

    pub user: String,

    pub stop_signal: String,
}

impl ImageDefaults {
    pub fn resolve_argv(&self, command: &[String], entrypoint: Option<&str>) -> Vec<String> {
        match entrypoint {
            Some(value) => {
                let mut result = if value.is_empty() {
                    Vec::new()
                } else {
                    vec![value.to_owned()]
                };
                result.extend_from_slice(command);
                result
            }
            None => self
                .entrypoint
                .iter()
                .chain(if command.is_empty() {
                    self.command.as_slice()
                } else {
                    command
                })
                .cloned()
                .collect(),
        }
    }

    pub fn argv(&self) -> Vec<String> {
        self.entrypoint
            .iter()
            .chain(&self.command)
            .cloned()
            .collect()
    }
}

crate::named_enum! {
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
    pub enum FailureCategory {
        #[default]
        Unclassified = "unclassified",
        InvalidInput = "invalid_input",
        ContentUnavailable = "content_unavailable",
        ConversionFailed = "conversion_failed",
        GuestIncompatible = "guest_incompatible",
        ResourceLimit = "resource_limit",
        DeadlineExceeded = "deadline_exceeded",
        Interrupted = "interrupted",
        UnknownOutcome = "unknown_outcome",
    }
}

impl FailureCategory {
    pub fn diagnostic(self, stage: &str, reason: &str) -> String {
        format!("{stage} [{}]: {reason}", self.as_str())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
#[serde(deny_unknown_fields)]
#[error("[{}] {}", .category.as_str(), .reason)]
pub struct ImageFailure {
    pub category: FailureCategory,

    pub reason: String,
}

impl ImageFailure {
    // The reason reaches terminals and logs, so control characters arrive
    // escaped.
    pub fn new(category: FailureCategory, reason: impl fmt::Display) -> Self {
        let escaped = reason.to_string().escape_debug().to_string();
        Self {
            category,
            reason: truncate(&escaped, reason::MAX_CHARS),
        }
    }

    pub fn from_io(error: &io::Error, fallback: FailureCategory) -> Self {
        if let Some(failure) = error
            .get_ref()
            .and_then(|inner| inner.downcast_ref::<Self>())
        {
            return failure.clone();
        }

        if let Some(inner) = error
            .get_ref()
            .and_then(|inner| inner.downcast_ref::<io::Error>())
        {
            return Self::from_io(inner, fallback);
        }

        let category = match error.kind() {
            io::ErrorKind::StorageFull | io::ErrorKind::OutOfMemory => {
                FailureCategory::ResourceLimit
            }
            io::ErrorKind::TimedOut => FailureCategory::DeadlineExceeded,
            _ => fallback,
        };
        Self::new(category, error.report())
    }

    pub fn is_bounded(&self) -> bool {
        self.reason.chars().count() <= reason::MAX_CHARS
            && !self.reason.chars().any(char::is_control)
    }
}

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

    #[test]
    fn test_diagnostics_cannot_emit_terminal_controls_or_exceed_the_bound() {
        let failure = ImageFailure::new(FailureCategory::InvalidInput, "\u{1b}[31m\n".repeat(1000));
        assert_eq!(failure.reason.chars().count(), reason::MAX_CHARS);
        assert!(failure.is_bounded());
    }

    #[test]
    fn test_io_adapters_preserve_the_original_category_and_message() {
        let failure = ImageFailure::new(FailureCategory::GuestIncompatible, "unsupported runtime");
        let error = io::Error::other(io::Error::other(failure));
        let recovered = ImageFailure::from_io(&error, FailureCategory::ConversionFailed);
        assert_eq!(recovered.category, FailureCategory::GuestIncompatible);
        assert_eq!(recovered.reason, "unsupported runtime");
    }
}