Files
crank/apps/admin-api/src/service/resources.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

885 lines
36 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Story 3.6: сервис typed static Resource Drafts.
//!
//! Здесь живёт продуктовый pipeline D-20 в фиксированном порядке:
//! B (разбор multipart/метаданных) → C (разрешение Resource) → D (неизменяемость)
//! → E (поля метаданных, MIME) → F (precondition) → G (содержимое) → H/I (запись
//! bytes и транзакция реестра). Метаданные побеждают содержимое, разрешение
//! Resource побеждает содержимое — именно в этом порядке проверки вызываются.
//!
//! Точки наблюдения счётчиков (D-19) стоят вплотную к реальным вызовам:
//! `counters::note_artifact_put()` перед `ArtifactStore::put_registered` и
//! `counters::note_artifact_read()` перед физическим чтением байт в
//! `load_content`. В production-сборке кода счётчиков нет.
use std::sync::Arc;
use crate::error::ApiError;
use crank_artifacts::{ArtifactError, ArtifactStore};
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::{
ResourceError, ResourceKind, ResourceLimits, ResourceMetadata, ResourceSensitivity,
ResourceStatus,
};
use crank_registry::PostgresRegistry;
use crank_registry::model::resource::{
ArchiveResourceRequest, CreateResourceDraftRequest, PublishResourceVersionRequest,
ResourceDraftRecord, ResourcePublicationRecord, ResourceVersionRecord,
UpdateResourceDraftRequest,
};
use serde::Serialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
const MAX_PAGE_SIZE: u32 = 100;
const DEFAULT_DOWNLOAD_FILENAME: &str = "resource";
/// Inline-счётчики реальных точек (D-19): отдельного production-модуля и
/// публичного probe нет — весь код под `#[cfg(test)]`.
#[cfg(test)]
pub(crate) mod counters {
use std::sync::atomic::{AtomicU64, Ordering};
static ARTIFACT_PUTS: AtomicU64 = AtomicU64::new(0);
static ARTIFACT_READS: AtomicU64 = AtomicU64::new(0);
pub(crate) fn note_artifact_put() {
ARTIFACT_PUTS.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn note_artifact_read() {
ARTIFACT_READS.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn artifact_puts() -> u64 {
ARTIFACT_PUTS.load(Ordering::SeqCst)
}
pub(crate) fn artifact_reads() -> u64 {
ARTIFACT_READS.load(Ordering::SeqCst)
}
pub(crate) fn reset() {
ARTIFACT_PUTS.store(0, Ordering::SeqCst);
ARTIFACT_READS.store(0, Ordering::SeqCst);
}
}
/// BUILD-only детерминированный шов (P3, TL F05): ровно одна точка между
/// разрешением версии и физическим чтением байт в `load_content`.
///
/// Тест ставит сюда controlled concurrent update того же Resource и получает
/// детерминированное чередование без гонки. Ровно один вызов на установленный
/// шаг; в production-сборке модуля и вызова нет.
#[cfg(test)]
pub(crate) mod interleave {
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
type Hook = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;
static HOOK: Mutex<Option<Hook>> = Mutex::new(None);
static AFTER_RESOLVE: Mutex<Option<Hook>> = Mutex::new(None);
/// Устанавливает шаг, который будет исполнен один раз на следующей точке.
pub(crate) fn install(hook: Hook) {
*HOOK.lock().expect("interleave hook lock must not poison") = Some(hook);
}
/// Исполняет установленный шаг (если он есть) и снимает его.
pub(crate) async fn fire() {
let hook = HOOK
.lock()
.expect("interleave hook lock must not poison")
.take();
if let Some(hook) = hook {
hook().await;
}
}
/// Второй BUILD-only шов (F6, TL run109): точка **после** разрешения версии и
/// **до** физического чтения байт. Нужен, чтобы наблюдать окно, которое первый
/// шов (`fire`, до разрешения) поймать не может: одновременное обновление,
/// случившееся уже после pinned-разрешения, не должно менять ответ.
pub(crate) fn install_after_resolve(hook: Hook) {
*AFTER_RESOLVE
.lock()
.expect("interleave hook lock must not poison") = Some(hook);
}
/// Исполняет установленный после-разрешения шаг (если он есть) и снимает его.
pub(crate) async fn fire_after_resolve() {
let hook = AFTER_RESOLVE
.lock()
.expect("interleave hook lock must not poison")
.take();
if let Some(hook) = hook {
hook().await;
}
}
}
/// Метаданные Draft в форме multipart-части (D-16).
#[derive(Clone, Debug)]
pub(crate) struct DraftMetadata {
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub sensitivity: String,
}
/// Новый Draft вместе с его bytes.
#[derive(Clone, Debug)]
pub(crate) struct NewDraft {
pub workspace_id: WorkspaceId,
pub metadata: DraftMetadata,
pub bytes: Vec<u8>,
}
/// Результат создания Draft.
#[derive(Clone, Debug)]
pub(crate) struct CreatedDraft {
pub resource_id: ResourceId,
}
/// Идентификатор неизменяемого поля Draft (D-16). Присутствие ключа в запросе
/// обновления — уже нарушение, независимо от его значения (включая `null`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ImmutableField {
Uri,
Name,
Kind,
}
impl ImmutableField {
fn wire_name(self) -> &'static str {
match self {
Self::Uri => "uri",
Self::Name => "name",
Self::Kind => "kind",
}
}
}
/// Обновление существующего Draft. `uri`/`name`/`kind` в payload не принимаются:
/// переданное значение — уже нарушение (D-16).
#[derive(Clone, Debug)]
pub(crate) struct UpdateDraft {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub description: String,
pub mime_type: String,
pub sensitivity: String,
pub expected_updated_at: Option<String>,
pub immutable_fields: Vec<ImmutableField>,
pub bytes: Vec<u8>,
}
/// Публикация текущего Draft (Story 3.7). Precondition — точное `updated_at` карточки,
/// как у существующего PUT; отсутствие/расхождение — `resource_stale`.
#[derive(Clone, Debug)]
pub(crate) struct PublishResource {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub expected_updated_at: Option<String>,
}
/// Архив Resource (Story 3.7 AC05/AC06). Тот же precondition, что у publish/PUT;
/// archived-переход не удаляет artifacts/publications и не меняет Agent snapshots.
#[derive(Clone, Debug)]
pub(crate) struct ArchiveResource {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub expected_updated_at: Option<String>,
}
/// Сервис Resource Drafts: реестр + content-addressed store + пределы содержимого.
#[derive(Clone)]
pub(crate) struct ResourcesService {
registry: PostgresRegistry,
store: Arc<ArtifactStore>,
limits: ResourceLimits,
}
impl ResourcesService {
pub(crate) fn new(
registry: PostgresRegistry,
store: Arc<ArtifactStore>,
limits: ResourceLimits,
) -> Self {
Self {
registry,
store,
limits,
}
}
/// Создание Draft: E (метаданные) → G (содержимое) → put bytes → одна транзакция.
pub(crate) async fn create_draft(
&self,
draft: NewDraft,
) -> Result<CreatedDraft, ResourceError> {
let metadata = parse_metadata(&draft.metadata)?;
let bytes = ResourceMetadata::validate_content(
metadata.kind,
&metadata.mime_type,
&draft.bytes,
&self.limits,
)?;
let resource_id = generate_resource_id();
let now = truncate_to_micros(OffsetDateTime::now_utc());
let artifact = self.put_registered(&bytes).await?;
let record = self
.registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: draft.workspace_id,
resource_id: resource_id.clone(),
uri: metadata.uri,
name: metadata.name,
description: metadata.description,
kind: metadata.kind.as_str().to_owned(),
mime_type: metadata.mime_type,
sensitivity: metadata.sensitivity.as_str().to_owned(),
artifact,
created_at: now,
})
.await?;
Ok(CreatedDraft {
resource_id: record.resource.resource_id,
})
}
/// Обновление Draft в порядке C → D → E → F → G → H/I.
pub(crate) async fn update_draft(
&self,
update: UpdateDraft,
) -> Result<ResourceCardResponse, ResourceError> {
// C: разрешение Resource до любой работы с содержимым.
let current = self
.registry
.get_resource_draft(update.workspace_id.as_str(), &update.resource_id)
.await?;
// D: uri/name/kind неизменяемы — присутствие любого из них уже нарушение.
if let Some(field) = update.immutable_fields.first() {
return Err(ResourceError::FieldImmutable {
field: field.wire_name(),
});
}
// E: только изменяемые поля метаданных.
let current_kind = parse_kind(&current.resource.kind)?;
if !ResourceMetadata::description_is_valid(&update.description) {
return Err(ResourceError::DescriptionInvalid);
}
if !ResourceMetadata::mime_syntax_is_valid(&update.mime_type) {
return Err(ResourceError::MimeSyntaxInvalid);
}
match ResourceKind::for_mime(&update.mime_type) {
None => return Err(ResourceError::MimeNotAllowed),
Some(owner) if owner != current_kind => {
return Err(ResourceError::KindMismatch);
}
Some(_) => {}
}
let sensitivity = parse_sensitivity(&update.sensitivity)?;
// F: precondition решается до любой работы с содержимым (D-20 F→G→H).
// Сравнение идёт с только что прочитанным `updated_at` этого Resource;
// авторитетный CAS под блокировкой строки остаётся в реестре и ловит
// настоящую гонку между двумя одновременными запросами.
let expected_updated_at = update
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
// Актуальный CAS на уже архивном Resource — lifecycle-отказ (409), не 500:
// Archived -> Draft недопустим, карточка больше не редактируется.
if current.resource.status == ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: ResourceStatus::Draft,
});
}
// G: содержимое.
let bytes = ResourceMetadata::validate_content(
current_kind,
&update.mime_type,
&update.bytes,
&self.limits,
)?;
let artifact = self.put_registered(&bytes).await?;
self.registry
.update_resource_draft(UpdateResourceDraftRequest {
workspace_id: update.workspace_id.clone(),
resource_id: update.resource_id.clone(),
description: update.description,
mime_type: update.mime_type,
sensitivity: sensitivity.as_str().to_owned(),
expected_updated_at,
artifact,
})
.await?;
self.card(&update.workspace_id, &update.resource_id).await
}
/// Публикация проверенного Draft в immutable Published Version (AT-3.7-02/03).
///
/// Порядок: C (разрешение Resource) → F (точный precondition) → E (повторная проверка
/// сохранённых metadata) → G (bounded bytes, digest/integrity, secret-policy) →
/// CAS-транзакция реестра со сверкой version/digest/size под row-lock.
pub(crate) async fn publish(
&self,
request: PublishResource,
) -> Result<PublishedVersionResponse, ResourceError> {
let current = self
.registry
.get_resource_draft(request.workspace_id.as_str(), &request.resource_id)
.await?;
// Story 3.10: template Draft публикуется по definition-контракту, без bytes.
if current.version.source_kind == "template" {
return self.publish_template(request, current).await;
}
// F: precondition решается до любой работы с содержимым (как в существующем PUT).
let expected_updated_at = request
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
// Актуальный CAS на уже архивном Resource — lifecycle-отказ (409): публикация
// архивной карточки недопустима, immutable history при этом не меняется.
if current.resource.status == ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: ResourceStatus::Published,
});
}
// E: сохранённые metadata проверяются заново (defense-in-depth) до чтения bytes:
// повреждённая/устаревшая грамматика обязана дать стабильный 400, а не integrity-отказ.
let kind = parse_kind(&current.resource.kind)?;
let metadata = ResourceMetadata {
uri: current.resource.uri.clone(),
name: current.resource.name.clone(),
description: current.resource.description.clone(),
kind,
mime_type: current.version.mime_type.clone(),
sensitivity: parse_sensitivity(&current.version.sensitivity)?,
};
metadata.validate()?;
let limit = self.limits.effective_limit(kind);
if usize::try_from(current.version.size_bytes)
.map(|size| size > limit)
.unwrap_or(true)
{
return Err(ResourceError::ContentTooLarge);
}
// Один снимок metadata/bytes: resolved-версия служит источником bytes и
// подтверждения digest для publish-транзакции (TOCTOU закрывается CAS/сверкой).
let (bytes, resolved) = self
.load_content(&request.workspace_id, &request.resource_id)
.await?;
let snapshot = &resolved.snapshot;
// G: повторная проверка семантики сохранённых bytes.
ResourceMetadata::validate_content(kind, &metadata.mime_type, &bytes, &self.limits)?;
self.validate_publication_policy(&request.workspace_id, &metadata, &bytes)
.await?;
let artifact = self.put_registered(&bytes).await?;
let published_at = truncate_to_micros(OffsetDateTime::now_utc());
let publication = self
.registry
.publish_resource_version(PublishResourceVersionRequest {
workspace_id: request.workspace_id.clone(),
resource_id: request.resource_id.clone(),
expected_updated_at,
expected_version: snapshot.version.version,
expected_digest: snapshot.version.digest.clone(),
expected_size_bytes: snapshot.version.size_bytes,
artifact,
published_at,
})
.await?;
let card = self
.card(&request.workspace_id, &request.resource_id)
.await?;
Ok(PublishedVersionResponse {
resource: card,
published_version: PublishedVersionView::from_record(&publication),
})
}
/// Архив Resource: C (разрешение) → F (точный precondition) → транзакция архива.
///
/// Archived-отказ с актуальным CAS — существующий domain-код
/// `resource_lifecycle_invalid` (409). Artifacts/publications/Agent snapshots не
/// затрагиваются: меняются только lifecycle и ревизия карточки.
pub(crate) async fn archive(
&self,
request: ArchiveResource,
) -> Result<ResourceCardResponse, ResourceError> {
let current = self
.registry
.get_resource_draft(request.workspace_id.as_str(), &request.resource_id)
.await?;
let expected_updated_at = request
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
// Старый CAS обязан дать stale даже для уже архивного Resource: порядок
// «precondition → lifecycle» сохраняет принятую 428-семантику повторов.
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
self.registry
.archive_resource(ArchiveResourceRequest {
workspace_id: request.workspace_id.clone(),
resource_id: request.resource_id.clone(),
expected_updated_at,
archived_at: truncate_to_micros(OffsetDateTime::now_utc()),
})
.await?;
self.card(&request.workspace_id, &request.resource_id).await
}
/// Точная Published Version: metadata снимка, без owning-ссылки/raw filename.
pub(crate) async fn published_version(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<PublishedVersionView, ResourceError> {
match self
.registry
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
.await
{
Ok(resolved) => Ok(PublishedVersionView::from_record(&resolved.publication)),
// Story 3.10: definition-only версия живёт без artifact-ссылки.
Err(ResourceError::NotFound) => {
self.published_template_view(workspace_id, resource_id, version)
.await
}
Err(error) => Err(error),
}
}
/// Байты точной Published Version для inert download (политику заголовков задаёт роут).
pub(crate) async fn read_published_content_for_download(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<ResourceDownload, ResourceError> {
// Story 3.10: определение шаблона не является содержимым и не скачивается.
if self
.publication_is_template(workspace_id, resource_id, version)
.await?
{
return Err(ResourceError::SourceNotPortable);
}
let (bytes, publication) = self
.load_published_content(workspace_id, resource_id, version)
.await?;
Ok(ResourceDownload {
bytes,
mime_type: publication.mime_type,
name: publication.name,
})
}
/// Единственная точка чтения bytes точной Published Version: один pinned-снимок
/// публикации, физическое чтение через store и проверка digest/size.
///
/// Story 3.9 использует тот же путь для экспорта точной версии, поэтому второго
/// обращения к `ArtifactStore` не появляется.
pub(crate) async fn load_published_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<
(
Vec<u8>,
crank_registry::model::resource::ResourcePublicationRecord,
),
ResourceError,
> {
let resolved = self
.registry
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
.await?;
let publication = resolved.publication;
let artifact_ref = resolved.artifact_ref;
let store = Arc::clone(&self.store);
#[cfg(test)]
counters::note_artifact_read();
let bytes = tokio::task::spawn_blocking(move || store.read(&artifact_ref))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)?;
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != publication.size_bytes
|| sha256_hex(&bytes) != publication.digest
{
return Err(ResourceError::ArtifactIntegrity);
}
Ok((bytes, publication))
}
/// Secret-policy публикации: структурные raw secrets и explicit `include:` директивы.
/// Все отказы одинаково generic; текст/цель никогда не раскрываются.
async fn validate_publication_policy(
&self,
workspace_id: &WorkspaceId,
metadata: &ResourceMetadata,
bytes: &[u8],
) -> Result<(), ResourceError> {
if self
.publication_findings(workspace_id, metadata, bytes)
.await?
.is_empty()
{
Ok(())
} else {
Err(ResourceError::SecretFindings)
}
}
/// Publication-policy findings на тех же pinned bytes, что и публикация: единый
/// scanner/validator для preview (AC01) и publish, только стабильный domain-код
/// `resource_secret_findings`; совпавший текст и цель ссылки не раскрываются.
async fn publication_findings(
&self,
workspace_id: &WorkspaceId,
metadata: &ResourceMetadata,
bytes: &[u8],
) -> Result<Vec<ResourceError>, ResourceError> {
if crank_core::resource::publication_secret_findings(bytes).is_some() {
return Ok(vec![ResourceError::SecretFindings]);
}
for target in crank_core::resource::publication_include_directives(bytes) {
// Ссылка разрешается только внутри этого workspace и только по уже
// опубликованной metadata; неразрешённая/чужая/невалидная цель — тот же отказ.
if !ResourceMetadata::uri_is_valid(&target) {
return Ok(vec![ResourceError::SecretFindings]);
}
let Some(published) = self
.registry
.published_resource_sensitivity_by_uri(workspace_id.as_str(), &target)
.await?
else {
return Ok(vec![ResourceError::SecretFindings]);
};
let referenced = parse_sensitivity(&published)?;
if sensitivity_rank(referenced) > sensitivity_rank(metadata.sensitivity) {
return Ok(vec![ResourceError::SecretFindings]);
}
}
Ok(Vec::new())
}
/// Карточка Draft.
pub(crate) async fn card(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<ResourceCardResponse, ResourceError> {
let record = self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await?;
let mut card = ResourceCardResponse::from_record(&record);
// Story 3.10: template-карточка несёт source view и blocker findings
// сохранённого определения; static wire не меняется (source отсутствует).
if record.version.source_kind == "template" {
let (source, findings) = self
.template_card(workspace_id, resource_id, record.version.version)
.await?;
card.source = Some(source);
card.findings = findings;
}
Ok(card)
}
pub(crate) async fn list(
&self,
workspace_id: &WorkspaceId,
) -> Result<ResourceListResponse, ResourceError> {
let records = self
.registry
.list_resource_drafts(workspace_id.as_str(), MAX_PAGE_SIZE)
.await?;
Ok(ResourceListResponse {
items: records
.iter()
.map(ResourceCardResponse::from_record)
.collect(),
})
}
/// Байты текущей версии: единственная физическая точка чтения (D-19).
///
/// Вход для in-crate проверок чтения (counter/integrity): production отдаёт
/// bytes через `read_content_for_download`, и оба идут через один `load_content`,
/// поэтому второго пути чтения не появляется. В production-сборке метода нет.
#[cfg(test)]
pub(crate) async fn read_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<Vec<u8>, ResourceError> {
let (bytes, _) = self.load_content(workspace_id, resource_id).await?;
Ok(bytes)
}
/// Байты текущей версии для ответа-скачивания (политику заголовков задаёт маршрут).
///
/// MIME и имя Resource берутся из того же pinned-разрешения, что и bytes:
/// отдельного чтения card-строки здесь нет (P3).
pub(crate) async fn read_content_for_download(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<ResourceDownload, ResourceError> {
// Story 3.10: у template Draft нет файла содержимого.
let record = self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await?;
if record.version.source_kind == "template" {
return Err(ResourceError::SourceNotPortable);
}
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
Ok(ResourceDownload {
bytes,
mime_type: resolved.snapshot.version.mime_type,
name: resolved.snapshot.resource.name,
})
}
async fn load_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<
(
Vec<u8>,
crank_registry::model::resource::ResolvedResourceVersion,
),
ResourceError,
> {
// C + metadata-сверки: чужой/несуществующий Resource и рассинхронизация
// metadata отсекаются до чтения байт.
//
// BUILD-only тестовая точка чередования (P3): единственное место, где
// одновременное обновление того же Resource попадает между источником
// metadata и физическим чтением bytes. Дальше версия разрешается **один**
// раз и обслуживает весь ответ, поэтому metadata версии N и bytes версии
// N+1 в одном ответе невозможны.
#[cfg(test)]
interleave::fire().await;
let resolved = self
.registry
.resolve_current_resource_version(workspace_id.as_str(), resource_id)
.await?;
// F6 (TL run109): второй шов стоит **после** pinned-разрешения: он позволяет
// наблюдать, что позднее обновление того же Resource не подменяет ни metadata,
// ни bytes уже разрешённого ответа.
#[cfg(test)]
interleave::fire_after_resolve().await;
let artifact_ref = resolved.artifact_ref.clone();
let store = Arc::clone(&self.store);
#[cfg(test)]
counters::note_artifact_read();
let bytes = tokio::task::spawn_blocking(move || store.read(&artifact_ref))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)?;
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != resolved.snapshot.version.size_bytes {
return Err(ResourceError::ArtifactIntegrity);
}
if sha256_hex(&bytes) != resolved.snapshot.version.digest {
return Err(ResourceError::ArtifactIntegrity);
}
Ok((bytes, resolved))
}
async fn put_registered(
&self,
bytes: &[u8],
) -> Result<crank_artifacts::RegisteredArtifact, ResourceError> {
let store = Arc::clone(&self.store);
let owned = bytes.to_vec();
#[cfg(test)]
counters::note_artifact_put();
// Точка регистрации durable содержимого; bounded bytes уже провалидированы.
tokio::task::spawn_blocking(move || store.put_registered(&owned))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)
}
}
/// Ответ скачивания: bytes, заявленный MIME и имя Resource (для derived filename).
pub(crate) struct ResourceDownload {
pub bytes: Vec<u8>,
pub mime_type: String,
pub name: String,
}
/// Имя файла выводится из `name` и заявленного MIME; raw upload filename не
/// сохраняется вообще (D-12), поэтому header injection и traversal невозможны.
pub(crate) fn derived_filename(name: &str, mime_type: &str) -> String {
let extension = match mime_type {
"application/json" => "json",
"text/plain" => "txt",
"text/markdown" => "md",
"text/csv" => "csv",
"application/pdf" => "pdf",
"image/png" => "png",
"image/jpeg" => "jpg",
"image/gif" => "gif",
"image/webp" => "webp",
"image/svg+xml" => "svg",
"text/html" => "html",
_ => "bin",
};
let stem: String = name
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
.take(64)
.collect();
let stem = if stem.is_empty() {
DEFAULT_DOWNLOAD_FILENAME
} else {
stem.as_str()
};
format!("{stem}.{extension}")
}
fn parse_metadata(metadata: &DraftMetadata) -> Result<ResourceMetadata, ResourceError> {
// Неизвестный `kind` не достижим через HTTP: маршрут отвергает его как generic
// `validation_error` (D-20 шаг B) до вызова сервиса. Здесь он маппится в ближайший
// существующий код, чтобы не расширять wire-контракт.
let kind = ResourceKind::parse(&metadata.kind).ok_or(ResourceError::KindMismatch)?;
let mut parsed = ResourceMetadata {
uri: metadata.uri.clone(),
name: metadata.name.clone(),
description: metadata.description.clone(),
kind,
mime_type: metadata.mime_type.clone(),
// Заполняется последним шагом E (см. ниже) и до этого не наблюдается.
sensitivity: ResourceSensitivity::Internal,
};
// D-20 шаг E: поля проверяются в порядке uri → name → description → kind → mime_type,
// и только затем значение `sensitivity`: её неизвестное значение — форма запроса
// (generic 400), поэтому оно не может опережать более ранние поля.
parsed.validate()?;
parsed.sensitivity = parse_sensitivity(&metadata.sensitivity)?;
Ok(parsed)
}
fn parse_sensitivity(value: &str) -> Result<ResourceSensitivity, ResourceError> {
ResourceSensitivity::parse(value).ok_or(ResourceError::UnknownMetadataValue {
field: "sensitivity",
})
}
/// Порядок строгости sensitivity для проверки `include:` (понижение запрещено).
fn sensitivity_rank(value: ResourceSensitivity) -> u8 {
match value {
ResourceSensitivity::Public => 0,
ResourceSensitivity::Internal => 1,
ResourceSensitivity::Secret => 2,
}
}
fn parse_kind(value: &str) -> Result<ResourceKind, ResourceError> {
ResourceKind::parse(value).ok_or(ResourceError::ArtifactIntegrity)
}
fn parse_timestamp(value: &str) -> Result<OffsetDateTime, ResourceError> {
OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339)
.map(truncate_to_micros)
.map_err(|_| ResourceError::Stale)
}
/// Микросекундная точность: Postgres `timestamptz` и RFC3339 round-trip
/// optimistic-precondition не должны расходиться из-за наносекунд.
fn truncate_to_micros(value: OffsetDateTime) -> OffsetDateTime {
let nanos = value.nanosecond();
value
.replace_nanosecond(nanos - nanos % 1_000)
.unwrap_or(value)
}
fn format_timestamp(value: OffsetDateTime) -> String {
value
.format(&time::format_description::well_known::Rfc3339)
.unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_owned())
}
fn generate_resource_id() -> ResourceId {
ResourceId::new(format!("res_{}", uuid::Uuid::now_v7().simple()))
}
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn map_artifact_error(error: ArtifactError) -> ResourceError {
match error {
ArtifactError::NotFound | ArtifactError::Integrity => ResourceError::ArtifactIntegrity,
ArtifactError::EmptySource | ArtifactError::SourceTooLarge => {
ResourceError::ArtifactIntegrity
}
_ => ResourceError::StorageUnavailable,
}
}
#[cfg(test)]
#[path = "resources/tests.rs"]
mod tests;
#[path = "resources/preview.rs"]
mod preview;
#[path = "resources/revocation.rs"]
mod revocation;
#[path = "resources/portability.rs"]
pub(crate) mod portability;
#[path = "resources/template.rs"]
pub(crate) mod template;
#[path = "resources/test_read.rs"]
mod test_read;
#[path = "resources/views.rs"]
mod views;
pub(crate) use views::*;