Skip to main content

engenho_kube_codegen/
openapi.rs

1//! `OpenAPI` v3 parser — sufficient surface to extract a "kind shape"
2//! per [`crate::catalog::KindEntry`].
3//!
4//! Intentionally minimal — full $ref-walking lives in M0.0.4. For
5//! M0.0.1 we just need to confirm each cataloged kind EXISTS in the
6//! vendored schema + has the expected `x-kubernetes-group-version-kind`
7//! metadata. That's the "this catalog matches the schema" check that
8//! gates `engenho-kube-codegen --check`.
9
10use anyhow::{Context, Result, anyhow};
11use serde::Deserialize;
12use std::collections::BTreeMap;
13
14/// Top-level `OpenAPI` v3 document. We only deserialize the components
15/// section we use — the rest is left as raw JSON.
16#[derive(Debug, Deserialize)]
17pub struct OpenApiDoc {
18    /// Sub-section with the resource type definitions.
19    pub components: Components,
20}
21
22/// `components.schemas` from the `OpenAPI` doc.
23#[derive(Debug, Deserialize)]
24pub struct Components {
25    /// Definition map: key is the full openapi-key
26    /// (e.g. `io.k8s.api.core.v1.Pod`), value is the schema body.
27    pub schemas: BTreeMap<String, KindShape>,
28}
29
30/// Per-kind schema body. We only extract what we need.
31#[derive(Debug, Deserialize, Clone)]
32pub struct KindShape {
33    /// `x-kubernetes-group-version-kind` array. Most kinds have ONE
34    /// entry; alpha kinds in transition can have multiple.
35    #[serde(default, rename = "x-kubernetes-group-version-kind")]
36    pub gvks: Vec<XGvk>,
37
38    /// Human-readable description (drops into the generated rustdoc).
39    #[serde(default)]
40    pub description: String,
41
42    /// Top-level properties. Used at M0.0.4 to emit typed fields.
43    #[serde(default)]
44    pub properties: BTreeMap<String, serde_json::Value>,
45
46    /// Required properties. Used at M0.0.4 for `#[serde(skip_serializing_if)]`.
47    #[serde(default)]
48    pub required: Vec<String>,
49}
50
51/// `x-kubernetes-group-version-kind` entry.
52#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
53pub struct XGvk {
54    /// API group (`""` for core/v1).
55    pub group: String,
56    /// API version.
57    pub version: String,
58    /// Kind name.
59    pub kind: String,
60}
61
62impl OpenApiDoc {
63    /// Load + parse an `OpenAPI` v3 JSON file.
64    ///
65    /// # Errors
66    ///
67    /// Forwards parse errors with context including the file path.
68    pub fn load(path: &std::path::Path) -> Result<Self> {
69        let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
70        serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))
71    }
72
73    /// Find the `KindShape` for `openapi_key`, or error.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error mentioning the key when absent.
78    pub fn shape(&self, openapi_key: &str) -> Result<&KindShape> {
79        self.components
80            .schemas
81            .get(openapi_key)
82            .ok_or_else(|| anyhow!("kind {openapi_key:?} not in OpenAPI components.schemas"))
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn parses_minimal_openapi_doc() {
92        let json = serde_json::json!({
93            "components": {
94                "schemas": {
95                    "io.k8s.api.core.v1.Pod": {
96                        "x-kubernetes-group-version-kind": [
97                            {"group": "", "version": "v1", "kind": "Pod"}
98                        ],
99                        "description": "Pod is a collection of containers",
100                        "properties": {"metadata": {}, "spec": {}, "status": {}},
101                        "required": ["spec"]
102                    }
103                }
104            }
105        });
106        let doc: OpenApiDoc = serde_json::from_value(json).unwrap();
107        let pod = doc.shape("io.k8s.api.core.v1.Pod").unwrap();
108        assert_eq!(pod.gvks.len(), 1);
109        assert_eq!(
110            pod.gvks[0],
111            XGvk {
112                group: String::new(),
113                version: "v1".into(),
114                kind: "Pod".into(),
115            }
116        );
117    }
118
119    #[test]
120    fn missing_shape_errors() {
121        let doc = OpenApiDoc {
122            components: Components {
123                schemas: BTreeMap::new(),
124            },
125        };
126        let err = doc.shape("io.k8s.api.core.v1.Pod").unwrap_err();
127        assert!(err.to_string().contains("not in OpenAPI"));
128    }
129}