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
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.
860 lines
37 KiB
Rust
860 lines
37 KiB
Rust
//! Persistence Story 3.6: typed static Resource Drafts (V16).
|
||
//!
|
||
//! Каждая мутация — **одна** транзакция (D-15). Самокоммитящие
|
||
//! `create_artifact_source`/`detach_artifact_source` здесь не вызываются: вместо них
|
||
//! используется локальный SQL в уже открытой транзакции, а из общего кода
|
||
//! переиспользуются tx-local helper-ы `require_workspace`, `ensure_blob`,
|
||
//! `get_source_in_transaction` (видимость `pub(super)`, логика не менялась).
|
||
//!
|
||
//! Физическое чтение байт сюда **не** входит: `resolve_resource_version` делает
|
||
//! workspace-scoped join версии/ссылки/blob и все metadata-сверки, а байты читает
|
||
//! сервис на единственной наблюдаемой точке чтения (D-19).
|
||
|
||
use crank_artifacts::ArtifactRef;
|
||
use crank_core::WorkspaceId;
|
||
use crank_core::ids::{AgentId, ResourceId};
|
||
use crank_core::resource::{ResourceError, ResourceSensitivity, ResourceStatus};
|
||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||
|
||
use crate::RegistryError;
|
||
use crate::model::resource::{
|
||
CreateResourceDraftRequest, MAX_RESOURCE_DRAFT_PAGE_SIZE, PublishResourceVersionRequest,
|
||
ResolvedResourcePublication, ResolvedResourceVersion, ResourceDraftRecord,
|
||
ResourcePublicationRecord, ResourceRecord, ResourceVersionRecord, UpdateResourceDraftRequest,
|
||
};
|
||
use crate::model::{
|
||
ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourceSensitivity,
|
||
CreateArtifactSourceRequest,
|
||
};
|
||
|
||
use super::PostgresRegistry;
|
||
use super::artifact_source::{ensure_blob, get_source_in_transaction, require_workspace};
|
||
|
||
mod archive;
|
||
mod publication;
|
||
mod read;
|
||
mod revocation;
|
||
mod template;
|
||
|
||
pub use revocation::{AuthorizedResourceRead, BoundResourceAdmission};
|
||
|
||
use publication::resolved_publication;
|
||
|
||
const RESOURCE_ID_PREFIX: &str = "res_";
|
||
const MAX_SOURCE_TAIL_BYTES: usize = 96;
|
||
|
||
const DRAFT_SELECT: &str = "select
|
||
r.workspace_id, r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||
r.current_draft_version, r.created_at as resource_created_at,
|
||
r.updated_at as resource_updated_at,
|
||
(select max(p.version) from resource_publications p
|
||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||
as latest_published_version,
|
||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||
v.created_at as version_created_at,
|
||
v.superseded_at
|
||
from resources r
|
||
join resource_versions v
|
||
on v.workspace_id = r.workspace_id
|
||
and v.resource_id = r.resource_id
|
||
where r.workspace_id = $1 and r.resource_id = $2 and v.superseded_at is null";
|
||
|
||
const DRAFT_LIST_SELECT: &str = "select
|
||
r.workspace_id, r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||
r.current_draft_version, r.created_at as resource_created_at,
|
||
r.updated_at as resource_updated_at,
|
||
(select max(p.version) from resource_publications p
|
||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||
as latest_published_version,
|
||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||
v.created_at as version_created_at,
|
||
v.superseded_at
|
||
from resources r
|
||
join resource_versions v
|
||
on v.workspace_id = r.workspace_id
|
||
and v.resource_id = r.resource_id
|
||
where r.workspace_id = $1 and v.superseded_at is null
|
||
order by r.created_at asc, r.resource_id asc
|
||
limit $2";
|
||
|
||
const VERSION_SELECT: &str = "select
|
||
version, kind as version_kind, mime_type as version_mime_type,
|
||
size_bytes as version_size_bytes, digest as version_digest,
|
||
sensitivity as version_sensitivity, source_kind as version_source_kind,
|
||
created_at as version_created_at, superseded_at
|
||
from resource_versions
|
||
where workspace_id = $1 and resource_id = $2 and superseded_at is null";
|
||
|
||
const PUBLICATION_SELECT: &str = "select
|
||
p.resource_id, p.version, p.uri, p.name, p.description, p.kind,
|
||
p.mime_type, p.size_bytes, p.digest, p.sensitivity, p.source_kind, p.published_at,
|
||
s.blob_digest, s.mime_type as source_mime_type,
|
||
s.sensitivity as source_sensitivity, s.lifecycle as source_lifecycle,
|
||
b.artifact_ref, b.size_bytes as blob_size_bytes,
|
||
b.storage_lifecycle as blob_lifecycle
|
||
from resource_publications p
|
||
join artifact_sources s
|
||
on s.workspace_id = p.workspace_id and s.source_id = p.artifact_source_id
|
||
join artifact_blobs b on b.digest = s.blob_digest
|
||
where p.workspace_id = $1 and p.resource_id = $2 and p.version = $3";
|
||
|
||
const RESOLVE_SELECT: &str = "select
|
||
r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||
r.current_draft_version, r.created_at as resource_created_at,
|
||
r.updated_at as resource_updated_at,
|
||
(select max(p.version) from resource_publications p
|
||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||
as latest_published_version,
|
||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||
v.created_at as version_created_at,
|
||
v.superseded_at,
|
||
s.blob_digest, s.mime_type as source_mime_type,
|
||
s.sensitivity as source_sensitivity, s.lifecycle as source_lifecycle,
|
||
b.artifact_ref, b.size_bytes as blob_size_bytes,
|
||
b.storage_lifecycle as blob_lifecycle
|
||
from resource_versions v
|
||
join resources r
|
||
on r.workspace_id = v.workspace_id and r.resource_id = v.resource_id
|
||
join artifact_sources s
|
||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||
join artifact_blobs b on b.digest = s.blob_digest
|
||
where v.workspace_id = $1 and v.resource_id = $2
|
||
and (($3::int is null and v.superseded_at is null) or v.version = $3)";
|
||
|
||
impl PostgresRegistry {
|
||
/// Id behind the authenticated published Agent route, for AgentSnapshot execution origin.
|
||
pub async fn published_agent_id(
|
||
&self,
|
||
workspace_slug: &str,
|
||
agent_slug: &str,
|
||
) -> Result<AgentId, RegistryError> {
|
||
let id: Option<String> = sqlx::query_scalar(
|
||
"select a.id from workspaces w join agents a on a.workspace_id=w.id join published_agents pa on pa.agent_id=a.id where w.slug=$1 and a.slug=$2 and a.status='published'",
|
||
)
|
||
.bind(workspace_slug)
|
||
.bind(agent_slug)
|
||
.fetch_optional(self.pool())
|
||
.await?;
|
||
id.map(AgentId::new)
|
||
.ok_or_else(|| RegistryError::PublishedAgentNotFound {
|
||
workspace_slug: workspace_slug.to_owned(),
|
||
agent_slug: agent_slug.to_owned(),
|
||
})
|
||
}
|
||
|
||
/// Создание Draft: bytes уже durable (`RegisteredArtifact`), реестр добавляет
|
||
/// blob-метаданные, активную owning-ссылку, строку Resource и версию 1.
|
||
pub async fn create_resource_draft(
|
||
&self,
|
||
request: CreateResourceDraftRequest,
|
||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||
let source_id = version_source_id(&request.resource_id, 1)?;
|
||
let sensitivity = parse_sensitivity(&request.sensitivity)?;
|
||
let source_request = CreateArtifactSourceRequest {
|
||
workspace_id: &request.workspace_id,
|
||
source_id: &source_id,
|
||
artifact: &request.artifact,
|
||
mime_type: &request.mime_type,
|
||
sensitivity,
|
||
created_at: request.created_at,
|
||
};
|
||
|
||
let mut transaction = self
|
||
.pool()
|
||
.begin()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
require_workspace(&mut transaction, &request.workspace_id)
|
||
.await
|
||
.map_err(map_registry_error)?;
|
||
ensure_blob(&mut transaction, &source_request)
|
||
.await
|
||
.map_err(map_registry_error)?;
|
||
|
||
// Строгий insert: повторный create с тем же resource_id обязан упасть
|
||
// на PK, а не тихо игнорироваться (D-15 шаг 4).
|
||
sqlx::query(
|
||
"insert into artifact_sources (
|
||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||
lifecycle, created_at, updated_at, detached_at
|
||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(source_id.as_str())
|
||
.bind(request.artifact.artifact_ref().digest_hex())
|
||
.bind(&request.mime_type)
|
||
.bind(&request.sensitivity)
|
||
.bind(request.created_at)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
sqlx::query(
|
||
"insert into resources (
|
||
workspace_id, resource_id, uri, name, description, status, kind,
|
||
current_draft_version, created_at, updated_at
|
||
) values ($1, $2, $3, $4, $5, 'draft', $6, 1, $7, $7)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(&request.uri)
|
||
.bind(&request.name)
|
||
.bind(&request.description)
|
||
.bind(&request.kind)
|
||
.bind(request.created_at)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
sqlx::query(
|
||
"insert into resource_versions (
|
||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||
sensitivity, artifact_source_id, created_at, superseded_at
|
||
) values ($1, $2, 1, $3, $4, $5, $6, $7, $8, $9, null)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(&request.kind)
|
||
.bind(&request.mime_type)
|
||
.bind(size_bytes(&request.artifact)?)
|
||
.bind(request.artifact.artifact_ref().digest_hex())
|
||
.bind(&request.sensitivity)
|
||
.bind(source_id.as_str())
|
||
.bind(request.created_at)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
let record = read_draft(
|
||
&mut transaction,
|
||
&request.workspace_id,
|
||
&request.resource_id,
|
||
)
|
||
.await?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
transaction
|
||
.commit()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
Ok(record)
|
||
}
|
||
|
||
/// Обновление Draft. Точная последовательность D-15 (шаги 2–9): row-lock,
|
||
/// precondition, `ensure_blob`, пометка прежней версии **до** вставки новой,
|
||
/// новая активная ссылка, новая версия, отсоединение старой ссылки,
|
||
/// переключение указателя — всё в одной транзакции.
|
||
pub async fn update_resource_draft(
|
||
&self,
|
||
request: UpdateResourceDraftRequest,
|
||
) -> Result<ResourceVersionRecord, ResourceError> {
|
||
let mut transaction = self
|
||
.pool()
|
||
.begin()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
|
||
// Шаг 2: блокировка строки Resource и optimistic precondition.
|
||
let row = sqlx::query(
|
||
"select current_draft_version, updated_at
|
||
from resources
|
||
where workspace_id = $1 and resource_id = $2
|
||
for update",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.fetch_optional(&mut *transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||
.ok_or(ResourceError::NotFound)?;
|
||
let current_version: i32 = row
|
||
.try_get("current_draft_version")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
let recorded_updated_at: time::OffsetDateTime = row
|
||
.try_get("updated_at")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
if recorded_updated_at != request.expected_updated_at {
|
||
return Err(ResourceError::Stale);
|
||
}
|
||
let current_version =
|
||
u32::try_from(current_version).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
|
||
// Текущая версия читается только по своим собственным полям; её owning-ссылка,
|
||
// timestamps и lifecycle берутся из artifact_sources (D-15 шаг 2).
|
||
let current = sqlx::query(
|
||
"select artifact_source_id
|
||
from resource_versions
|
||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.fetch_optional(&mut *transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
let old_source_id = ArtifactSourceId::new(
|
||
current
|
||
.try_get::<String, _>("artifact_source_id")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
);
|
||
let old_source =
|
||
get_source_in_transaction(&mut transaction, &request.workspace_id, &old_source_id)
|
||
.await
|
||
.map_err(map_registry_error)?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
if old_source.lifecycle != ArtifactSourceLifecycle::Active {
|
||
return Err(ResourceError::ArtifactIntegrity);
|
||
}
|
||
let old_source_updated_at = old_source.updated_at;
|
||
|
||
let now = truncate_to_micros(time::OffsetDateTime::now_utc());
|
||
let next_version = current_version
|
||
.checked_add(1)
|
||
.ok_or(ResourceError::StorageUnavailable)?;
|
||
let new_source_id = version_source_id(&request.resource_id, next_version)?;
|
||
let sensitivity = parse_sensitivity(&request.sensitivity)?;
|
||
let new_source_request = CreateArtifactSourceRequest {
|
||
workspace_id: &request.workspace_id,
|
||
source_id: &new_source_id,
|
||
artifact: &request.artifact,
|
||
mime_type: &request.mime_type,
|
||
sensitivity,
|
||
created_at: now,
|
||
};
|
||
|
||
// Шаг 3: новые bytes в blob-метаданных. До этого шага версии не тронуты.
|
||
ensure_blob(&mut transaction, &new_source_request)
|
||
.await
|
||
.map_err(map_registry_error)?;
|
||
|
||
// Шаг 4: пометить прежнюю версию заменённой — строго до вставки новой,
|
||
// иначе частичный unique-index отвергнет две текущие версии.
|
||
let superseded = sqlx::query(
|
||
"update resource_versions
|
||
set superseded_at = $1
|
||
where workspace_id = $2 and resource_id = $3 and superseded_at is null",
|
||
)
|
||
.bind(now)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?
|
||
.rows_affected();
|
||
if superseded != 1 {
|
||
return Err(ResourceError::ArtifactIntegrity);
|
||
}
|
||
|
||
// Шаг 5: новая активная owning-ссылка (обычный insert, без `do nothing`).
|
||
sqlx::query(
|
||
"insert into artifact_sources (
|
||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||
lifecycle, created_at, updated_at, detached_at
|
||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(new_source_id.as_str())
|
||
.bind(request.artifact.artifact_ref().digest_hex())
|
||
.bind(&request.mime_type)
|
||
.bind(&request.sensitivity)
|
||
.bind(now)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
// Шаг 6: новая строка версии (FK на resources и artifact_sources проверяет БД).
|
||
sqlx::query(
|
||
"insert into resource_versions (
|
||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||
sensitivity, artifact_source_id, created_at, superseded_at
|
||
) select r.workspace_id, r.resource_id, $3, r.kind, $4, $5, $6, $7, $8, $9, null
|
||
from resources r
|
||
where r.workspace_id = $1 and r.resource_id = $2",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(version_number(next_version)?)
|
||
.bind(&request.mime_type)
|
||
.bind(size_bytes(&request.artifact)?)
|
||
.bind(request.artifact.artifact_ref().digest_hex())
|
||
.bind(&request.sensitivity)
|
||
.bind(new_source_id.as_str())
|
||
.bind(now)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
// Шаг 7: отсоединить прежнюю owning-ссылку с CAS по её `updated_at`.
|
||
let detached = sqlx::query(
|
||
"update artifact_sources
|
||
set lifecycle = 'detached', updated_at = $1, detached_at = $1
|
||
where workspace_id = $2 and source_id = $3
|
||
and lifecycle = 'active' and updated_at = $4",
|
||
)
|
||
.bind(now)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(old_source_id.as_str())
|
||
.bind(old_source_updated_at)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?
|
||
.rows_affected();
|
||
if detached != 1 {
|
||
return Err(ResourceError::ArtifactIntegrity);
|
||
}
|
||
|
||
// Шаг 8: переключение указателя; uri/name/kind неизменяемы (D-16). Правка после
|
||
// публикации возвращает карточку в Draft, published snapshot не затрагивается.
|
||
let updated = sqlx::query(
|
||
"update resources
|
||
set current_draft_version = $3, updated_at = $4, description = $5, status = 'draft'
|
||
where workspace_id = $1 and resource_id = $2",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(version_number(next_version)?)
|
||
.bind(now)
|
||
.bind(&request.description)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?
|
||
.rows_affected();
|
||
if updated != 1 {
|
||
return Err(ResourceError::NotFound);
|
||
}
|
||
|
||
let record = read_current_version(
|
||
&mut transaction,
|
||
&request.workspace_id,
|
||
&request.resource_id,
|
||
)
|
||
.await?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
transaction
|
||
.commit()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
Ok(record)
|
||
}
|
||
|
||
/// Публикация текущего Draft в immutable Published Version (V17).
|
||
///
|
||
/// В одной транзакции: row-lock Resource и CAS precondition → повторная сверка
|
||
/// version/digest/size текущей версии → отдельная owning-ссылка публикации на тот же
|
||
/// content-addressed blob → строка `resource_publications` со снимком публичных
|
||
/// metadata → переключение статуса/ревизии карточки. Отказ не пишет ни строки и не
|
||
/// сдвигает CAS.
|
||
pub async fn publish_resource_version(
|
||
&self,
|
||
request: PublishResourceVersionRequest,
|
||
) -> Result<ResourcePublicationRecord, ResourceError> {
|
||
let mut transaction = self
|
||
.pool()
|
||
.begin()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
|
||
let row = sqlx::query(
|
||
"select uri, name, description, kind, current_draft_version, updated_at
|
||
from resources
|
||
where workspace_id = $1 and resource_id = $2
|
||
for update",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.fetch_optional(&mut *transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||
.ok_or(ResourceError::NotFound)?;
|
||
|
||
let recorded_updated_at: time::OffsetDateTime = row
|
||
.try_get("updated_at")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
// Story 3.8: отзыв закрывает Resource целиком и не снимается редактированием.
|
||
// Проверка идёт под уже взятым FOR UPDATE, поэтому гонка с revoke закрыта:
|
||
// побеждает тот, кто первым получил строку.
|
||
if revocation::is_revoked(
|
||
&mut transaction,
|
||
request.workspace_id.as_str(),
|
||
request.resource_id.as_str(),
|
||
)
|
||
.await?
|
||
{
|
||
return Err(ResourceError::Revoked);
|
||
}
|
||
// F: точный precondition. Успешная публикация сдвигает ревизию, поэтому повтор
|
||
// прежней карточки — stale, а не duplicate publication.
|
||
if recorded_updated_at != request.expected_updated_at {
|
||
return Err(ResourceError::Stale);
|
||
}
|
||
let current_draft_version = u32::try_from(
|
||
row.try_get::<i32, _>("current_draft_version")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
)
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
|
||
let version_row = sqlx::query(
|
||
"select version, mime_type, size_bytes, digest, sensitivity
|
||
from resource_versions
|
||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.fetch_optional(&mut *transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
|
||
let version = u32::try_from(
|
||
version_row
|
||
.try_get::<i32, _>("version")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
)
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
let digest: String = version_row
|
||
.try_get("digest")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
let size_bytes: i64 = version_row
|
||
.try_get("size_bytes")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
// TOCTOU: между физической проверкой bytes и этим коммитом Draft мог измениться.
|
||
// Любое расхождение — stale, публикация не создаётся.
|
||
if version != request.expected_version
|
||
|| current_draft_version != version
|
||
|| digest != request.expected_digest
|
||
|| size_bytes != request.expected_size_bytes
|
||
{
|
||
return Err(ResourceError::Stale);
|
||
}
|
||
|
||
let mime_type: String = version_row
|
||
.try_get("mime_type")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
let sensitivity: String = version_row
|
||
.try_get("sensitivity")
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||
let source_sensitivity = parse_sensitivity(&sensitivity)?;
|
||
|
||
// Уже опубликованная версия не публикуется повторно: клиент получил свежую
|
||
// карточку, но Draft с тех пор не менялся. Это stale-состояние (reload), а не
|
||
// duplicate row/500.
|
||
let already_published = sqlx::query_scalar::<_, bool>(
|
||
"select exists(
|
||
select 1 from resource_publications
|
||
where workspace_id = $1 and resource_id = $2 and version = $3
|
||
)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(version_number(version)?)
|
||
.fetch_one(&mut *transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
if already_published {
|
||
return Err(ResourceError::Stale);
|
||
}
|
||
let now = truncate_to_micros(request.published_at);
|
||
let next_updated_at = if now > recorded_updated_at {
|
||
now
|
||
} else {
|
||
recorded_updated_at + time::Duration::microseconds(1)
|
||
};
|
||
let source_id = publication_source_id(&request.resource_id, version)?;
|
||
let source_request = CreateArtifactSourceRequest {
|
||
workspace_id: &request.workspace_id,
|
||
source_id: &source_id,
|
||
artifact: &request.artifact,
|
||
mime_type: &mime_type,
|
||
sensitivity: source_sensitivity,
|
||
created_at: now,
|
||
};
|
||
ensure_blob(&mut transaction, &source_request)
|
||
.await
|
||
.map_err(map_registry_error)?;
|
||
|
||
// Отдельная owning-ссылка публикации: Draft update отсоединяет только свою
|
||
// ссылку, поэтому published bytes/metadata остаются живыми независимо.
|
||
sqlx::query(
|
||
"insert into artifact_sources (
|
||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||
lifecycle, created_at, updated_at, detached_at
|
||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(source_id.as_str())
|
||
.bind(digest.as_str())
|
||
.bind(&mime_type)
|
||
.bind(&sensitivity)
|
||
.bind(now)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
sqlx::query(
|
||
"insert into resource_publications (
|
||
workspace_id, resource_id, version, uri, name, description, kind,
|
||
mime_type, size_bytes, digest, sensitivity, artifact_source_id, published_at
|
||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(version_number(version)?)
|
||
.bind(row.try_get::<String, _>("uri").map_err(integrity)?)
|
||
.bind(row.try_get::<String, _>("name").map_err(integrity)?)
|
||
.bind(row.try_get::<String, _>("description").map_err(integrity)?)
|
||
.bind(row.try_get::<String, _>("kind").map_err(integrity)?)
|
||
.bind(&mime_type)
|
||
.bind(size_bytes)
|
||
.bind(digest.as_str())
|
||
.bind(&sensitivity)
|
||
.bind(source_id.as_str())
|
||
.bind(now)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?;
|
||
|
||
let updated = sqlx::query(
|
||
"update resources
|
||
set status = 'published', updated_at = $3
|
||
where workspace_id = $1 and resource_id = $2 and updated_at = $4",
|
||
)
|
||
.bind(request.workspace_id.as_str())
|
||
.bind(request.resource_id.as_str())
|
||
.bind(next_updated_at)
|
||
.bind(recorded_updated_at)
|
||
.execute(&mut *transaction)
|
||
.await
|
||
.map_err(map_write_error)?
|
||
.rows_affected();
|
||
if updated != 1 {
|
||
return Err(ResourceError::Stale);
|
||
}
|
||
|
||
let record = read_publication(
|
||
&mut transaction,
|
||
&request.workspace_id,
|
||
&request.resource_id,
|
||
version,
|
||
)
|
||
.await?
|
||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||
transaction
|
||
.commit()
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
Ok(record)
|
||
}
|
||
}
|
||
|
||
async fn read_draft(
|
||
transaction: &mut Transaction<'_, Postgres>,
|
||
workspace_id: &WorkspaceId,
|
||
resource_id: &ResourceId,
|
||
) -> Result<Option<ResourceDraftRecord>, ResourceError> {
|
||
let row = sqlx::query(DRAFT_SELECT)
|
||
.bind(workspace_id.as_str())
|
||
.bind(resource_id.as_str())
|
||
.fetch_optional(&mut **transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
row.as_ref().map(map_draft).transpose()
|
||
}
|
||
|
||
async fn read_current_version(
|
||
transaction: &mut Transaction<'_, Postgres>,
|
||
workspace_id: &WorkspaceId,
|
||
resource_id: &ResourceId,
|
||
) -> Result<Option<ResourceVersionRecord>, ResourceError> {
|
||
let row = sqlx::query(VERSION_SELECT)
|
||
.bind(workspace_id.as_str())
|
||
.bind(resource_id.as_str())
|
||
.fetch_optional(&mut **transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
row.as_ref().map(map_version).transpose()
|
||
}
|
||
|
||
async fn read_publication(
|
||
transaction: &mut Transaction<'_, Postgres>,
|
||
workspace_id: &WorkspaceId,
|
||
resource_id: &ResourceId,
|
||
version: u32,
|
||
) -> Result<Option<ResourcePublicationRecord>, ResourceError> {
|
||
let row = sqlx::query(PUBLICATION_SELECT)
|
||
.bind(workspace_id.as_str())
|
||
.bind(resource_id.as_str())
|
||
.bind(version_number(version)?)
|
||
.fetch_optional(&mut **transaction)
|
||
.await
|
||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||
row.as_ref().map(map_publication).transpose()
|
||
}
|
||
|
||
fn map_draft(row: &PgRow) -> Result<ResourceDraftRecord, ResourceError> {
|
||
let resource = ResourceRecord {
|
||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id").map_err(integrity)?),
|
||
uri: row.try_get("uri").map_err(integrity)?,
|
||
name: row.try_get("name").map_err(integrity)?,
|
||
description: row.try_get("description").map_err(integrity)?,
|
||
status: parse_status(&row.try_get::<String, _>("status").map_err(integrity)?)?,
|
||
kind: row.try_get("kind").map_err(integrity)?,
|
||
current_draft_version: u32::try_from(
|
||
row.try_get::<i32, _>("current_draft_version")
|
||
.map_err(integrity)?,
|
||
)
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
latest_published_version: row
|
||
.try_get::<Option<i32>, _>("latest_published_version")
|
||
.map_err(integrity)?
|
||
.map(u32::try_from)
|
||
.transpose()
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
created_at: row.try_get("resource_created_at").map_err(integrity)?,
|
||
updated_at: row.try_get("resource_updated_at").map_err(integrity)?,
|
||
};
|
||
let version = map_version(row)?;
|
||
Ok(ResourceDraftRecord { resource, version })
|
||
}
|
||
|
||
fn parse_status(value: &str) -> Result<ResourceStatus, ResourceError> {
|
||
match value {
|
||
"draft" => Ok(ResourceStatus::Draft),
|
||
"published" => Ok(ResourceStatus::Published),
|
||
"archived" => Ok(ResourceStatus::Archived),
|
||
_ => Err(ResourceError::ArtifactIntegrity),
|
||
}
|
||
}
|
||
|
||
fn map_version(row: &PgRow) -> Result<ResourceVersionRecord, ResourceError> {
|
||
Ok(ResourceVersionRecord {
|
||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(integrity)?)
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
kind: row.try_get("version_kind").map_err(integrity)?,
|
||
mime_type: row.try_get("version_mime_type").map_err(integrity)?,
|
||
size_bytes: row.try_get("version_size_bytes").map_err(integrity)?,
|
||
digest: row.try_get("version_digest").map_err(integrity)?,
|
||
sensitivity: row.try_get("version_sensitivity").map_err(integrity)?,
|
||
source_kind: row.try_get("version_source_kind").map_err(integrity)?,
|
||
created_at: row.try_get("version_created_at").map_err(integrity)?,
|
||
superseded_at: row.try_get("superseded_at").map_err(integrity)?,
|
||
})
|
||
}
|
||
|
||
fn map_publication(row: &PgRow) -> Result<ResourcePublicationRecord, ResourceError> {
|
||
Ok(ResourcePublicationRecord {
|
||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id").map_err(integrity)?),
|
||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(integrity)?)
|
||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||
uri: row.try_get("uri").map_err(integrity)?,
|
||
name: row.try_get("name").map_err(integrity)?,
|
||
description: row.try_get("description").map_err(integrity)?,
|
||
kind: row.try_get("kind").map_err(integrity)?,
|
||
mime_type: row.try_get("mime_type").map_err(integrity)?,
|
||
size_bytes: row.try_get("size_bytes").map_err(integrity)?,
|
||
digest: row.try_get("digest").map_err(integrity)?,
|
||
sensitivity: row.try_get("sensitivity").map_err(integrity)?,
|
||
source_kind: row.try_get("source_kind").map_err(integrity)?,
|
||
published_at: row.try_get("published_at").map_err(integrity)?,
|
||
})
|
||
}
|
||
|
||
fn integrity(_: sqlx::Error) -> ResourceError {
|
||
ResourceError::ArtifactIntegrity
|
||
}
|
||
|
||
fn parse_sensitivity(value: &str) -> Result<ArtifactSourceSensitivity, ResourceError> {
|
||
match ResourceSensitivity::parse(value) {
|
||
Some(ResourceSensitivity::Public) => Ok(ArtifactSourceSensitivity::Public),
|
||
Some(ResourceSensitivity::Internal) => Ok(ArtifactSourceSensitivity::Internal),
|
||
Some(ResourceSensitivity::Secret) => Ok(ArtifactSourceSensitivity::Secret),
|
||
None => Err(ResourceError::StorageUnavailable),
|
||
}
|
||
}
|
||
|
||
fn size_bytes(artifact: &crank_artifacts::RegisteredArtifact) -> Result<i64, ResourceError> {
|
||
i64::try_from(artifact.size_bytes()).map_err(|_| ResourceError::StorageUnavailable)
|
||
}
|
||
|
||
/// Версия вне представимого БД диапазона не может существовать как Published
|
||
/// Version: exact publication lookup отвечает sanitized NotFound, а не отказом
|
||
/// хранилища (TL F4). Draft-разрешение сохраняет прежнюю taxonomy.
|
||
fn published_version_number(version: u32) -> Result<i32, ResourceError> {
|
||
i32::try_from(version).map_err(|_| ResourceError::NotFound)
|
||
}
|
||
|
||
fn version_number(version: u32) -> Result<i32, ResourceError> {
|
||
i32::try_from(version).map_err(|_| ResourceError::StorageUnavailable)
|
||
}
|
||
|
||
/// Детерминированный owning ref версии: `src_<resource-tail>_v<version>`.
|
||
fn version_source_id(
|
||
resource_id: &ResourceId,
|
||
version: u32,
|
||
) -> Result<ArtifactSourceId, ResourceError> {
|
||
let tail = resource_tail(resource_id)?;
|
||
Ok(ArtifactSourceId::new(format!("src_{tail}_v{version}")))
|
||
}
|
||
|
||
/// Owning ref публикации: отдельный от Draft-ссылки, поэтому Draft update не может
|
||
/// отсоединить published bytes.
|
||
fn publication_source_id(
|
||
resource_id: &ResourceId,
|
||
version: u32,
|
||
) -> Result<ArtifactSourceId, ResourceError> {
|
||
let tail = resource_tail(resource_id)?;
|
||
Ok(ArtifactSourceId::new(format!("src_{tail}_v{version}_pub")))
|
||
}
|
||
|
||
fn resource_tail(resource_id: &ResourceId) -> Result<String, ResourceError> {
|
||
let tail = resource_id
|
||
.as_str()
|
||
.strip_prefix(RESOURCE_ID_PREFIX)
|
||
.unwrap_or_else(|| resource_id.as_str());
|
||
if tail.is_empty()
|
||
|| tail.len() > MAX_SOURCE_TAIL_BYTES
|
||
|| !tail
|
||
.bytes()
|
||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
|
||
{
|
||
return Err(ResourceError::StorageUnavailable);
|
||
}
|
||
Ok(tail.to_owned())
|
||
}
|
||
|
||
/// Микросекундная точность: Postgres `timestamptz` хранит микросекунды, поэтому
|
||
/// optimistic-precondition не должен зависеть от наносекунд клиента.
|
||
pub(crate) fn truncate_to_micros(value: time::OffsetDateTime) -> time::OffsetDateTime {
|
||
let nanos = value.nanosecond();
|
||
value
|
||
.replace_nanosecond(nanos - nanos % 1_000)
|
||
.unwrap_or(value)
|
||
}
|
||
|
||
fn map_registry_error(error: RegistryError) -> ResourceError {
|
||
match error {
|
||
RegistryError::WorkspaceNotFound { .. } => ResourceError::NotFound,
|
||
_ => ResourceError::StorageUnavailable,
|
||
}
|
||
}
|
||
|
||
/// Классификация отказа записи: конфликты uniqueness дают стабильные 409-коды,
|
||
/// прочие FK/CHECK-отказы — 500 с фиксированным сообщением (D-20 шаг I).
|
||
fn map_write_error(error: sqlx::Error) -> ResourceError {
|
||
let Some(database) = error.as_database_error() else {
|
||
return ResourceError::StorageUnavailable;
|
||
};
|
||
if database.code().as_deref() != Some("23505") {
|
||
return ResourceError::StorageUnavailable;
|
||
}
|
||
match database.constraint() {
|
||
Some("resources_workspace_uri_unique") => ResourceError::UriDuplicate,
|
||
Some("resources_workspace_name_unique") => ResourceError::NameDuplicate,
|
||
_ => ResourceError::StorageUnavailable,
|
||
}
|
||
}
|