krab-api 0.2.1

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

pub fn aggregated_version(accept: &str) -> Option<&'static str> {
    for mt in accept.split(',') {
        let mut g = false;
        let mut v = None;
        let mut list = false;
        for p in mt.split(';').skip(1) {
            match p.trim().split_once('=') {
                Some(("g", "apidiscovery.k8s.io")) => g = true,
                Some(("v", "v2")) => v = Some("v2"),
                Some(("v", "v2beta1")) => v = Some("v2beta1"),
                Some(("as", "APIGroupDiscoveryList")) => list = true,
                _ => {}
            }
        }
        if g && list && v.is_some() {
            return v;
        }
    }
    None
}

pub fn content_type(v: &str) -> String {
    format!("application/json;g=apidiscovery.k8s.io;v={v};as=APIGroupDiscoveryList")
}

pub fn api_resource(r: &ResDef) -> Value {
    json!({"name": r.plural, "singularName": r.singular, "namespaced": r.namespaced, "kind": r.kind, "verbs": r.verbs, "shortNames": r.short, "categories": r.categories})
}

pub fn resource_list(group: &str, version: &str) -> Option<Value> {
    let gv = if group.is_empty() {
        version.to_string()
    } else {
        format!("{group}/{version}")
    };
    let mut out = Vec::new();
    for r in registry::in_group(group, version) {
        out.push(api_resource(r));
        for s in r.subresources {
            let (g, v, k) = r.sub_kind(s);
            let mut e = json!({"name": format!("{}/{s}", r.plural), "singularName": "", "namespaced": r.namespaced, "kind": k, "verbs": r.sub_verbs(s)});
            if *s == "scale" {
                e["group"] = json!(g);
                e["version"] = json!(v);
            }
            out.push(e);
        }
    }
    if out.is_empty() {
        return None;
    }
    Some(
        json!({"kind": "APIResourceList", "apiVersion": "v1", "groupVersion": gv, "resources": out}),
    )
}

pub fn api_group(group: &str) -> Option<Value> {
    let (_, v) = registry::group_versions()
        .into_iter()
        .find(|(g, _)| *g == group)?;
    let gv = format!("{group}/{v}");
    Some(
        json!({"kind": "APIGroup", "apiVersion": "v1", "name": group, "versions": [{"groupVersion": gv, "version": v}], "preferredVersion": {"groupVersion": gv, "version": v}}),
    )
}

pub fn api_group_list() -> Value {
    let groups: Vec<Value> = registry::group_versions()
        .into_iter()
        .filter_map(|(g, _)| api_group(g))
        .map(|mut g| {
            if let Some(o) = g.as_object_mut() {
                o.remove("kind");
                o.remove("apiVersion");
            }
            g
        })
        .collect();
    json!({"kind": "APIGroupList", "apiVersion": "v1", "groups": groups})
}

fn agg_resource(r: &ResDef) -> Value {
    let subs: Vec<Value> = r
        .subresources
        .iter()
        .map(|s| {
            let (g, v, k) = r.sub_kind(s);
            json!({"subresource": s, "responseKind": {"group": g, "version": v, "kind": k}, "verbs": r.sub_verbs(s)})
        })
        .collect();
    let mut e = json!({
        "resource": r.plural,
        "responseKind": {"group": r.group, "version": r.version, "kind": r.kind},
        "scope": if r.namespaced {"Namespaced"} else {"Cluster"},
        "singularResource": r.singular,
        "verbs": r.verbs,
    });
    if !r.short.is_empty() {
        e["shortNames"] = json!(r.short);
    }
    if !r.categories.is_empty() {
        e["categories"] = json!(r.categories);
    }
    if !subs.is_empty() {
        e["subresources"] = Value::Array(subs);
    }
    e
}

fn agg_item(group: &str, version: &str) -> Value {
    let resources: Vec<Value> = registry::in_group(group, version)
        .map(agg_resource)
        .collect();
    let mut meta = json!({"creationTimestamp": null});
    if !group.is_empty() {
        meta["name"] = json!(group);
    }
    json!({"metadata": meta, "versions": [{"version": version, "resources": resources, "freshness": "Current"}]})
}

pub fn aggregated(legacy: bool, v: &str) -> Value {
    let items: Vec<Value> = if legacy {
        vec![agg_item("", "v1")]
    } else {
        registry::group_versions()
            .into_iter()
            .map(|(g, ver)| agg_item(g, ver))
            .collect()
    };
    json!({"kind": "APIGroupDiscoveryList", "apiVersion": format!("apidiscovery.k8s.io/{v}"), "metadata": {}, "items": items})
}

pub fn openapi_index() -> Value {
    let mut paths = serde_json::Map::new();
    paths.insert(
        "api/v1".into(),
        json!({"serverRelativeURL": "/openapi/v3/api/v1"}),
    );
    for (g, v) in registry::group_versions() {
        paths.insert(
            format!("apis/{g}/{v}"),
            json!({"serverRelativeURL": format!("/openapi/v3/apis/{g}/{v}")}),
        );
    }
    json!({ "paths": paths })
}

pub fn openapi_doc(group: &str, version: &str) -> Option<Value> {
    let mut paths = serde_json::Map::new();
    let param = json!([{"name": "fieldValidation", "in": "query", "schema": {"type": "string", "uniqueItems": true}}, {"name": "fieldManager", "in": "query", "schema": {"type": "string", "uniqueItems": true}}, {"name": "dryRun", "in": "query", "schema": {"type": "string", "uniqueItems": true}}]);
    let base = if group.is_empty() {
        format!("/api/{version}")
    } else {
        format!("/apis/{group}/{version}")
    };
    let mut any = false;
    for r in registry::in_group(group, version).filter(|r| r.stored) {
        any = true;
        let gvk = json!({"group": r.group, "version": r.version, "kind": r.kind});
        let ns = if r.namespaced {
            "/namespaces/{namespace}"
        } else {
            ""
        };
        let op = |verb: &str| json!({"operationId": format!("{verb}{}", r.kind), "x-kubernetes-action": verb, "x-kubernetes-group-version-kind": gvk, "parameters": param, "responses": {"200": {"description": "OK"}}});
        if r.can("create") {
            paths.insert(
                format!("{base}{ns}/{}", r.plural),
                json!({"post": op("post")}),
            );
        }
        if r.can("patch") {
            paths.insert(
                format!("{base}{ns}/{}/{{name}}", r.plural),
                json!({"put": op("put"), "patch": op("patch")}),
            );
        }
    }
    if !any {
        return None;
    }
    Some(
        json!({"openapi": "3.0.0", "info": {"title": "Kubernetes", "version": crate::objects::VERSION}, "paths": paths, "components": {"schemas": {}}}),
    )
}

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

    #[test]
    fn accept_negotiation() {
        let a = "application/json;g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList,application/json;g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList,application/json";
        assert_eq!(aggregated_version(a), Some("v2"));
        assert_eq!(aggregated_version("application/json"), None);
    }

    #[test]
    fn aggregated_has_subresources() {
        let v = aggregated(false, "v2");
        let apps = v["items"]
            .as_array()
            .unwrap()
            .iter()
            .find(|i| i["metadata"]["name"] == "apps")
            .unwrap();
        let d = apps["versions"][0]["resources"]
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["resource"] == "deployments")
            .unwrap();
        assert_eq!(d["subresources"][1]["responseKind"]["kind"], "Scale");
        assert_eq!(
            aggregated(true, "v2")["items"][0]["versions"][0]["version"],
            "v1"
        );
    }
}