Files
crank/apps/admin-api/src/error/resource.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

166 lines
8.1 KiB
Rust

//! Отображение ошибок 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<ResourceError> 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(),
}
}