story 2-12-preview-partial-mode: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
d1ba0bd0e4
commit
ab35d67177
56 files changed
+5801
-376
No files matched your search
@@ -6,8 +6,9 @@ use crank_core::{
|
||||
SecretStatus, ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
|
||||
};
|
||||
use crank_import::rest::{
|
||||
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, NORMALIZER_VERSION,
|
||||
PROJECTION_VERSION, operation_draft_from_candidate, validate_document_source_safe,
|
||||
ImportFinding, ImportFindingSeverity, ImportNameConflict, ImportOperationCandidate,
|
||||
NORMALIZER_VERSION, PROJECTION_VERSION, operation_draft_from_candidate,
|
||||
validate_document_source_safe,
|
||||
};
|
||||
use crank_registry::{
|
||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||
@@ -27,7 +28,8 @@ use crate::{
|
||||
AdminService, OpenApiImportAuthProfileChoice, OpenApiImportCreatePayload,
|
||||
OpenApiImportCreateResponse, OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
|
||||
OpenApiImportPlanCandidateView, OpenApiImportPlanCounts, OpenApiImportPlanCreatePayload,
|
||||
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision, OpenApiImportPreviewResponse,
|
||||
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision,
|
||||
OpenApiImportPlanRevalidationResponse, OpenApiImportPreviewResponse,
|
||||
OpenApiImportSecurityProfileChoice, OpenApiImportSkippedOperation, OpenApiUpload,
|
||||
OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
||||
},
|
||||
@@ -52,7 +54,8 @@ use verified_preview::{
|
||||
const IMPORT_JOB_TTL_HOURS: i64 = 24;
|
||||
const OPENAPI_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
const OPENAPI_PARSE_CONCURRENCY: usize = 4;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 512;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
|
||||
const OPENAPI_SUPPORT_MATRIX_VERSION: &str = "1.0.2";
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_SERVER_URL_BYTES: usize = 8_192;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
@@ -60,6 +63,132 @@ const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
|
||||
static OPENAPI_PARSE_SLOTS: tokio::sync::Semaphore =
|
||||
tokio::sync::Semaphore::const_new(OPENAPI_PARSE_CONCURRENCY);
|
||||
|
||||
fn preview_name_conflicts(
|
||||
preview: &crank_import::rest::ImportPreview,
|
||||
catalog_names: &[String],
|
||||
) -> Vec<ImportNameConflict> {
|
||||
let operations = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| group.operations.iter())
|
||||
.collect::<Vec<_>>();
|
||||
let mut operation_ids = BTreeMap::<&str, usize>::new();
|
||||
for candidate in &operations {
|
||||
if let Some(id) = candidate.operation_id.as_deref() {
|
||||
*operation_ids.entry(id).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let occupied = catalog_names
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut proposals = catalog_names.iter().cloned().collect::<BTreeSet<_>>();
|
||||
proposals.extend(
|
||||
operations
|
||||
.iter()
|
||||
.map(|candidate| candidate.suggested_name.clone()),
|
||||
);
|
||||
let mut conflicts = Vec::new();
|
||||
for candidate in operations {
|
||||
let duplicate = candidate
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.is_some_and(|id| operation_ids.get(id).is_some_and(|count| *count > 1));
|
||||
let invalid = candidate.operation_id.as_deref().is_some_and(|id| {
|
||||
id.is_empty()
|
||||
|| id.len() > MAX_IMPORT_PLAN_NAME_BYTES
|
||||
|| !id.bytes().enumerate().all(|(index, ch)| {
|
||||
ch.is_ascii_alphabetic() || ch == b'_' || (index > 0 && ch.is_ascii_digit())
|
||||
})
|
||||
});
|
||||
let taken = occupied.contains(candidate.suggested_name.as_str());
|
||||
if !duplicate && !invalid && !taken {
|
||||
continue;
|
||||
}
|
||||
let base = candidate
|
||||
.suggested_name
|
||||
.chars()
|
||||
.take(240)
|
||||
.collect::<String>();
|
||||
let proposal = next_available_name(&base, &mut proposals);
|
||||
for conflict_type in [
|
||||
duplicate.then_some("duplicate_name"),
|
||||
invalid.then_some("invalid_name"),
|
||||
taken.then_some("taken_name"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
conflicts.push(ImportNameConflict {
|
||||
operation_key: candidate.key.clone(),
|
||||
conflict_type: conflict_type.to_owned(),
|
||||
proposed_name: proposal.clone(),
|
||||
source_location: candidate.source_location.as_ref().map(|location| {
|
||||
crank_import::rest::SourceLocation {
|
||||
pointer: if candidate.operation_id.is_some() {
|
||||
format!("{}/operationId", location.pointer)
|
||||
} else {
|
||||
location.pointer.clone()
|
||||
},
|
||||
}
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
conflicts
|
||||
}
|
||||
|
||||
fn next_available_name(base: &str, occupied: &mut BTreeSet<String>) -> String {
|
||||
// A catalog may contain more names than the preview candidate cap. With
|
||||
// occupied.len() + 1 suffixes, at least one candidate must be free.
|
||||
(2..=occupied.len() + 2)
|
||||
.map(|index| format!("{base}_{index}"))
|
||||
.find(|name| occupied.insert(name.clone()))
|
||||
.expect("finite occupied names always leave a free suffix")
|
||||
}
|
||||
|
||||
fn attach_preview_readiness(
|
||||
preview: &mut crank_import::rest::ImportPreview,
|
||||
choices: &[OpenApiImportSecurityProfileChoice],
|
||||
) {
|
||||
let document_blocked = preview.findings.iter().any(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none()
|
||||
});
|
||||
for candidate in preview
|
||||
.groups
|
||||
.iter_mut()
|
||||
.flat_map(|group| group.operations.iter_mut())
|
||||
{
|
||||
let blocked = document_blocked
|
||||
|| candidate
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.severity == ImportFindingSeverity::Error);
|
||||
let alternatives = &candidate.security_requirements.alternatives;
|
||||
let public = alternatives.is_empty()
|
||||
|| alternatives
|
||||
.iter()
|
||||
.any(|alternative| alternative.supported && alternative.schemes.is_empty());
|
||||
candidate.status = if blocked {
|
||||
"blocked"
|
||||
} else if public {
|
||||
"actionable"
|
||||
} else if alternatives.iter().enumerate().any(|(index, alternative)| {
|
||||
alternative.supported
|
||||
&& choices.iter().any(|choice| {
|
||||
choice.operation_key == candidate.key
|
||||
&& choice.alternative_index == index
|
||||
&& !choice.profiles.is_empty()
|
||||
})
|
||||
}) {
|
||||
"unresolved"
|
||||
} else {
|
||||
"blocked"
|
||||
}
|
||||
.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
impl AdminService {
|
||||
#[instrument(skip(self, upload), fields(workspace_id = %workspace_id.as_str()))]
|
||||
pub async fn preview_openapi_import(
|
||||
@@ -186,6 +315,20 @@ impl AdminService {
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::openapi_upload(locale, "no_methods"));
|
||||
}
|
||||
let candidate_count: usize = parsed
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.operations.len())
|
||||
.sum();
|
||||
if candidate_count > MAX_IMPORT_PLAN_KEYS {
|
||||
dependencies.detach_all().await;
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::validation_with_context(
|
||||
"OpenAPI preview has too many candidates",
|
||||
json!({ "error_code": "openapi_preview_too_many_candidates", "limit": MAX_IMPORT_PLAN_KEYS }),
|
||||
));
|
||||
}
|
||||
let source_envelope = ImportJobSourceEnvelope {
|
||||
source_id,
|
||||
digest: artifact.artifact_ref().clone(),
|
||||
@@ -236,12 +379,19 @@ impl AdminService {
|
||||
let security_profile_choices = self
|
||||
.security_profile_choices(workspace_id, &parsed.preview)
|
||||
.await?;
|
||||
let catalog_names = self
|
||||
.registry
|
||||
.list_import_catalog_names(workspace_id)
|
||||
.await?;
|
||||
let mut response_preview = parsed.preview;
|
||||
response_preview.conflicts = preview_name_conflicts(&response_preview, &catalog_names);
|
||||
attach_preview_readiness(&mut response_preview, &security_profile_choices);
|
||||
Ok(OpenApiImportPreviewResponse {
|
||||
job_id: job_id.as_str().to_owned(),
|
||||
expires_at: expires_at
|
||||
.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
preview: parsed.preview,
|
||||
preview: response_preview,
|
||||
security_profile_choices,
|
||||
})
|
||||
}
|
||||
@@ -542,6 +692,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
|
||||
operation.name
|
||||
),
|
||||
operation_key: Some(operation.operation_key.clone()),
|
||||
source_location: None,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -560,6 +711,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
|
||||
format!("Операция {name} уже существует и была пропущена.")
|
||||
},
|
||||
operation_key: Some(operation.operation_key.clone()),
|
||||
source_location: None,
|
||||
});
|
||||
OpenApiImportSkippedOperation {
|
||||
operation_key: operation.operation_key.clone(),
|
||||
@@ -658,3 +810,20 @@ fn tool_quality_finding_from_import(finding: &ImportFinding) -> ToolQualityFindi
|
||||
field_path: finding.operation_key.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preview_name_tests {
|
||||
use super::next_available_name;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn crowded_catalog_still_gets_a_free_deterministic_proposal() {
|
||||
let mut occupied = (2..=2_002)
|
||||
.map(|index| format!("shared_{index}"))
|
||||
.collect::<BTreeSet<_>>();
|
||||
occupied.insert("shared".to_owned());
|
||||
|
||||
assert_eq!(next_available_name("shared", &mut occupied), "shared_2003");
|
||||
assert_eq!(next_available_name("shared", &mut occupied), "shared_2004");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user