krab-api 0.1.0

Kubernetes-compatible API server for krabkube
Documentation
use crate::registry::ResDef;
use serde_json::{Value, json};

#[derive(Debug)]
pub struct ApiError {
    pub code: u16,
    pub reason: &'static str,
    pub message: String,
    pub details: Value,
}

impl ApiError {
    pub fn new(code: u16, reason: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            reason,
            message: message.into(),
            details: Value::Null,
        }
    }

    pub fn to_json(&self) -> Value {
        let mut v = json!({"kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": self.message, "reason": self.reason, "code": self.code});
        if !self.details.is_null() {
            v["details"] = self.details.clone();
        }
        v
    }

    fn with(mut self, details: Value) -> Self {
        self.details = details;
        self
    }

    pub fn bad_request(msg: impl Into<String>) -> Self {
        Self::new(400, "BadRequest", msg)
    }

    pub fn not_found_path() -> Self {
        Self::new(
            404,
            "NotFound",
            "the server could not find the requested resource",
        )
    }

    pub fn method_not_allowed() -> Self {
        Self::new(
            405,
            "MethodNotAllowed",
            "the server does not allow this method on the requested resource",
        )
    }

    pub fn unsupported_media(msg: impl Into<String>) -> Self {
        Self::new(415, "UnsupportedMediaType", msg)
    }
}

fn details(r: &ResDef, name: &str) -> Value {
    let mut d = json!({"name": name, "kind": r.plural});
    if !r.group.is_empty() {
        d["group"] = json!(r.group);
    }
    d
}

pub fn not_found(r: &ResDef, name: &str) -> ApiError {
    ApiError::new(
        404,
        "NotFound",
        format!("{} \"{name}\" not found", r.qualified()),
    )
    .with(details(r, name))
}

pub fn namespace_not_found(ns: &str) -> ApiError {
    ApiError::new(404, "NotFound", format!("namespaces \"{ns}\" not found"))
        .with(json!({"name": ns, "kind": "namespaces"}))
}

pub fn already_exists(r: &ResDef, name: &str) -> ApiError {
    ApiError::new(
        409,
        "AlreadyExists",
        format!("{} \"{name}\" already exists", r.qualified()),
    )
    .with(details(r, name))
}

pub fn conflict(r: &ResDef, name: &str, why: &str) -> ApiError {
    ApiError::new(
        409,
        "Conflict",
        format!(
            "Operation cannot be fulfilled on {} \"{name}\": {why}",
            r.qualified()
        ),
    )
    .with(details(r, name))
}

pub fn stale(r: &ResDef, name: &str) -> ApiError {
    conflict(
        r,
        name,
        "the object has been modified; please apply your changes to the latest version and try again",
    )
}

pub fn forbidden(r: &ResDef, name: &str, why: &str) -> ApiError {
    ApiError::new(
        403,
        "Forbidden",
        format!("{} \"{name}\" is forbidden: {why}", r.qualified()),
    )
    .with(details(r, name))
}

pub fn invalid(r: &ResDef, name: &str, causes: Vec<(&str, String)>) -> ApiError {
    let text: Vec<String> = causes.iter().map(|(f, m)| format!("{f}: {m}")).collect();
    let msg = if text.len() == 1 {
        text[0].clone()
    } else {
        format!("[{}]", text.join(", "))
    };
    let mut d = json!({"name": name, "kind": r.kind, "causes": causes.iter().map(|(f, m)| json!({"reason": "FieldValueInvalid", "message": m, "field": f})).collect::<Vec<_>>()});
    if !r.group.is_empty() {
        d["group"] = json!(r.group);
    }
    ApiError::new(
        422,
        "Invalid",
        format!("{} \"{name}\" is invalid: {msg}", r.kind),
    )
    .with(d)
}