feat(import): resolve references and schema composition
This commit is contained in:
1 parent
6c2a3712d8
commit
55209a9bbc
46 files changed
+4848
-437
No files matched your search
@@ -5,13 +5,13 @@ use thiserror::Error;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
CoverageDisposition, CoverageEntry, ImportFinding, ImportFindingSeverity,
|
||||
ImportGroupPreview, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedApiMetadata, NormalizedFinding, NormalizedIr,
|
||||
NormalizedLiteral, NormalizedOperation, NormalizedParameter, NormalizedScalarKind,
|
||||
NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION, RestImportDocument,
|
||||
RestImportOperation, RestImportParameter, SourceDigest, SourceIdentity, SourceLocation,
|
||||
SourceSyntax,
|
||||
CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding,
|
||||
ImportFindingSeverity, ImportGroupPreview, ImportPreview, ImportSourcePreview,
|
||||
NORMALIZER_VERSION, NormalizationConfig, NormalizedApiMetadata, NormalizedFinding,
|
||||
NormalizedIr, NormalizedLiteral, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedScalarKind, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
RestImportDocument, RestImportOperation, RestImportParameter, SourceDigest, SourceIdentity,
|
||||
SourceLocation, SourceSyntax,
|
||||
},
|
||||
openapi3,
|
||||
payload::candidate_from_operation,
|
||||
@@ -39,6 +39,25 @@ pub fn preview_document(document: &str) -> Result<ImportPreview, ImportParseErro
|
||||
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<Vec<String>, 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<Vec<String>, 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.
|
||||
@@ -83,6 +102,18 @@ pub fn normalize_verified_document(
|
||||
document: &str,
|
||||
digest: SourceDigest,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
normalize_verified_bundle(document, digest, &[], config)
|
||||
}
|
||||
|
||||
/// 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<NormalizedIr, ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
@@ -99,6 +130,14 @@ pub fn normalize_verified_document(
|
||||
};
|
||||
let root = decode(document)?;
|
||||
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 root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
||||
@@ -112,7 +151,15 @@ pub fn normalize_verified_document(
|
||||
if parsed.operations.is_empty() {
|
||||
return Err(ImportParseError::NoMethods);
|
||||
}
|
||||
canonicalize(parsed, digest, config, root, source_syntax)
|
||||
canonicalize(
|
||||
parsed,
|
||||
digest,
|
||||
config,
|
||||
root,
|
||||
source_syntax,
|
||||
resolution.graph,
|
||||
resolution.findings,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
@@ -202,6 +249,8 @@ fn canonicalize(
|
||||
config: &NormalizationConfig,
|
||||
root: Value,
|
||||
source_syntax: SourceSyntax,
|
||||
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
||||
resolution_findings: Vec<NormalizedFinding>,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
@@ -260,6 +309,7 @@ fn canonicalize(
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
findings.extend(resolution_findings);
|
||||
let mut operations = document
|
||||
.operations
|
||||
.into_iter()
|
||||
@@ -466,6 +516,40 @@ fn canonicalize(
|
||||
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);
|
||||
}
|
||||
@@ -501,10 +585,9 @@ fn canonicalize(
|
||||
}
|
||||
sort_normalized_findings(&mut operation.findings);
|
||||
}
|
||||
// Resolution is deliberately deferred. References already represented by
|
||||
// an operation schema use that operation's blocker; all other references
|
||||
// need a document-level blocker so omitted object-level semantics can
|
||||
// never reach Apply silently.
|
||||
// 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()
|
||||
@@ -529,7 +612,11 @@ fn canonicalize(
|
||||
}),
|
||||
);
|
||||
sort_normalized_findings(&mut findings);
|
||||
for finding in &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
|
||||
@@ -580,6 +667,7 @@ fn canonicalize(
|
||||
.unwrap_or_default(),
|
||||
paths: normalize_coverage::paths_from_operations(&operations, version),
|
||||
unresolved_references,
|
||||
reference_graph,
|
||||
source,
|
||||
operations,
|
||||
findings,
|
||||
@@ -593,9 +681,56 @@ pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError>
|
||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != 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::<BTreeSet<_>>();
|
||||
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,
|
||||
@@ -650,7 +785,10 @@ fn legacy_schema_value(schema: &NormalizedSchema) -> Value {
|
||||
let mut value = match &schema.kind {
|
||||
NormalizedSchemaKind::Reference { reference } => serde_json::json!({"$ref": reference.uri}),
|
||||
NormalizedSchemaKind::Composition { operator, variants } => {
|
||||
serde_json::json!({operator: variants.iter().map(legacy_schema_value).collect::<Vec<_>>() })
|
||||
serde_json::json!({
|
||||
operator: variants.iter().map(legacy_schema_value).collect::<Vec<_>>(),
|
||||
"x-crank-lossless-composition": true,
|
||||
})
|
||||
}
|
||||
NormalizedSchemaKind::Object {
|
||||
properties,
|
||||
@@ -718,7 +856,7 @@ fn schema_contains_reference(schema: &NormalizedSchema, location: &SourceLocatio
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_value_limits(
|
||||
pub(super) fn validate_value_limits(
|
||||
value: &Value,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
|
||||
Reference in new issue
Block a user