use iac_forge::ir::IacType;
use iac_forge::naming::{to_pascal_case, to_snake_case};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldMatch {
Match,
Skip,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FieldSig {
json_name: String,
openapi_type: String,
openapi_format: String,
required: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct BodySchema {
fields: BTreeMap<String, FieldSig>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BodySigMap {
schemas: BTreeMap<String, BodySchema>,
}
impl BodySigMap {
pub fn from_openapi_json_path(
path: impl AsRef<Path>,
) -> Result<Self, Box<dyn std::error::Error>> {
let bytes = std::fs::read(path.as_ref())?;
let v: Value = serde_json::from_slice(&bytes)?;
Ok(Self::from_value(&v))
}
#[must_use]
pub fn from_value(spec: &Value) -> Self {
let mut schemas = BTreeMap::new();
let Some(components_schemas) = spec
.get("components")
.and_then(|c| c.get("schemas"))
.and_then(|s| s.as_object())
else {
return Self { schemas };
};
for (schema_name, schema_value) in components_schemas {
let Some(props) = schema_value
.get("properties")
.and_then(|p| p.as_object())
else {
continue;
};
let required: Vec<String> = schema_value
.get("required")
.and_then(|r| r.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let mut fields = BTreeMap::new();
for (json_name, prop_value) in props {
let pascal = pascal_case_from_json(json_name);
let openapi_type = prop_value
.get("type")
.and_then(|t| t.as_str())
.unwrap_or("")
.to_string();
let openapi_format = prop_value
.get("format")
.and_then(|f| f.as_str())
.unwrap_or("")
.to_string();
fields.insert(
pascal,
FieldSig {
json_name: json_name.clone(),
openapi_type,
openapi_format,
required: required.iter().any(|r| r == json_name),
},
);
}
let pascal_schema = pascal_case_from_json(schema_name);
schemas.insert(
pascal_schema,
BodySchema {
fields: fields.clone(),
},
);
schemas.insert(schema_name.clone(), BodySchema { fields });
}
Self { schemas }
}
#[must_use]
pub fn check_field(
&self,
body_type: &str,
pascal_field: &str,
attr_type: &IacType,
attr_required: bool,
) -> FieldMatch {
let Some(schema) = self.schemas.get(body_type) else {
return FieldMatch::Skip;
};
let Some(sig) = schema.fields.get(pascal_field) else {
return FieldMatch::Skip;
};
if !openapi_matches_iac_type(&sig.openapi_type, &sig.openapi_format, attr_type) {
return FieldMatch::Skip;
}
if sig.required != attr_required {
return FieldMatch::Skip;
}
FieldMatch::Match
}
#[must_use]
pub fn schema_count(&self) -> usize {
self.schemas.len()
}
}
pub type SharedBodySigMap = Option<Arc<BodySigMap>>;
fn pascal_case_from_json(s: &str) -> String {
to_pascal_case(&to_snake_case(s))
}
fn openapi_matches_iac_type(otype: &str, oformat: &str, iac: &IacType) -> bool {
match iac {
IacType::String => otype == "string",
IacType::Boolean => otype == "boolean",
IacType::Float | IacType::Numeric => {
otype == "number" || (otype == "integer" && (oformat == "double" || oformat == "float"))
}
IacType::Integer => {
otype == "integer" && oformat != "int32"
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn fixture_spec() -> Value {
json!({
"components": {
"schemas": {
"authMethodCreateApiKey": {
"type": "object",
"required": ["name"],
"properties": {
"name": { "type": "string" },
"access-expires": { "type": "integer", "format": "int64" },
"force-sub-claims": { "type": "boolean" },
"delete-protection": { "type": "string" },
"token": { "type": "string" }
}
},
"rotatedSecretCreateWindows": {
"type": "object",
"required": ["name", "target-name"],
"properties": {
"name": { "type": "string" },
"target-name": { "type": "string" },
"rotation-hour": { "type": "integer", "format": "int32" },
"delete-protection": { "type": "string" }
}
}
}
}
})
}
#[test]
fn parses_components_schemas_with_pascal_index() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(m.schema_count(), 4);
}
#[test]
fn matches_aligned_scalar_field() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"AuthMethodCreateApiKey",
"AccessExpires",
&IacType::Integer,
false,
),
FieldMatch::Match,
);
assert_eq!(
m.check_field(
"AuthMethodCreateApiKey",
"ForceSubClaims",
&IacType::Boolean,
false,
),
FieldMatch::Match,
);
}
#[test]
fn skips_type_mismatch_delete_protection_bool_vs_string() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"AuthMethodCreateApiKey",
"DeleteProtection",
&IacType::Boolean,
false,
),
FieldMatch::Skip,
);
}
#[test]
fn skips_type_mismatch_rotation_hour_int64_vs_int32() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"RotatedSecretCreateWindows",
"RotationHour",
&IacType::Integer,
false,
),
FieldMatch::Skip,
);
}
#[test]
fn skips_missing_field() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"AuthMethodCreateApiKey",
"NonexistentField",
&IacType::String,
false,
),
FieldMatch::Skip,
);
}
#[test]
fn skips_unknown_body_type() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"TotallyMadeUpBody",
"Name",
&IacType::String,
true,
),
FieldMatch::Skip,
);
}
#[test]
fn skips_required_disagreement() {
let m = BodySigMap::from_value(&fixture_spec());
assert_eq!(
m.check_field(
"RotatedSecretCreateWindows",
"TargetName",
&IacType::String,
false, ),
FieldMatch::Skip,
);
assert_eq!(
m.check_field(
"RotatedSecretCreateWindows",
"TargetName",
&IacType::String,
true,
),
FieldMatch::Match,
);
}
}