Files
crank/crates/crank-import/src/rest/swagger2.rs
T
bsodfather e93de7015a
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
feat(import): complete OpenAPI onboarding and verify delivery
2026-10-09 17:50:38 +03:00

1000 lines
39 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use crank_core::HttpMethod;
use serde_json::Value;
use crate::rest::{
model::{
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
},
normalize::ImportParseError,
recommendations::{document_blocker, document_finding},
};
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
parse_document_v2(root)
}
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let security_schemes = super::security::schemes(root, true);
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();
let mut internal_finding_locations = Vec::new();
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
super::swagger2_findings::servers(root),
);
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();
let paths = root
.get("paths")
.and_then(Value::as_object)
.ok_or(ImportParseError::UnsupportedDocument)?;
for (path, path_item) in paths {
if !path_item.is_object() {
findings.push(super::http_methods::invalid_path_item());
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
}));
continue;
}
for method_name in super::swagger2_findings::unsupported_methods(path_item) {
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"),
);
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
path_parameters.findings,
);
let path_parameters = path_parameters.parameters;
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
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) = super::http_methods::from_lower(method_name) else {
continue;
};
let mut operation_parameters = path_parameters.clone();
let parsed_parameters = parameters(
root,
operation_value.get("parameters"),
&format!("{path_pointer}/{method_name}/parameters"),
);
let parsed_parameter_findings = parsed_parameters.findings;
operation_parameters.extend(parsed_parameters.parameters);
deduplicate_parameters(&mut operation_parameters);
let tags = tags(
operation_value.get("tags"),
&format!("{path_pointer}/{method_name}/tags"),
);
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
tags.findings,
);
let request_body_variants = swagger_request_body_variants(
root,
path_item,
operation_value,
&path_pointer,
&format!("{path_pointer}/{method_name}"),
);
let request_body_schema = operation_parameters
.iter()
.find(|parameter| parameter.name == "body")
.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")
.collect::<Vec<_>>();
let operation_pointer = format!("{path_pointer}/{method_name}");
let mut located_operation_findings =
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
let (security_requirements, security_findings) =
super::security::collect_operation_requirements(
root,
operation_value,
&operation_pointer,
&security_schemes,
);
located_operation_findings.extend(security_findings);
located_operation_findings.extend(parsed_parameter_findings);
located_operation_findings.extend(super::swagger2_findings::path_parameters(
path,
&operation_parameters,
&operation_pointer,
));
let (operation_findings, internal_finding_locations) =
located_operation_findings.into_iter().unzip();
let response_schema = (method != HttpMethod::Head)
.then(|| response_schema(operation_value, &operation_pointer))
.flatten();
operations.push(RestImportOperation {
key: format!("{} {}", method_name.to_uppercase(), path),
method,
path: path.clone(),
source_location: None,
security_requirements,
operation_id: operation_value
.get("operationId")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
summary: operation_value
.get("summary")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
description: operation_value
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
tags: tags.tags,
parameters: operation_parameters,
request_body_schema: request_body_schema
.as_ref()
.map(|(schema, _)| schema.clone()),
request_body_schema_location: request_body_schema.map(|(_, location)| location),
request_body_variants,
response_schema: response_schema.as_ref().map(|(schema, _)| schema.clone()),
response_schema_location: response_schema.map(|(_, location)| location),
response_variants: swagger_response_variants(
root,
operation_value,
&operation_pointer,
method,
),
servers: Vec::new(),
findings: operation_findings,
internal_finding_locations,
});
}
}
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
super::security::unused_unsupported_scheme_findings(root, &security_schemes),
);
Ok(RestImportDocument {
format: "swagger".to_owned(),
version: Some("2.0".to_owned()),
title,
servers,
security_schemes,
operations,
findings,
internal_finding_locations,
})
}
fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
let mut seen = std::collections::BTreeSet::new();
parameters.reverse();
parameters.retain(|parameter| seen.insert((parameter.name.clone(), parameter.location)));
parameters.reverse();
}
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) = super::http_methods::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(),
source_location: None,
security_requirements: Default::default(),
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,
request_body_variants: Vec::new(),
response_schema: legacy_response_schema(root, operation),
response_schema_location: None,
response_variants: Vec::new(),
servers: Vec::new(),
findings: super::swagger2_findings::legacy_operation(path, operation),
internal_finding_locations: Vec::new(),
});
}
}
Ok(RestImportDocument {
format: "swagger".to_owned(),
version: Some("2.0".to_owned()),
title,
servers,
security_schemes: Default::default(),
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();
};
let base_path = root.get("basePath").and_then(Value::as_str).unwrap_or("");
if host.is_empty()
|| host.contains('@')
|| host.chars().any(char::is_whitespace)
|| (!base_path.is_empty() && !base_path.starts_with('/'))
|| base_path.chars().any(char::is_control)
{
return Vec::new();
}
let schemes = root
.get("schemes")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.filter(|scheme| matches!(*scheme, "http" | "https"))
.collect::<Vec<_>>()
})
.filter(|items| !items.is_empty())
.unwrap_or_else(|| vec!["https"]);
schemes
.into_iter()
.map(|scheme| {
format!("{scheme}://{host}{base_path}")
.trim_end_matches('/')
.to_owned()
})
.collect()
}
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()
.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)?;
let parameter_schema = swagger_parameter_schema(_root, &item);
if parameter_schema.is_none() {
findings.push(parameter_blocker(
"missing_parameter_schema",
"Swagger parameter не содержит schema/type.",
&pointer,
));
}
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").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}"),
},
});
}
if raw_location == "formData" {
findings.extend(super::swagger2_findings::form_data_parameter(
&item,
parameter_schema.as_ref(),
&pointer,
));
return None;
}
let location = match raw_location {
"path" => RestParameterLocation::Path,
"query" => RestParameterLocation::Query,
"header" => RestParameterLocation::Header,
"cookie" => {
findings.push(parameter_blocker(
"unsupported_cookie_parameter",
"Cookie parameter пока не поддерживается и не был импортирован.",
&pointer,
));
return None;
}
_ => {
findings.push(parameter_blocker(
"unsupported_parameter_location",
"Параметр использует неподдерживаемое значение in и не был импортирован.",
&pointer,
));
return None;
}
};
if parameter_schema.as_ref().is_some_and(|schema| {
matches!(schema.get("type").and_then(Value::as_str), Some("array" | "object"))
}) || item.get("collectionFormat").is_some()
{
let finding_pointer = if item.get("collectionFormat").is_some() {
format!("{pointer}/collectionFormat")
} else {
pointer.clone()
};
findings.push(parameter_blocker(
"unsupported_parameter_style",
"Swagger array/object parameter serialization не поддерживается текущим REST mapping.",
&finding_pointer,
));
}
if let Some(schema) = swagger_parameter_schema(_root, &item) {
super::openapi3_findings::schema_findings(
&schema,
&pointer,
&mut findings,
);
}
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),
description: item
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
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();
ParsedParameters {
parameters,
findings,
}
}
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 swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
if let Some(schema) = parameter.get("schema") {
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(), value.clone());
}
}
if schema.get("type").and_then(Value::as_str) == Some("file") {
schema.insert("type".to_owned(), Value::String("string".to_owned()));
schema.insert("format".to_owned(), Value::String("binary".to_owned()));
}
if schema.is_empty() {
None
} else {
Some(Value::Object(schema))
}
}
fn response_schema(
operation: &Value,
operation_pointer: &str,
) -> Option<(Value, crate::rest::model::SourceLocation)> {
let responses = operation.get("responses")?.as_object()?;
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);
}
}
responses
.get("default")
.and_then(|response| response_schema_at(response, operation_pointer, "default"))
}
fn swagger_request_body_variants(
root: &Value,
path_item: &Value,
operation: &Value,
path_pointer: &str,
operation_pointer: &str,
) -> Vec<RestRequestBodyVariant> {
let parameters =
effective_swagger_parameters(path_item, operation, path_pointer, operation_pointer);
let body = parameters
.iter()
.find(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("body"));
let form = swagger_form_data_schema(&parameters);
let (schema, schema_source_location, schema_property_source_locations) =
if let Some((body, pointer)) = body {
let Some(schema) = body.get("schema").cloned() else {
return Vec::new();
};
(
schema,
Some(crate::rest::model::SourceLocation {
pointer: format!("{pointer}/schema"),
}),
Default::default(),
)
} else if let Some(form) = form {
form
} else {
return Vec::new();
};
let required = body
.and_then(|(parameter, _)| parameter.get("required").and_then(Value::as_bool))
.unwrap_or_else(|| {
parameters.iter().any(|(parameter, _)| {
parameter.get("in").and_then(Value::as_str) == Some("formData")
&& parameter
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false)
})
});
let content_types = effective_media_types(root, operation, "consumes", "application/json");
content_types
.into_iter()
.filter(|content_type| supported_request_content_type(content_type))
.map(|content_type| RestRequestBodyVariant {
content_type,
required,
schema: Some(schema.clone()),
multipart_field_mime_types: Default::default(),
source_location: crate::rest::model::SourceLocation {
pointer: schema_source_location
.as_ref()
.map(|location| location.pointer.trim_end_matches("/schema").to_owned())
.unwrap_or_else(|| format!("{operation_pointer}/parameters")),
},
schema_source_location: schema_source_location.clone(),
schema_property_source_locations: schema_property_source_locations.clone(),
})
.collect()
}
fn effective_swagger_parameters(
path_item: &Value,
operation: &Value,
path_pointer: &str,
operation_pointer: &str,
) -> Vec<(Value, String)> {
let mut parameters = Vec::new();
for (owner, pointer) in [
(path_item, format!("{path_pointer}/parameters")),
(operation, format!("{operation_pointer}/parameters")),
] {
let Some(items) = owner.get("parameters").and_then(Value::as_array) else {
continue;
};
for (index, parameter) in items.iter().enumerate() {
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
continue;
};
let Some(location) = parameter.get("in").and_then(Value::as_str) else {
continue;
};
parameters.retain(|(existing, _): &(Value, String)| {
existing.get("name").and_then(Value::as_str) != Some(name)
|| existing.get("in").and_then(Value::as_str) != Some(location)
});
parameters.push((parameter.clone(), format!("{pointer}/{index}")));
}
}
parameters
}
fn swagger_form_data_schema(
parameters: &[(Value, String)],
) -> Option<(
Value,
Option<crate::rest::model::SourceLocation>,
std::collections::BTreeMap<String, crate::rest::model::SourceLocation>,
)> {
let form_parameters = parameters
.iter()
.filter(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("formData"));
let mut properties = serde_json::Map::new();
let mut required = Vec::new();
let mut property_locations = std::collections::BTreeMap::new();
let mut root_pointer = None;
for (parameter, pointer) in form_parameters {
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
continue;
};
root_pointer.get_or_insert_with(|| {
pointer
.rsplit_once('/')
.map(|(parent, _)| parent.to_owned())
.unwrap_or_else(|| pointer.clone())
});
property_locations.insert(
name.to_owned(),
crate::rest::model::SourceLocation {
pointer: pointer.clone(),
},
);
properties.insert(
name.to_owned(),
swagger_parameter_schema(&Value::Null, parameter)
.unwrap_or_else(|| Value::Object(serde_json::Map::new())),
);
if parameter
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false)
{
required.push(Value::String(name.to_owned()));
}
}
if properties.is_empty() {
return None;
}
let mut schema = serde_json::Map::new();
schema.insert("type".to_owned(), Value::String("object".to_owned()));
schema.insert("properties".to_owned(), Value::Object(properties));
if !required.is_empty() {
schema.insert("required".to_owned(), Value::Array(required));
}
Some((
Value::Object(schema),
root_pointer.map(|pointer| crate::rest::model::SourceLocation { pointer }),
property_locations,
))
}
fn supported_request_content_type(content_type: &str) -> bool {
content_type == "application/x-www-form-urlencoded"
|| content_type == "multipart/form-data"
|| content_type == "application/json"
|| content_type.ends_with("+json")
}
fn effective_media_types(
root: &Value,
operation: &Value,
field: &str,
default: &str,
) -> Vec<String> {
operation
.get(field)
.or_else(|| root.get(field))
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.filter(|items| !items.is_empty())
.unwrap_or_else(|| vec![default.to_owned()])
}
fn swagger_response_variants(
root: &Value,
operation: &Value,
operation_pointer: &str,
method: HttpMethod,
) -> Vec<RestResponseVariant> {
let Some(responses) = operation.get("responses").and_then(Value::as_object) else {
return Vec::new();
};
let produces = effective_media_types(root, operation, "produces", "application/json");
let supported_produces = produces
.iter()
.filter(|content_type| supported_response_content_type(content_type))
.cloned()
.collect::<Vec<_>>();
let mut variants = responses
.iter()
.filter_map(|(code, response)| {
let status_code = code
.parse::<u16>()
.ok()
.filter(|code| (200..300).contains(code))?;
let schema = response.get("schema").cloned();
let pointer = format!(
"{operation_pointer}/responses/{}",
code.replace('~', "~0").replace('/', "~1")
);
if method == HttpMethod::Head {
return Some(vec![RestResponseVariant {
status_code,
content_type: None,
schema: None,
source_location: crate::rest::model::SourceLocation { pointer },
schema_source_location: None,
}]);
}
if schema.is_none() {
return Some(vec![RestResponseVariant {
status_code,
content_type: None,
schema,
source_location: crate::rest::model::SourceLocation { pointer },
schema_source_location: None,
}]);
}
if supported_produces.is_empty() {
return Some(Vec::new());
}
Some(
supported_produces
.iter()
.map(|content_type| RestResponseVariant {
status_code,
content_type: Some(content_type.clone()),
schema: schema.clone(),
source_location: crate::rest::model::SourceLocation {
pointer: pointer.clone(),
},
schema_source_location: Some(crate::rest::model::SourceLocation {
pointer: format!("{pointer}/schema"),
}),
})
.collect(),
)
})
.flatten()
.collect::<Vec<_>>();
variants.sort_by(|left, right| {
(left.status_code, left.content_type.as_deref().unwrap_or("")).cmp(&(
right.status_code,
right.content_type.as_deref().unwrap_or(""),
))
});
variants
}
fn supported_response_content_type(content_type: &str) -> bool {
content_type == "application/json" || content_type.ends_with("+json")
}
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")
),
},
)
})
}