//! Отображение ошибок Resource в HTTP-ответ admin-api (D-14). //! //! Домен отдаёт только стабильные `code`/`field`; HTTP-статус и конверт //! собираются здесь, поэтому `error.rs` не разрастается и остаётся в пределах //! лимита размера файла. use super::ApiError; use crank_core::resource::ResourceError; use serde_json::{Value, json}; /// Стабильные коды/поля Resource (D-14): `context.error_code` наблюдаем как /// `error.code`, `context.field` — как `error.context.field`. Сообщения /// фиксированные и никогда не содержат bytes содержимого или текст хранилища. impl From for ApiError { fn from(value: ResourceError) -> Self { let code = value.code(); let mut context = json!({ "error_code": code }); if let Some(field) = value.field() { context["field"] = Value::String(field.to_owned()); } if value == ResourceError::Stale { context["recovery"] = Value::String("reload".to_owned()); } // Story 3.10: блокирующие findings уходят в существующее поле конверта // `error.context.findings[]` (`code` + `field`), без текста определения. if let ResourceError::SourceBlocked { findings } = &value { context["findings"] = json!(findings); } let message = resource_error_message(&value); match value { ResourceError::ContentEmpty | ResourceError::ContentInvalidUtf8 | ResourceError::ContentInvalidJson | ResourceError::ArtifactIntegrity | ResourceError::SecretFindings => Self::Unprocessable { message, context: Some(context), }, ResourceError::SourceNotPublished | ResourceError::SourceBlocked { .. } => { Self::Unprocessable { message, context: Some(context), } } ResourceError::ContentTooLarge => Self::PayloadTooLarge { message, context: Some(context), }, ResourceError::UriDuplicate | ResourceError::NameDuplicate => Self::Conflict { message, context: Some(context), }, // Story 3.10: definition-only Resource не переносим (export/content). ResourceError::SourceNotPortable => Self::Conflict { message, context: Some(context), }, ResourceError::SourceNotFound => Self::NotFound { message, context: Some(context), }, ResourceError::Stale => Self::PreconditionRequired { message, context: Some(context), }, ResourceError::NotFound => Self::NotFound { message, context: Some(context), }, // Story 3.8: отозванный Resource — обычный конфликт с устойчивым кодом; // сообщение и контекст не раскрывают content/URI/digest. ResourceError::Revoked => Self::Conflict { message, context: Some(context), }, ResourceError::StorageUnavailable | ResourceError::InvalidLimits => Self::Internal { message: "internal server error".to_owned(), context: Some(context), }, // Lifecycle-отказ — обычный клиентский конфликт, а не внутренняя ошибка: // код остаётся существующим (`resource_lifecycle_invalid`), сообщение // фиксированное и не раскрывает from/to. ResourceError::InvalidLifecycleTransition { .. } => Self::Conflict { message, context: Some(context), }, ResourceError::MimeSyntaxInvalid | ResourceError::MimeNotAllowed | ResourceError::KindMismatch | ResourceError::UriInvalid | ResourceError::NameInvalid | ResourceError::DescriptionInvalid | ResourceError::PortabilityEnvelopeInvalid | ResourceError::SourceInvalid { .. } | ResourceError::FieldImmutable { .. } => Self::Validation { message, context: Some(context), }, // D-20 B/E: значение поля вне набора — форма запроса. Отказ выводится как // generic `validation_error` без Resource-специфичного кода и без поля. ResourceError::UnknownMetadataValue { .. } => Self::Validation { message, context: None, }, } } } fn resource_error_message(error: &ResourceError) -> String { match error { ResourceError::ContentEmpty => "resource content must not be empty".to_owned(), ResourceError::PortabilityEnvelopeInvalid => { "resource portability envelope is invalid".to_owned() } ResourceError::ContentTooLarge => { "resource content exceeds the configured limit".to_owned() } ResourceError::ContentInvalidUtf8 => "resource content is not valid UTF-8".to_owned(), ResourceError::ContentInvalidJson => "resource content is not valid JSON".to_owned(), ResourceError::MimeSyntaxInvalid => "resource mime type syntax is invalid".to_owned(), ResourceError::MimeNotAllowed => { "resource mime type is not allowed for this kind".to_owned() } ResourceError::KindMismatch => { "resource mime type is incompatible with the declared kind".to_owned() } ResourceError::UriInvalid => "resource uri is invalid".to_owned(), ResourceError::NameInvalid => "resource name is invalid".to_owned(), ResourceError::DescriptionInvalid => "resource description is invalid".to_owned(), ResourceError::UnknownMetadataValue { field } => { format!("resource metadata field `{field}` has an unknown value") } ResourceError::UriDuplicate => "resource uri already exists in this workspace".to_owned(), ResourceError::NameDuplicate => "resource name already exists in this workspace".to_owned(), ResourceError::FieldImmutable { field } => { format!("resource field {field} is immutable") } ResourceError::Stale => "resource changed since it was read".to_owned(), ResourceError::NotFound => "resource was not found in this workspace".to_owned(), ResourceError::Revoked => "resource has been revoked".to_owned(), ResourceError::ArtifactIntegrity => { "resource artifact integrity verification failed".to_owned() } ResourceError::SecretFindings => { "resource content contains secret material or an access-bypassing reference".to_owned() } ResourceError::StorageUnavailable | ResourceError::InvalidLimits => { "internal server error".to_owned() } ResourceError::InvalidLifecycleTransition { .. } => { "resource lifecycle transition is not allowed".to_owned() } ResourceError::SourceInvalid { .. } => "resource source definition is invalid".to_owned(), ResourceError::SourceNotFound => { "resource source operation was not found in this workspace".to_owned() } ResourceError::SourceNotPublished => { "resource source operation version is not published".to_owned() } ResourceError::SourceBlocked { .. } => { "resource source definition has blocking findings".to_owned() } ResourceError::SourceNotPortable => "resource source definition is not portable".to_owned(), } }