feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -0,0 +1,440 @@
|
||||
use super::*;
|
||||
use crank_registry::{ApplyImportPlanRequest, ImportPlanApplyReport};
|
||||
|
||||
const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
|
||||
|
||||
impl AdminService {
|
||||
/// Reads an immutable plan and checks its current authority without Apply mutations.
|
||||
pub async fn revalidate_openapi_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
|
||||
self.revalidate_openapi_import_plan_with_locale(
|
||||
workspace_id,
|
||||
plan_id,
|
||||
OpenApiUploadLocale::En,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Locale-aware variant used by the HTTP boundary.
|
||||
pub async fn revalidate_openapi_import_plan_with_locale(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
let plan = self
|
||||
.registry
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
)
|
||||
})?;
|
||||
let mut reason = None;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
reason = Some("import_plan_expired");
|
||||
} else if let Some(job) = self
|
||||
.registry
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
{
|
||||
if job.kind != ImportJobKind::OpenApi
|
||||
|| job.status != ImportJobStatus::Pending
|
||||
|| job.expires_at <= now
|
||||
{
|
||||
reason = Some("import_plan_job_terminal");
|
||||
} else {
|
||||
match self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => {
|
||||
let v2 = plan.payload.get("schema_version").and_then(Value::as_str)
|
||||
== Some("import-plan-v2");
|
||||
if self
|
||||
.read_import_job_dependencies(
|
||||
workspace_id,
|
||||
&job.preview_payload,
|
||||
locale,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
reason = Some("import_dependency_verification_failed");
|
||||
} else if !v2 {
|
||||
// Historical plans stay readable for audit, but lack the
|
||||
// catalog evidence required for current Apply authority.
|
||||
reason = Some("importer_version_changed");
|
||||
} else if resolved
|
||||
.fingerprint
|
||||
.get("normalizer_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(NORMALIZER_VERSION)
|
||||
|| resolved
|
||||
.fingerprint
|
||||
.get("projection_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(PROJECTION_VERSION)
|
||||
|| plan
|
||||
.payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION)
|
||||
{
|
||||
reason = Some("importer_version_changed");
|
||||
} else if self
|
||||
.registry
|
||||
.revalidate_import_plan(workspace_id, plan_id, &resolved.fingerprint)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
reason = Some("import_plan_revalidation_failed");
|
||||
}
|
||||
}
|
||||
Err(_) => reason = Some("import_preview_revalidation_failed"),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reason = Some("import_plan_job_unavailable");
|
||||
}
|
||||
|
||||
let counts = &plan.payload["counts"];
|
||||
let count = |key: &str| {
|
||||
counts
|
||||
.get(key)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| usize::try_from(value).ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let selected = plan.payload["candidates"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|candidate| {
|
||||
let decision = &candidate["decision"];
|
||||
let string = |value: &Value| value.as_str().map(str::to_owned);
|
||||
OpenApiImportPlanCandidateView {
|
||||
key: string(&candidate["key"]).unwrap_or_default(),
|
||||
name: string(&candidate["name"]).unwrap_or_default(),
|
||||
state: string(&candidate["state"]).unwrap_or_default(),
|
||||
action: string(&decision["action"]),
|
||||
target_operation_id: string(&decision["target_operation_id"]),
|
||||
confirmed_name: string(&decision["confirmed_name"]),
|
||||
auth_profile_id: string(&decision["auth_profile_id"]),
|
||||
security_alternative_index: decision["security_alternative_index"]
|
||||
.as_u64()
|
||||
.and_then(|value| usize::try_from(value).ok()),
|
||||
reason: string(&candidate["reason"]),
|
||||
}
|
||||
});
|
||||
let excluded = plan
|
||||
.payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|key| OpenApiImportPlanCandidateView {
|
||||
key: key.to_owned(),
|
||||
name: excluded_candidate_display_name(&plan.payload, key),
|
||||
state: "excluded".to_owned(),
|
||||
action: None,
|
||||
target_operation_id: None,
|
||||
confirmed_name: None,
|
||||
auth_profile_id: None,
|
||||
security_alternative_index: None,
|
||||
reason: plan.payload["excluded_reasons"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
|
||||
.and_then(|item| item["reason"].as_str())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| Some("not_selected".to_owned())),
|
||||
});
|
||||
Ok(OpenApiImportPlanRevalidationResponse {
|
||||
plan_reference: plan.id.as_str().to_owned(),
|
||||
plan_digest: plan.digest,
|
||||
revalidation_status: if reason.is_some() { "stale" } else { "current" }.to_owned(),
|
||||
revalidation_required: reason.is_some(),
|
||||
reason: reason.map(str::to_owned),
|
||||
counts: OpenApiImportPlanCounts {
|
||||
selected: count("selected"),
|
||||
excluded: count("excluded"),
|
||||
actionable: count("actionable"),
|
||||
blocked: count("blocked"),
|
||||
},
|
||||
candidates: selected.chain(excluded).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn apply_openapi_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
payload: OpenApiImportPlanApplyPayload,
|
||||
) -> Result<ImportPlanApplyReport, ApiError> {
|
||||
self.apply_openapi_import_plan_with_locale(
|
||||
workspace_id,
|
||||
plan_id,
|
||||
payload,
|
||||
OpenApiUploadLocale::En,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), plan_id = %plan_id.as_str()))]
|
||||
pub async fn apply_openapi_import_plan_with_locale(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
payload: OpenApiImportPlanApplyPayload,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<ImportPlanApplyReport, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
validate_apply_payload(&payload)?;
|
||||
|
||||
// The replay row is deliberately checked before the plan or job.
|
||||
// Its report remains authoritative after normal TTL cleanup removes
|
||||
// those source rows.
|
||||
if let Some(application) = self
|
||||
.registry
|
||||
.get_import_plan_application(workspace_id, &payload.idempotency_key)
|
||||
.await?
|
||||
{
|
||||
if application.plan_digest != payload.plan_digest {
|
||||
return Err(key_digest_conflict(locale));
|
||||
}
|
||||
return Ok(application.result.report);
|
||||
}
|
||||
|
||||
let plan = self
|
||||
.registry
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
)
|
||||
})?;
|
||||
|
||||
if plan.digest != payload.plan_digest {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_digest_mismatch",
|
||||
));
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
return Err(import_plan_repreview_error(locale, "import_plan_expired"));
|
||||
}
|
||||
|
||||
let job = self
|
||||
.registry
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
.ok_or_else(|| import_plan_repreview_error(locale, "import_plan_job_unavailable"))?;
|
||||
if job.kind != ImportJobKind::OpenApi {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_job_kind_mismatch",
|
||||
));
|
||||
}
|
||||
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_job_terminal",
|
||||
));
|
||||
}
|
||||
|
||||
let resolved = self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
.map_err(|resolution| match resolution {
|
||||
ImportPreviewResolution::Fatal(error_code, _) => {
|
||||
import_plan_repreview_error(locale, error_code)
|
||||
}
|
||||
ImportPreviewResolution::NonFatal(_) => {
|
||||
import_plan_repreview_error(locale, "import_preview_revalidation_failed")
|
||||
}
|
||||
})?;
|
||||
|
||||
// Applying a new plan requires the current normalizer/projection
|
||||
// contract. Historic jobs remain available to the legacy replay path,
|
||||
// but a plan created from a historic projection must be previewed
|
||||
// again before it can authorize mutations.
|
||||
if resolved
|
||||
.fingerprint
|
||||
.get("normalizer_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(NORMALIZER_VERSION)
|
||||
|| resolved
|
||||
.fingerprint
|
||||
.get("projection_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(PROJECTION_VERSION)
|
||||
|| (plan.payload.get("schema_version").and_then(Value::as_str)
|
||||
== Some("import-plan-v2")
|
||||
&& plan
|
||||
.payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION))
|
||||
{
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"importer_version_changed",
|
||||
));
|
||||
}
|
||||
|
||||
// Verify every persisted external snapshot again without making a
|
||||
// network request. The registry repeats source/dependency checks
|
||||
// under its transaction before it mutates operations.
|
||||
self.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
import_plan_repreview_error(locale, "import_dependency_verification_failed")
|
||||
})?;
|
||||
|
||||
let result = self
|
||||
.registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id,
|
||||
plan_id,
|
||||
plan_digest: &payload.plan_digest,
|
||||
idempotency_key: &payload.idempotency_key,
|
||||
verified_fingerprint: &resolved.fingerprint,
|
||||
applied_at: &now,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| map_apply_registry_error(locale, error))?;
|
||||
Ok(result.report)
|
||||
}
|
||||
}
|
||||
|
||||
fn excluded_candidate_display_name(plan: &Value, key: &str) -> String {
|
||||
plan["excluded_reasons"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
|
||||
.and_then(|item| item["name"].as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or(key)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn validate_apply_payload(payload: &OpenApiImportPlanApplyPayload) -> Result<(), ApiError> {
|
||||
let digest_valid = payload.plan_digest.len() == 64
|
||||
&& payload
|
||||
.plan_digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
|
||||
if !digest_valid {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"plan_digest must be 64 lowercase hexadecimal characters",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
if !(1..=MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES).contains(&payload.idempotency_key.len())
|
||||
|| payload.idempotency_key.trim() != payload.idempotency_key
|
||||
|| payload.idempotency_key.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ApiError::validation_with_context(
|
||||
"idempotency_key must be a non-empty bounded printable value",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_apply_registry_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
|
||||
match error {
|
||||
RegistryError::ImportPlanNotFound { .. } => ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
),
|
||||
RegistryError::ImportPlanExpired { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_expired")
|
||||
}
|
||||
RegistryError::ImportPlanPayloadCorrupt { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_payload_invalid")
|
||||
}
|
||||
RegistryError::ImportPlanFingerprintStale { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_fingerprint_stale")
|
||||
}
|
||||
RegistryError::ImportPlanKeyDigestConflict { .. } => key_digest_conflict(locale),
|
||||
RegistryError::ImportPlanNameConflict { .. } => {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => "имя операции изменилось после создания плана",
|
||||
OpenApiUploadLocale::En => "an operation name changed after the plan was created",
|
||||
};
|
||||
ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"error_code": "import_plan_name_conflict",
|
||||
"recovery": "confirm_skip_rename_or_new_version"
|
||||
}),
|
||||
)
|
||||
}
|
||||
RegistryError::ImportPlanTargetStale { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_target_stale")
|
||||
}
|
||||
RegistryError::ImportPlanAuthUnavailable { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_auth_unavailable")
|
||||
}
|
||||
other => ApiError::from(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn key_digest_conflict(locale: OpenApiUploadLocale) -> ApiError {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => {
|
||||
"ключ идемпотентности уже зафиксирован для другого материала плана; создайте новый preview"
|
||||
}
|
||||
OpenApiUploadLocale::En => {
|
||||
"idempotency key was already committed for different plan material"
|
||||
}
|
||||
};
|
||||
ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"error_code": "import_plan_key_digest_conflict",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::excluded_candidate_display_name;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn excluded_candidate_name_uses_persisted_display_name_and_legacy_key_fallback() {
|
||||
let current = json!({
|
||||
"excluded_reasons": [{
|
||||
"key": "GET /alpha",
|
||||
"name": "Alpha display label",
|
||||
"reason": "not_selected"
|
||||
}]
|
||||
});
|
||||
assert_eq!(
|
||||
excluded_candidate_display_name(¤t, "GET /alpha"),
|
||||
"Alpha display label"
|
||||
);
|
||||
|
||||
let historic = json!({
|
||||
"excluded_reasons": [{ "key": "GET /alpha", "reason": "not_selected" }]
|
||||
});
|
||||
assert_eq!(
|
||||
excluded_candidate_display_name(&historic, "GET /alpha"),
|
||||
"GET /alpha"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user