feat(import): add deterministic OpenAPI normalized IR
CI / Rust Checks (push) Failing after 3m12s
CI / UI Checks (push) Has been skipped
CI / Frontend E2E (push) Has been skipped
CI / Community Image Smoke (push) Has been skipped
CI / Deploy (push) Has been skipped

This commit is contained in:
bsodfather committed 2026-08-29 04:15:37 +03:00
1 parent bc03c33387
commit 6c2a3712d8
22 files changed
+6051 -352

No files matched your search

+491 -41
View File
@@ -2,12 +2,19 @@ use crank_core::HttpMethod;
use serde_json::Value;
use crate::rest::{
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
normalize::{ImportParseError, resolve_local_ref},
recommendations::{document_finding, operation_finding},
model::{
ImportFinding, ImportFindingSeverity, RestImportDocument, RestImportOperation,
RestImportParameter, RestParameterLocation,
},
normalize::ImportParseError,
recommendations::{document_blocker, document_finding, operation_finding},
};
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
parse_document_v2(root)
}
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let title = root
.pointer("/info/title")
.and_then(Value::as_str)
@@ -15,11 +22,15 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
.to_owned();
let servers = swagger_servers(root);
let mut findings = Vec::new();
let mut internal_finding_locations = Vec::new();
if servers.is_empty() {
findings.push(document_finding(
"missing_servers",
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
pointer: String::new(),
}));
}
let mut operations = Vec::new();
@@ -29,20 +40,95 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
.ok_or(ImportParseError::UnsupportedDocument)?;
for (path, path_item) in paths {
let path_parameters = parameters(root, path_item.get("parameters"));
if !path_item.is_object() {
findings.push(path_item_blocker(path));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
}));
continue;
}
for method_name in ["head", "options", "trace", "connect"] {
if path_item.get(method_name).is_some() {
findings.push(document_blocker(
"unsupported_http_method",
format!("Метод {method_name} для пути {path} пока не поддерживается."),
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!(
"/paths/{}/{}",
path.replace('~', "~0").replace('/', "~1"),
method_name
),
}));
}
}
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
let path_parameters = parameters(
root,
path_item.get("parameters"),
&format!("{path_pointer}/parameters"),
);
append_parameter_findings(
&mut findings,
&mut internal_finding_locations,
path_parameters.findings,
);
let path_parameters = path_parameters.parameters;
for method_name in ["get", "post", "put", "patch", "delete"] {
let Some(operation_value) = path_item.get(method_name) else {
continue;
};
if !operation_value.is_object() {
findings.push(document_blocker(
"invalid_operation",
"Операция имеет неверную структуру и не была интерпретирована.",
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!(
"/paths/{}/{}",
path.replace('~', "~0").replace('/', "~1"),
method_name
),
}));
continue;
}
let Some(method) = method_from_lower(method_name) else {
continue;
};
let mut operation_parameters = path_parameters.clone();
operation_parameters.extend(parameters(root, operation_value.get("parameters")));
let parsed_parameters = parameters(
root,
operation_value.get("parameters"),
&format!("{path_pointer}/{method_name}/parameters"),
);
append_parameter_findings(
&mut findings,
&mut internal_finding_locations,
parsed_parameters.findings,
);
operation_parameters.extend(parsed_parameters.parameters);
let tags = tags(
operation_value.get("tags"),
&format!("{path_pointer}/{method_name}/tags"),
);
append_parameter_findings(
&mut findings,
&mut internal_finding_locations,
tags.findings,
);
let request_body_schema = operation_parameters
.iter()
.find(|parameter| parameter.name == "body")
.and_then(|parameter| parameter.schema.clone());
.and_then(|parameter| {
parameter.schema.clone().map(|schema| {
(
schema,
crate::rest::model::SourceLocation {
pointer: format!("{}/schema", parameter.source_location.pointer),
},
)
})
});
let operation_parameters = operation_parameters
.into_iter()
.filter(|parameter| parameter.name != "body")
@@ -64,20 +150,22 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
tags: operation_value
.get("tags")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default(),
tags: tags.tags,
parameters: operation_parameters,
request_body_schema,
response_schema: response_schema(root, operation_value),
request_body_schema: request_body_schema
.as_ref()
.map(|(schema, _)| schema.clone()),
request_body_schema_location: request_body_schema.map(|(_, location)| location),
response_schema: response_schema(
operation_value,
&format!("{path_pointer}/{method_name}"),
)
.map(|(schema, _)| schema),
response_schema_location: response_schema(
operation_value,
&format!("{path_pointer}/{method_name}"),
)
.map(|(_, location)| location),
servers: Vec::new(),
findings: swagger_operation_findings(path, operation_value),
});
@@ -91,9 +179,201 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
servers,
operations,
findings,
internal_finding_locations,
})
}
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let title = root
.pointer("/info/title")
.and_then(Value::as_str)
.unwrap_or("Imported API")
.to_owned();
let servers = swagger_servers(root);
let mut findings = Vec::new();
if servers.is_empty() {
findings.push(document_finding(
"missing_servers",
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
));
}
let mut operations = Vec::new();
let paths = root
.get("paths")
.and_then(Value::as_object)
.ok_or(ImportParseError::UnsupportedDocument)?;
for (path, path_item) in paths {
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
let path_parameters = legacy_parameters(
root,
path_item.get("parameters"),
&format!("{path_pointer}/parameters"),
);
for method_name in ["get", "post", "put", "patch", "delete"] {
let Some(operation) = path_item.get(method_name) else {
continue;
};
let Some(method) = method_from_lower(method_name) else {
continue;
};
let operation_pointer = format!("{path_pointer}/{method_name}");
let mut parameters = path_parameters.clone();
parameters.extend(legacy_parameters(
root,
operation.get("parameters"),
&format!("{operation_pointer}/parameters"),
));
let request_body_schema = parameters
.iter()
.find(|parameter| parameter.name == "body")
.and_then(|parameter| parameter.schema.clone());
let parameters = parameters
.into_iter()
.filter(|parameter| parameter.name != "body")
.collect();
operations.push(RestImportOperation {
key: format!("{} {}", method_name.to_uppercase(), path),
method,
path: path.clone(),
operation_id: operation
.get("operationId")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
summary: operation
.get("summary")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
description: operation
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
tags: legacy_tags(operation.get("tags")),
parameters,
request_body_schema,
request_body_schema_location: None,
response_schema: legacy_response_schema(root, operation),
response_schema_location: None,
servers: Vec::new(),
findings: swagger_operation_findings(path, operation),
});
}
}
Ok(RestImportDocument {
format: "swagger".to_owned(),
version: Some("2.0".to_owned()),
title,
servers,
operations,
findings,
internal_finding_locations: Vec::new(),
})
}
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default()
}
fn legacy_parameters(
root: &Value,
value: Option<&Value>,
base_pointer: &str,
) -> Vec<RestImportParameter> {
value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.enumerate()
.filter_map(|(index, item)| {
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
let raw_location = item.get("in").and_then(Value::as_str)?;
let pointer = format!("{base_pointer}/{index}");
if raw_location == "body" {
return Some(RestImportParameter {
name: "body".to_owned(),
location: RestParameterLocation::Query,
required: item
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false),
description: item
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: item.get("schema").map(|schema| {
crate::rest::normalize::resolve_local_ref(root, schema, 0)
}),
source_location: crate::rest::model::SourceLocation { pointer },
schema_source_location: None,
});
}
let location = match raw_location {
"path" => RestParameterLocation::Path,
"query" => RestParameterLocation::Query,
"header" => RestParameterLocation::Header,
_ => return None,
};
Some(RestImportParameter {
name: item.get("name").and_then(Value::as_str)?.to_owned(),
location,
required: item
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false)
|| location == RestParameterLocation::Path,
description: item
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: legacy_parameter_schema(root, &item),
source_location: crate::rest::model::SourceLocation { pointer },
schema_source_location: None,
})
})
.collect()
})
.unwrap_or_default()
}
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
if let Some(schema) = parameter.get("schema") {
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
}
let mut schema = serde_json::Map::new();
for key in ["type", "format", "items", "enum", "default", "description"] {
if let Some(value) = parameter.get(key) {
schema.insert(
key.to_owned(),
crate::rest::normalize::resolve_local_ref(root, value, 0),
);
}
}
(!schema.is_empty()).then_some(Value::Object(schema))
}
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
let responses = operation.get("responses")?.as_object()?;
for code in ["200", "201", "202", "default"] {
let Some(response) = responses.get(code) else {
continue;
};
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
if let Some(schema) = response.get("schema") {
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
}
}
None
}
fn swagger_servers(root: &Value) -> Vec<String> {
let Some(host) = root.get("host").and_then(Value::as_str) else {
return Vec::new();
@@ -116,14 +396,51 @@ fn swagger_servers(root: &Value) -> Vec<String> {
.collect()
}
fn parameters(root: &Value, value: Option<&Value>) -> Vec<RestImportParameter> {
value
fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
let mut findings = Vec::new();
let parameters = value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| {
let item = resolve_local_ref(root, item, 0);
.enumerate()
.filter_map(|(index, item)| {
let pointer = format!("{base_pointer}/{index}");
{
let Some(object) = item.as_object() else {
findings.push(parameter_blocker(
"invalid_parameter",
"Параметр должен быть объектом и не был интерпретирован.",
&pointer,
));
return None;
};
if object.contains_key("$ref") {
findings.push(parameter_blocker(
"unresolved_parameter_reference",
"Параметр по $ref требует разрешения перед импортом.",
&pointer,
));
return None;
}
if !object.get("name").is_some_and(Value::is_string) {
findings.push(parameter_blocker(
"missing_parameter_name",
"У параметра отсутствует строковое поле name.",
&pointer,
));
return None;
}
if !object.get("in").is_some_and(Value::is_string) {
findings.push(parameter_blocker(
"missing_parameter_location",
"У параметра отсутствует строковое поле in.",
&pointer,
));
return None;
}
}
let item = item.clone();
let raw_location = item.get("in").and_then(Value::as_str)?;
if raw_location == "body" {
return Some(RestImportParameter {
@@ -137,16 +454,37 @@ fn parameters(root: &Value, value: Option<&Value>) -> Vec<RestImportParameter> {
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: item
.get("schema")
.map(|schema| resolve_local_ref(root, schema, 0)),
schema: item.get("schema").cloned(),
schema_source_location: item.get("schema").map(|_| {
crate::rest::model::SourceLocation {
pointer: format!("{base_pointer}/{index}/schema"),
}
}),
source_location: crate::rest::model::SourceLocation {
pointer: format!("{base_pointer}/{index}"),
},
});
}
let location = match raw_location {
"path" => RestParameterLocation::Path,
"query" => RestParameterLocation::Query,
"header" => RestParameterLocation::Header,
_ => return None,
"cookie" => {
findings.push(parameter_blocker(
"unsupported_cookie_parameter",
"Cookie parameter пока не поддерживается и не был импортирован.",
&pointer,
));
return None;
}
_ => {
findings.push(parameter_blocker(
"unsupported_parameter_location",
"Параметр использует неподдерживаемое значение in и не был импортирован.",
&pointer,
));
return None;
}
};
Some(RestImportParameter {
name: item.get("name").and_then(Value::as_str)?.to_owned(),
@@ -160,22 +498,95 @@ fn parameters(root: &Value, value: Option<&Value>) -> Vec<RestImportParameter> {
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: swagger_parameter_schema(root, &item),
schema: swagger_parameter_schema(_root, &item),
schema_source_location: Some(crate::rest::model::SourceLocation {
pointer: format!("{base_pointer}/{index}"),
}),
source_location: crate::rest::model::SourceLocation {
pointer,
},
})
})
.collect()
})
.unwrap_or_default()
.unwrap_or_default();
ParsedParameters {
parameters,
findings,
}
}
fn swagger_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
struct ParsedParameters {
parameters: Vec<RestImportParameter>,
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
}
struct ParsedTags {
tags: Vec<String>,
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
}
fn tags(value: Option<&Value>, base_pointer: &str) -> ParsedTags {
let mut findings = Vec::new();
let tags = value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.enumerate()
.filter_map(|(index, item)| match item.as_str() {
Some(tag) => Some(tag.to_owned()),
None => {
findings.push((
document_finding(
"invalid_tag",
"Тег должен быть строкой и не был импортирован.",
),
crate::rest::model::SourceLocation {
pointer: format!("{base_pointer}/{index}"),
},
));
None
}
})
.collect()
})
.unwrap_or_default();
ParsedTags { tags, findings }
}
fn parameter_blocker(
code: &str,
message: &str,
pointer: &str,
) -> (ImportFinding, crate::rest::model::SourceLocation) {
(
document_blocker(code, message),
crate::rest::model::SourceLocation {
pointer: pointer.to_owned(),
},
)
}
fn append_parameter_findings(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
) {
for (finding, location) in parameter_findings {
findings.push(finding);
locations.push(Some(location));
}
}
fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
if let Some(schema) = parameter.get("schema") {
return Some(resolve_local_ref(root, schema, 0));
return Some(schema.clone());
}
let mut schema = serde_json::Map::new();
for key in ["type", "format", "items", "enum", "default", "description"] {
if let Some(value) = parameter.get(key) {
schema.insert(key.to_owned(), resolve_local_ref(root, value, 0));
schema.insert(key.to_owned(), value.clone());
}
}
if schema.is_empty() {
@@ -185,18 +596,48 @@ fn swagger_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
}
}
fn response_schema(root: &Value, operation: &Value) -> Option<Value> {
fn response_schema(
operation: &Value,
operation_pointer: &str,
) -> Option<(Value, crate::rest::model::SourceLocation)> {
let responses = operation.get("responses")?.as_object()?;
for code in ["200", "201", "202", "default"] {
let Some(response) = responses.get(code) else {
continue;
};
let response = resolve_local_ref(root, response, 0);
if let Some(schema) = response.get("schema") {
return Some(resolve_local_ref(root, schema, 0));
let mut numeric = responses
.iter()
.filter_map(|(code, response)| {
(code.len() == 3)
.then(|| code.parse::<u16>().ok())
.flatten()
.filter(|status| (200..300).contains(status))
.map(|status| (status, code.as_str(), response))
})
.collect::<Vec<_>>();
numeric.sort_by(|left, right| (left.0, left.1).cmp(&(right.0, right.1)));
for (_, code, response) in numeric {
if let Some(schema) = response_schema_at(response, operation_pointer, code) {
return Some(schema);
}
}
None
responses
.get("default")
.and_then(|response| response_schema_at(response, operation_pointer, "default"))
}
fn response_schema_at(
response: &Value,
operation_pointer: &str,
code: &str,
) -> Option<(Value, crate::rest::model::SourceLocation)> {
response.get("schema").map(|schema| {
(
schema.clone(),
crate::rest::model::SourceLocation {
pointer: format!(
"{operation_pointer}/responses/{}/schema",
code.replace('~', "~0").replace('/', "~1")
),
},
)
})
}
fn swagger_operation_findings(
@@ -232,3 +673,12 @@ fn method_from_lower(value: &str) -> Option<HttpMethod> {
_ => None,
}
}
fn path_item_blocker(_path: &str) -> ImportFinding {
ImportFinding {
code: "invalid_path_item".to_owned(),
severity: ImportFindingSeverity::Error,
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
operation_key: None,
}
}