use std::collections::{BTreeMap, BTreeSet}; use serde_json::Value; use thiserror::Error; use crate::rest::{ model::{ CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding, ImportFindingSeverity, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION, NormalizationConfig, NormalizedApiMetadata, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION, RestImportDocument, SourceDigest, SourceIdentity, SourceLocation, SourceSyntax, }, openapi3, swagger2, }; use super::decode_budget; use super::normalize_coverage; use super::normalize_limits; #[derive(Debug, Error, PartialEq, Eq)] pub enum ImportParseError { #[error("document is not valid YAML or JSON")] InvalidDocument, #[error("unsupported OpenAPI document")] UnsupportedDocument, #[error("OpenAPI document exceeds normalization limits")] LimitExceeded, #[error("OpenAPI document contains no supported operations")] NoMethods, } pub fn preview_document(document: &str) -> Result { let digest = SourceDigest::parse("0".repeat(64)).expect("fixed digest is valid"); let ir = normalize_verified_document(document, digest, &NormalizationConfig::default())?; Ok(preview_from_ir(&ir)) } /// Enumerates reference URIs without resolving or performing I/O. Intended /// for an orchestration layer that materializes a bounded immutable bundle. pub fn reference_uris( document: &str, config: &NormalizationConfig, ) -> Result, ImportParseError> { super::reference::reference_uris(document, config) } /// Enumerates references in an already materialized external document. This /// keeps the historical primary-document API intact while applying the /// external-document byte limit at an explicit call site. pub fn external_reference_uris( document: &str, config: &NormalizationConfig, ) -> Result, ImportParseError> { super::reference::external_reference_uris(document, config) } /// Compatibility projection for jobs created before `NormalizedIr`. It is /// deliberately isolated from the v2 pipeline and may be removed only after /// the import-job TTL has elapsed. pub fn preview_document_legacy_v1(document: &str) -> Result { let root = decode_legacy_v1(document)?; let mut parsed = match root.get("openapi") { Some(_) => openapi3::parse_document_legacy_v1(&root)?, None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => { swagger2::parse_document_legacy_v1(&root)? } None => return Err(ImportParseError::UnsupportedDocument), }; for operation in &mut parsed.operations { for parameter in &mut operation.parameters { if let Some(schema) = parameter.schema.take() { parameter.schema = Some(resolve_local_ref(&root, &schema, 0)); } } if let Some(schema) = operation.request_body_schema.take() { operation.request_body_schema = Some(resolve_local_ref(&root, &schema, 0)); } if let Some(schema) = operation.response_schema.take() { operation.response_schema = Some(resolve_local_ref(&root, &schema, 0)); } } Ok(preview_from_document(parsed)) } fn decode_legacy_v1(document: &str) -> Result { let config = NormalizationConfig::default(); if document.len() > config.max_bytes || normalize_limits::alias_count(document) > config.max_aliases { return Err(ImportParseError::LimitExceeded); } decode_budget::preflight_primary(document, &config)?; let root = decode(document)?; validate_value_limits(&root, &config)?; Ok(root) } pub fn normalize_verified_document( document: &str, digest: SourceDigest, config: &NormalizationConfig, ) -> Result { normalize_verified_bundle(document, digest, &[], config) } /// Rejects source documents containing credential-like literals before a /// caller persists their original bytes. Accepted source bytes remain verbatim. pub fn validate_document_source_safe( document: &str, config: &NormalizationConfig, ) -> Result<(), ImportParseError> { config .validate_versions() .map_err(|_| ImportParseError::UnsupportedDocument)?; if document.len() > config.max_bytes || normalize_limits::alias_count(document) > config.max_aliases { return Err(ImportParseError::LimitExceeded); } decode_budget::preflight_primary(document, config)?; let mut root = super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?; validate_value_limits(&root, config)?; let mut findings = Vec::new(); let mut locations = Vec::new(); super::metadata_findings::redact_secret_like_literals( &mut root, "", &mut findings, &mut locations, ); if findings.is_empty() { Ok(()) } else { Err(ImportParseError::InvalidDocument) } } /// Normalizes a verified primary document together with immutable external /// snapshots. This function is pure: callers must perform all URL policy, /// fetching, artifact persistence and digest verification beforehand. pub fn normalize_verified_bundle( document: &str, digest: SourceDigest, snapshots: &[ExternalDocumentSnapshot], config: &NormalizationConfig, ) -> Result { config .validate_versions() .map_err(|_| ImportParseError::UnsupportedDocument)?; if document.len() > config.max_bytes || normalize_limits::alias_count(document) > config.max_aliases { return Err(ImportParseError::LimitExceeded); } if snapshots.len() > config.max_reference_documents { return Err(ImportParseError::LimitExceeded); } for snapshot in snapshots { if snapshot.document.len() > config.max_external_document_bytes || normalize_limits::alias_count(&snapshot.document) > config.max_aliases { return Err(ImportParseError::LimitExceeded); } } decode_budget::preflight_bundle(document, snapshots, config)?; let source_syntax = if serde_json::from_str::(document).is_ok() { SourceSyntax::Json } else { SourceSyntax::Yaml }; let root = super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?; validate_value_limits(&root, config)?; for snapshot in snapshots { if snapshot.document.len() > config.max_external_document_bytes { return Err(ImportParseError::LimitExceeded); } } let resolution = super::reference::resolve(root, digest.clone(), snapshots, config)?; let mut root = resolution.root; validate_value_limits(&root, config)?; let mut literal_findings = Vec::new(); let mut literal_locations = Vec::new(); super::metadata_findings::redact_secret_like_literals( &mut root, "", &mut literal_findings, &mut literal_locations, ); let mut parsed = match root.get("openapi").and_then(Value::as_str) { Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?, Some(_) => return Err(ImportParseError::UnsupportedDocument), None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => { swagger2::parse_document(&root)? } None => return Err(ImportParseError::UnsupportedDocument), }; parsed.findings.extend(literal_findings); parsed.internal_finding_locations.extend(literal_locations); if parsed.operations.is_empty() && !parsed .findings .iter() .any(|finding| finding.code == "unsupported_http_method") { return Err(ImportParseError::NoMethods); } canonicalize( parsed, digest, config, root, source_syntax, resolution.graph, resolution.findings, ) } pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview { super::normalize_projection::preview_from_ir(ir) } fn preview_from_document(document: RestImportDocument) -> ImportPreview { super::normalize_projection::preview_from_document(document) } pub(super) fn decode(document: &str) -> Result { if let Ok(json) = serde_json::from_str(document) { return Ok(json); } let yaml: serde_yaml::Value = serde_yaml::from_str(document).map_err(|_| ImportParseError::InvalidDocument)?; serde_json::to_value(yaml).map_err(|_| ImportParseError::InvalidDocument) } fn supported_oas_version(version: &str) -> bool { ["3.0.", "3.1."].into_iter().any(|prefix| { version.strip_prefix(prefix).is_some_and(|patch| { !patch.is_empty() && patch.bytes().all(|byte| byte.is_ascii_digit()) }) }) } fn canonicalize( document: RestImportDocument, digest: SourceDigest, config: &NormalizationConfig, root: Value, source_syntax: SourceSyntax, reference_graph: crate::rest::model::ResolvedReferenceGraph, resolution_findings: Vec, ) -> Result { let source = ImportSourcePreview { format: document.format, version: document.version, title: document.title, servers: document.servers, }; let version = source.version.as_deref().unwrap_or("unknown"); let mut coverage = Vec::new(); let source_tree = normalize_coverage::canonical_source_tree(&root, "", &mut coverage); let unresolved_references = normalize_coverage::references_from_source_tree(&source_tree); coverage.extend(unresolved_references.iter().map(|reference| CoverageEntry { construct_id: reference.construct_id.clone(), location: reference.location.clone(), disposition: CoverageDisposition::Mapped, })); coverage.push(CoverageEntry { construct_id: "document".to_owned(), location: SourceLocation { pointer: String::new(), }, disposition: CoverageDisposition::Mapped, }); coverage.extend(normalize_coverage::server_coverage( &source, &source_tree, version, )?); let mut covered_paths = BTreeSet::new(); let mut covered_parameters = BTreeSet::new(); let internal_finding_locations = document.internal_finding_locations.clone(); let mut findings = document .findings .into_iter() .enumerate() .map(|(index, finding)| { let location = internal_finding_locations.get(index).cloned().flatten(); NormalizedFinding { code: finding.code.clone(), severity: finding.severity, message: finding.message, construct_id: location .as_ref() .map(|location| { if location.pointer.is_empty() { "document".to_owned() } else { format!("{version}:{}", location.pointer) } }) .unwrap_or_else(|| "document".to_owned()), location: location.unwrap_or(SourceLocation { pointer: String::new(), }), operation_key: finding.operation_key, } }) .collect::>(); findings.extend(resolution_findings); let mut operations = document .operations .into_iter() .map(|operation| { let method = method_name(operation.method).to_ascii_lowercase(); let pointer = format!( "/paths/{}/{}", normalize_coverage::escape_pointer(&operation.path), method ); let stable_id = format!("{version}:{method}:{pointer}"); let location = SourceLocation { pointer: pointer.clone(), }; let mut operation_findings = Vec::new(); if covered_paths.insert(operation.path.clone()) { coverage.push(CoverageEntry { construct_id: format!("{version}:path:{}", operation.path), location: SourceLocation { pointer: format!( "/paths/{}", normalize_coverage::escape_pointer(&operation.path) ), }, disposition: CoverageDisposition::Mapped, }); } if operation .operation_id .as_deref() .is_some_and(|value| !value.trim().is_empty()) { coverage.push(CoverageEntry { construct_id: format!("{stable_id}:operation_id"), location: SourceLocation { pointer: format!("{pointer}/operationId"), }, disposition: CoverageDisposition::Mapped, }); } else { operation_findings.push(NormalizedFinding { code: "missing_operation_id".to_owned(), severity: ImportFindingSeverity::Warning, message: "У метода нет operationId.".to_owned(), construct_id: format!("{stable_id}:operation_id"), location: SourceLocation { pointer: format!("{pointer}/operationId"), }, operation_key: Some(operation.key.clone()), }); coverage.push(CoverageEntry { construct_id: format!("{stable_id}:operation_id"), location: SourceLocation { pointer: format!("{pointer}/operationId"), }, disposition: CoverageDisposition::Finding, }); } for (index, location) in normalize_coverage::tag_locations(&root, &pointer, &operation.tags)? .into_iter() .enumerate() { coverage.push(CoverageEntry { construct_id: format!("{stable_id}:tag:{index}"), location, disposition: CoverageDisposition::Mapped, }); } operation_findings.extend(operation.findings.iter().enumerate().map( |(index, finding)| { let finding_location = operation .internal_finding_locations .get(index) .cloned() .unwrap_or_else(|| location.clone()); NormalizedFinding { code: finding.code.clone(), severity: finding.severity.clone(), message: finding.message.clone(), construct_id: if finding_location == location { stable_id.clone() } else { format!("{version}:{}", finding_location.pointer) }, location: finding_location, operation_key: Some(operation.key.clone()), } }, )); let parameters = operation .parameters .into_iter() .map(|parameter| { let parameter_pointer = parameter.source_location.pointer; let parameter_id = format!( "parameter:{}", normalize_coverage::escape_pointer(¶meter_pointer) ); if covered_parameters.insert(parameter_id.clone()) { coverage.push(CoverageEntry { construct_id: parameter_id.clone(), location: SourceLocation { pointer: parameter_pointer.clone(), }, disposition: CoverageDisposition::Mapped, }); } NormalizedParameter { name: parameter.name, location: parameter.location, required: parameter.required, description: parameter.description, schema: parameter.schema.as_ref().map(|schema| { normalize_coverage::typed_schema( schema, parameter .schema_source_location .as_ref() .map(|location| location.pointer.as_str()) .unwrap_or(&format!("{parameter_pointer}/schema")), &format!("{parameter_id}:schema"), &mut coverage, ) }), construct_id: parameter_id, source_location: SourceLocation { pointer: parameter_pointer, }, } }) .collect::>(); let request_body_schema = operation.request_body_schema.as_ref().map(|schema| { let schema_location = operation .request_body_schema_location .as_ref() .cloned() .unwrap_or(SourceLocation { pointer: format!("{pointer}/requestBody"), }); normalize_coverage::typed_schema( schema, &schema_location.pointer, &format!( "{stable_id}:request:{}", normalize_coverage::escape_pointer(&schema_location.pointer) ), &mut coverage, ) }); let response_schema = operation.response_schema.as_ref().map(|schema| { let schema_location = operation .response_schema_location .as_ref() .cloned() .unwrap_or(SourceLocation { pointer: format!("{pointer}/responses"), }); normalize_coverage::typed_schema( schema, &schema_location.pointer, &format!( "{stable_id}:response:{}", normalize_coverage::escape_pointer(&schema_location.pointer) ), &mut coverage, ) }); let request_body_variants = operation .request_body_variants .iter() .map(|variant| NormalizedRequestBodyVariant { content_type: variant.content_type.clone(), required: variant.required, schema: variant.schema.as_ref().map(|schema| { let schema_location = variant .schema_source_location .as_ref() .unwrap_or(&variant.source_location); normalize_coverage::typed_schema_with_property_locations( schema, &schema_location.pointer, &variant.schema_property_source_locations, &mut coverage, ) }), multipart_field_mime_types: variant.multipart_field_mime_types.clone(), source_location: variant.source_location.clone(), }) .collect(); let response_variants = operation .response_variants .iter() .map(|variant| NormalizedResponseVariant { status_code: variant.status_code, content_type: variant.content_type.clone(), schema: variant.schema.as_ref().map(|schema| { let schema_location = variant .schema_source_location .as_ref() .unwrap_or(&variant.source_location); normalize_coverage::typed_schema( schema, &schema_location.pointer, &format!( "{stable_id}:response_variant:{}", normalize_coverage::escape_pointer(&schema_location.pointer) ), &mut coverage, ) }), source_location: variant.source_location.clone(), }) .collect(); if normalize_coverage::has_reference_schema(request_body_schema.as_ref()) || normalize_coverage::has_reference_schema(response_schema.as_ref()) || parameters.iter().any(|parameter| { normalize_coverage::has_reference_schema(parameter.schema.as_ref()) }) { operation_findings.push(NormalizedFinding { code: "unresolved_reference".to_owned(), severity: ImportFindingSeverity::Error, message: "Ссылка сохранена в NormalizedIR и будет разрешена отдельным этапом." .to_owned(), construct_id: stable_id.clone(), location: location.clone(), operation_key: Some(operation.key.clone()), }); } coverage.push(CoverageEntry { construct_id: stable_id.clone(), location: location.clone(), disposition: CoverageDisposition::Mapped, }); Ok::<_, ImportParseError>(NormalizedOperation { stable_id, location, key: operation.key, method: operation.method, path: operation.path, operation_id: operation.operation_id, summary: operation.summary, description: operation.description, tags: operation.tags, parameters, request_body_schema, response_schema, request_body_variants, response_variants, servers: operation.servers, security_requirements: operation.security_requirements, security_schemes: document.security_schemes.clone(), findings: operation_findings, }) }) .collect::, _>>()?; operations.sort_by(|left, right| { ( left.path.as_str(), method_rank(left.method), left.location.pointer.as_str(), ) .cmp(&( right.path.as_str(), method_rank(right.method), right.location.pointer.as_str(), )) }); let mut document_findings = Vec::with_capacity(findings.len()); for mut finding in findings.drain(..) { let resolution_finding = matches!( finding.code.as_str(), "external_reference_disabled" | "reference_target_missing" | "reference_uri_malformed" | "external_reference_unavailable" | "reference_type_mismatch" | "reference_graph_limit" | "all_of_conflict" | "unsupported_composition" | "unsupported_discriminator" ); let target = resolution_finding .then(|| { operations.iter_mut().find(|operation| { !finding.location.pointer.is_empty() && (finding.location.pointer == operation.location.pointer || finding .location .pointer .starts_with(&format!("{}/", operation.location.pointer))) }) }) .flatten(); if let Some(operation) = target { finding.operation_key = Some(operation.key.clone()); operation.findings.push(finding); } else { document_findings.push(finding); } } findings = document_findings; for operation in &mut operations { sort_normalized_findings(&mut operation.findings); } let mut operation_id_counts = BTreeMap::new(); for operation in &operations { if let Some(operation_id) = operation .operation_id .as_deref() .filter(|value| !value.trim().is_empty()) { *operation_id_counts .entry(operation_id.to_owned()) .or_insert(0usize) += 1; } } for operation in &mut operations { if let Some(operation_id) = operation .operation_id .as_deref() .filter(|value| !value.trim().is_empty()) && operation_id_counts[operation_id] > 1 { operation.findings.push(NormalizedFinding { code: "duplicate_operation_id".to_owned(), severity: ImportFindingSeverity::Warning, message: "operationId повторяется в документе.".to_owned(), construct_id: format!("{}:operation_id", operation.stable_id), location: SourceLocation { pointer: format!("{}/operationId", operation.location.pointer), }, operation_key: Some(operation.key.clone()), }); } sort_normalized_findings(&mut operation.findings); } // References left in the finite projection are precisely failures which // the bounded resolver could not safely expand. Keep a blocker at the // closest affected operation; unrelated operations remain actionable. findings.extend( unresolved_references .iter() .filter(|reference| { !operations.iter().any(|operation| { operation .parameters .iter() .filter_map(|parameter| parameter.schema.as_ref()) .chain(operation.request_body_schema.iter()) .chain(operation.response_schema.iter()) .chain( operation .request_body_variants .iter() .filter_map(|variant| variant.schema.as_ref()), ) .chain( operation .response_variants .iter() .filter_map(|variant| variant.schema.as_ref()), ) .any(|schema| schema_contains_reference(schema, &reference.location)) }) }) .map(|reference| NormalizedFinding { code: "unresolved_reference".to_owned(), severity: ImportFindingSeverity::Error, message: "Ссылка требует разрешения перед применением импорта.".to_owned(), construct_id: reference.construct_id.clone(), location: reference.location.clone(), operation_key: None, }), ); sort_normalized_findings(&mut findings); for finding in findings.iter().chain( operations .iter() .flat_map(|operation| operation.findings.iter()), ) { if !coverage.iter().any(|entry| { entry.construct_id == finding.construct_id && entry.location == finding.location && entry.disposition == CoverageDisposition::Mapped }) { coverage.push(CoverageEntry { construct_id: finding.construct_id.clone(), location: finding.location.clone(), disposition: CoverageDisposition::Finding, }); } } coverage.sort_by(|left, right| { ( left.construct_id.as_str(), left.location.pointer.as_str(), coverage_disposition_rank(&left.disposition), ) .cmp(&( right.construct_id.as_str(), right.location.pointer.as_str(), coverage_disposition_rank(&right.disposition), )) }); coverage.dedup(); let ir = NormalizedIr { normalizer_version: config.normalizer_version.clone(), projection_version: config.projection_version.clone(), source_identity: SourceIdentity { digest }, source_syntax, source_tree, metadata: NormalizedApiMetadata { title: source.title.clone(), version: root .pointer("/info/version") .and_then(Value::as_str) .map(ToOwned::to_owned), description: root .pointer("/info/description") .and_then(Value::as_str) .map(ToOwned::to_owned), }, base_path_candidates: root .get("basePath") .and_then(Value::as_str) .map(|value| vec![value.to_owned()]) .unwrap_or_default(), paths: normalize_coverage::paths_from_operations(&operations, version), unresolved_references, reference_graph, source, security_schemes: document.security_schemes, operations, findings, coverage, }; normalize_coverage::validate_coverage(&ir)?; Ok(ir) } pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> { if !((ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION) || (ir.normalizer_version == crate::rest::model::HISTORICAL_NORMALIZER_VERSION && ir.projection_version == crate::rest::model::HISTORICAL_PROJECTION_VERSION)) { return Err(ImportParseError::InvalidDocument); } validate_reference_graph(ir)?; normalize_coverage::validate_coverage(ir) } fn validate_reference_graph(ir: &NormalizedIr) -> Result<(), ImportParseError> { if ir .reference_graph .dependency_digests .windows(2) .any(|pair| pair[0] >= pair[1]) { return Err(ImportParseError::InvalidDocument); } let allowed = ir .reference_graph .dependency_digests .iter() .chain(std::iter::once(&ir.source_identity.digest)) .map(SourceDigest::as_str) .collect::>(); let edges = &ir.reference_graph.edges; if edges .windows(2) .any(|pair| reference_edge_key(&pair[0]) >= reference_edge_key(&pair[1])) || edges.iter().any(|edge| { !allowed.contains(edge.source.snapshot_digest.as_str()) || !allowed.contains(edge.target.snapshot_digest.as_str()) || !(edge.source.location.pointer.is_empty() || edge.source.location.pointer.starts_with('/')) || !(edge.target.location.pointer.is_empty() || edge.target.location.pointer.starts_with('/')) }) { return Err(ImportParseError::InvalidDocument); } Ok(()) } fn reference_edge_key( edge: &crate::rest::model::ResolvedReferenceEdge, ) -> (&str, &str, &str, &str, bool) { ( edge.source.snapshot_digest.as_str(), edge.source.location.pointer.as_str(), edge.target.snapshot_digest.as_str(), edge.target.location.pointer.as_str(), edge.recursive, ) } fn coverage_disposition_rank(disposition: &CoverageDisposition) -> u8 { match disposition { CoverageDisposition::Mapped => 0, CoverageDisposition::Finding => 1, } } fn schema_contains_reference(schema: &NormalizedSchema, location: &SourceLocation) -> bool { match &schema.kind { NormalizedSchemaKind::Reference { reference } => reference.location == *location, NormalizedSchemaKind::Object { properties, .. } => properties .values() .any(|schema| schema_contains_reference(schema, location)), NormalizedSchemaKind::Array { items, .. } => items .as_deref() .is_some_and(|schema| schema_contains_reference(schema, location)), NormalizedSchemaKind::Composition { variants, .. } => variants .iter() .any(|schema| schema_contains_reference(schema, location)), _ => false, } } pub(super) fn validate_value_limits( value: &Value, config: &NormalizationConfig, ) -> Result<(), ImportParseError> { fn visit( value: &Value, depth: usize, nodes: &mut usize, config: &NormalizationConfig, ) -> Result<(), ImportParseError> { *nodes += 1; if depth > config.max_depth || *nodes > config.max_nodes { return Err(ImportParseError::LimitExceeded); } match value { Value::String(text) if text.len() > config.max_scalar_bytes => { Err(ImportParseError::LimitExceeded) } Value::Array(items) => { if items.len() > config.max_collection_items { return Err(ImportParseError::LimitExceeded); } for item in items { visit(item, depth + 1, nodes, config)?; } Ok(()) } Value::Object(object) => { if object.len() > config.max_collection_items { return Err(ImportParseError::LimitExceeded); } for (key, item) in object { if key.len() > config.max_scalar_bytes { return Err(ImportParseError::LimitExceeded); } visit(item, depth + 1, nodes, config)?; } Ok(()) } _ => Ok(()), } } visit(value, 0, &mut 0, config) } fn method_name(method: crank_core::HttpMethod) -> &'static str { match method { crank_core::HttpMethod::Get => "GET", crank_core::HttpMethod::Post => "POST", crank_core::HttpMethod::Put => "PUT", crank_core::HttpMethod::Patch => "PATCH", crank_core::HttpMethod::Delete => "DELETE", crank_core::HttpMethod::Head => "HEAD", crank_core::HttpMethod::Options => "OPTIONS", } } fn method_rank(method: crank_core::HttpMethod) -> u8 { match method { crank_core::HttpMethod::Get => 0, crank_core::HttpMethod::Post => 1, crank_core::HttpMethod::Put => 2, crank_core::HttpMethod::Patch => 3, crank_core::HttpMethod::Delete => 4, crank_core::HttpMethod::Head => 5, crank_core::HttpMethod::Options => 6, } } fn severity_rank(severity: &ImportFindingSeverity) -> u8 { match severity { ImportFindingSeverity::Error => 0, ImportFindingSeverity::Warning => 1, ImportFindingSeverity::Info => 2, } } pub(super) fn sort_findings(findings: &mut [ImportFinding]) { findings.sort_by(|left, right| { ( severity_rank(&left.severity), left.operation_key.as_deref().unwrap_or(""), left.code.as_str(), ) .cmp(&( severity_rank(&right.severity), right.operation_key.as_deref().unwrap_or(""), right.code.as_str(), )) }); } fn sort_normalized_findings(findings: &mut [NormalizedFinding]) { findings.sort_by(|left, right| { ( severity_rank(&left.severity), left.construct_id.as_str(), left.code.as_str(), ) .cmp(&( severity_rank(&right.severity), right.construct_id.as_str(), right.code.as_str(), )) }); } // Kept private for pending pre-v2 job replays. New normalization never calls // it: refs are represented above and are resolved only in Story 2.3. #[allow(dead_code)] pub(crate) fn resolve_local_ref(root: &Value, value: &Value, depth: usize) -> Value { if depth > 12 { return value.clone(); } if let Some(reference) = value.get("$ref").and_then(Value::as_str) && let Some(resolved) = pointer(root, reference) { return resolve_local_ref(root, resolved, depth + 1); } match value { Value::Object(map) => Value::Object( map.iter() .map(|(key, item)| (key.clone(), resolve_local_ref(root, item, depth + 1))) .collect(), ), Value::Array(items) => Value::Array( items .iter() .map(|item| resolve_local_ref(root, item, depth + 1)) .collect(), ), _ => value.clone(), } } fn pointer<'a>(root: &'a Value, reference: &str) -> Option<&'a Value> { if !reference.starts_with("#/") { return None; } let mut current = root; for part in reference.trim_start_matches("#/").split('/') { current = current.get(part.replace("~1", "/").replace("~0", "~"))?; } Some(current) }