[skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
1 parent
1b6db09bd1
commit
301dce301a
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,91 @@
|
||||
//! Архив Resource (Story 3.7 AC05): exact CAS и lifecycle-переход в одной транзакции.
|
||||
//!
|
||||
//! Вынесен из `postgres/resource.rs`, чтобы файл оставался в пределах
|
||||
//! rust-code-health; поведение и SQL не менялись. Меняются только
|
||||
//! `status`/`updated_at` строки `resources`: уже созданные publications, их owning
|
||||
//! refs и блобы не трогаются, поэтому точные Published Version остаются читаемыми
|
||||
//! и неизменными.
|
||||
|
||||
use crank_core::resource::{ResourceError, ResourceLifecycle, ResourceLifecycleAction};
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::model::resource::{ArchiveResourceRequest, ResourceDraftRecord};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::{integrity, map_write_error, parse_status, read_draft, truncate_to_micros};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Архив Resource: меняется только lifecycle/ревизия карточки.
|
||||
pub async fn archive_resource(
|
||||
&self,
|
||||
request: ArchiveResourceRequest,
|
||||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let row = sqlx::query(
|
||||
"select status, 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)?;
|
||||
// F: точный precondition. Старый CAS обязан победить lifecycle-отказ: повтор
|
||||
// архива прежней карточкой — stale (428), а не «уже архивирован».
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let status = parse_status(&row.try_get::<String, _>("status").map_err(integrity)?)?;
|
||||
// Archived -> Archived недопустим: актуальный CAS на уже архивном Resource
|
||||
// даёт sanitized lifecycle-отказ (409), без 500 и без mutation.
|
||||
ResourceLifecycle::transition(status, ResourceLifecycleAction::Archive)?;
|
||||
|
||||
let archived_at = truncate_to_micros(request.archived_at);
|
||||
let next_updated_at = if archived_at > recorded_updated_at {
|
||||
archived_at
|
||||
} else {
|
||||
recorded_updated_at + time::Duration::microseconds(1)
|
||||
};
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set status = 'archived', 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_draft(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Сверка строки `PUBLICATION_SELECT` (вынесено из `postgres/resource.rs` под
|
||||
//! лимит rust-code-health).
|
||||
//!
|
||||
//! Сырой Admin-resolver и живой MCP-gate используют одну и ту же metadata/integrity
|
||||
//! проверку; gate добавляет отдельную tombstone-проверку, а не заменяет её.
|
||||
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::Row;
|
||||
use sqlx::postgres::PgRow;
|
||||
|
||||
use crate::model::resource::{ResolvedResourcePublication, ResourcePublicationRecord};
|
||||
|
||||
use super::{integrity, map_publication};
|
||||
|
||||
/// Metadata/integrity-сверка строки `PUBLICATION_SELECT`.
|
||||
pub(super) fn validated_publication(
|
||||
row: &PgRow,
|
||||
) -> Result<ResourcePublicationRecord, ResourceError> {
|
||||
let blob_digest: String = row.try_get("blob_digest").map_err(integrity)?;
|
||||
let source_mime_type: String = row.try_get("source_mime_type").map_err(integrity)?;
|
||||
let source_sensitivity: String = row.try_get("source_sensitivity").map_err(integrity)?;
|
||||
let source_lifecycle: String = row.try_get("source_lifecycle").map_err(integrity)?;
|
||||
let blob_size_bytes: i64 = row.try_get("blob_size_bytes").map_err(integrity)?;
|
||||
let blob_lifecycle: String = row.try_get("blob_lifecycle").map_err(integrity)?;
|
||||
|
||||
let publication = map_publication(row)?;
|
||||
if blob_digest != publication.digest
|
||||
|| source_mime_type != publication.mime_type
|
||||
|| source_sensitivity != publication.sensitivity
|
||||
|| source_lifecycle != "active"
|
||||
|| blob_lifecycle != "available"
|
||||
|| blob_size_bytes != publication.size_bytes
|
||||
{
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(publication)
|
||||
}
|
||||
|
||||
/// Полная разрешённая публикация из строки `PUBLICATION_SELECT` (metadata + ref).
|
||||
pub(super) fn resolved_publication(
|
||||
row: &PgRow,
|
||||
) -> Result<ResolvedResourcePublication, ResourceError> {
|
||||
let publication = validated_publication(row)?;
|
||||
let artifact_ref = ArtifactRef::parse(
|
||||
&row.try_get::<String, _>("artifact_ref")
|
||||
.map_err(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if artifact_ref.digest_hex() != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(ResolvedResourcePublication {
|
||||
publication,
|
||||
artifact_ref,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Отозван ли Resource (Story 3.8). Точная проверка живой eligibility без чтения
|
||||
/// metadata или bytes: используется рендером Prompt, чтобы pinned-версия не отдавалась
|
||||
/// после отзыва (Story 3.16, AC6/AC8).
|
||||
pub async fn resource_is_revoked(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<bool, ResourceError> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Точная Published Version с полной сверкой owning-ссылки и blob metadata.
|
||||
pub async fn resolve_resource_publication(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResolvedResourcePublication, ResourceError> {
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(published_version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let publication = resolved_publication(&row)?;
|
||||
Ok(publication)
|
||||
}
|
||||
|
||||
/// Workspace-local разрешение explicit `include:` цели: только уже опубликованная
|
||||
/// metadata этого workspace. Глобального поиска и раскрытия чужих сущностей нет.
|
||||
pub async fn published_resource_sensitivity_by_uri(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
uri: &str,
|
||||
) -> Result<Option<String>, ResourceError> {
|
||||
let sensitivity = sqlx::query(
|
||||
"select p.sensitivity
|
||||
from resource_publications p
|
||||
where p.workspace_id = $1 and p.uri = $2
|
||||
order by p.published_at desc, p.version desc
|
||||
limit 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(uri)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.map(|row| row.try_get::<String, _>("sensitivity"))
|
||||
.transpose()
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
Ok(sensitivity)
|
||||
}
|
||||
|
||||
/// Карточка Draft: строка Resource и её текущая версия.
|
||||
pub async fn get_resource_draft(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let row = sqlx::query(DRAFT_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
map_draft(&row)
|
||||
}
|
||||
|
||||
/// Ограниченная страница Draft-ов workspace.
|
||||
pub async fn list_resource_drafts(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ResourceDraftRecord>, ResourceError> {
|
||||
let limit = limit.clamp(1, MAX_RESOURCE_DRAFT_PAGE_SIZE);
|
||||
let rows = sqlx::query(DRAFT_LIST_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(i64::from(limit))
|
||||
.fetch_all(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
rows.iter().map(map_draft).collect()
|
||||
}
|
||||
|
||||
/// Workspace-scoped разрешение конкретной версии с полной metadata-сверкой.
|
||||
pub async fn resolve_resource_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
self.resolve_version(workspace_id, resource_id, Some(version))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Workspace-scoped разрешение текущей черновой версии.
|
||||
pub async fn resolve_current_resource_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
self.resolve_version(workspace_id, resource_id, None).await
|
||||
}
|
||||
|
||||
async fn resolve_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: Option<u32>,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
let row = sqlx::query(RESOLVE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version.map(version_number).transpose()?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let blob_digest: String = row.try_get("blob_digest").map_err(integrity)?;
|
||||
let source_mime_type: String = row.try_get("source_mime_type").map_err(integrity)?;
|
||||
let source_sensitivity: String = row.try_get("source_sensitivity").map_err(integrity)?;
|
||||
let source_lifecycle: String = row.try_get("source_lifecycle").map_err(integrity)?;
|
||||
let artifact_ref_text: String = row.try_get("artifact_ref").map_err(integrity)?;
|
||||
let blob_size_bytes: i64 = row.try_get("blob_size_bytes").map_err(integrity)?;
|
||||
let blob_lifecycle: String = row.try_get("blob_lifecycle").map_err(integrity)?;
|
||||
|
||||
// Снимок строк `resources`/`resource_versions` того же запроса: metadata
|
||||
// ответа и bytes берутся из него, а не из второго чтения (P3).
|
||||
let snapshot = map_draft(&row)?;
|
||||
let digest = snapshot.version.digest.clone();
|
||||
let mime_type = snapshot.version.mime_type.clone();
|
||||
let sensitivity = snapshot.version.sensitivity.clone();
|
||||
let size_bytes = snapshot.version.size_bytes;
|
||||
|
||||
if blob_digest != digest
|
||||
|| source_mime_type != mime_type
|
||||
|| source_sensitivity != sensitivity
|
||||
|| source_lifecycle != "active"
|
||||
|| blob_lifecycle != "available"
|
||||
|| blob_size_bytes != size_bytes
|
||||
{
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
let artifact_ref =
|
||||
ArtifactRef::parse(&artifact_ref_text).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if artifact_ref.digest_hex() != digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
Ok(ResolvedResourceVersion {
|
||||
snapshot,
|
||||
artifact_ref,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Resource security revocation (Story 3.8, owner decision A).
|
||||
//!
|
||||
//! Один tombstone на (workspace, Resource) — одновременно авторитетное состояние
|
||||
//! доступа и неизменяемая запись перехода. Отзыв закрывает все версии Resource во
|
||||
//! всех Agents, включая уже опубликованные snapshots; архив, immutable bytes и
|
||||
//! защищённое административное чтение сохраняются.
|
||||
//!
|
||||
//! Живая проверка доступа к MCP — только PostgreSQL, без cache/Valkey. Порядок
|
||||
//! блокировок: строка `resources` (якорь, FOR SHARE у чтения / FOR UPDATE у
|
||||
//! отзыва), затем свежий tombstone-lookup. `FOR SHARE` конфликтует с `FOR
|
||||
//! UPDATE`, поэтому revoke-first закрывает чтение до artifact bytes, а read-first
|
||||
//! линеаризует чтение до отзыва. Уже отправленные клиенту байты не отзываются.
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::postgres::PgRow;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use crate::AgentResourceBinding;
|
||||
use crate::model::resource::{
|
||||
BoundResourceTemplate, ResolvedResourcePublication, ResourcePublicationRecord,
|
||||
ResourceTemplateSourceRecord, RevokeResourceRequest,
|
||||
};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::publication::resolved_publication;
|
||||
use super::{PUBLICATION_SELECT, published_version_number};
|
||||
|
||||
/// Строка `resource_publications` шаблонной версии вместе с её определением: у шаблона нет
|
||||
/// owning artifact-ссылки, поэтому artifact-join из `PUBLICATION_SELECT` его не находит.
|
||||
const ADMITTED_TEMPLATE_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.definition_json, s.definition_digest from resource_publications p left join resource_template_sources s using(workspace_id, resource_id, version) where p.workspace_id=$1 and p.resource_id=$2 and p.version=$3 and p.source_kind='template'";
|
||||
|
||||
/// Transaction guard held while a template dispatch uses its shared Resource identity.
|
||||
pub struct AuthorizedResourceTemplateRead {
|
||||
transaction: Option<Transaction<'static, Postgres>>,
|
||||
}
|
||||
|
||||
impl AuthorizedResourceTemplateRead {
|
||||
pub async fn commit(mut self) -> Result<(), ResourceError> {
|
||||
self.transaction
|
||||
.take()
|
||||
.ok_or(ResourceError::StorageUnavailable)?
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
pub enum BoundResourceAdmission {
|
||||
/// Boxed: the resolved publication is much larger than the empty denial variant.
|
||||
Admitted(Box<ResolvedResourcePublication>),
|
||||
/// Valid published Resource template: it has no artifact/blob to resolve for a physical read,
|
||||
/// and its concrete URIs are the expanded ones discovered through `resources/templates/list`.
|
||||
Template,
|
||||
Revoked,
|
||||
}
|
||||
|
||||
/// Разрешённое чтение, удерживающее `FOR SHARE` на строке Resource до успешного
|
||||
/// commit. Пока guard жив, конкурентный отзыв ждёт; после отзыва новые проверки
|
||||
/// доступа запрещают чтение, а `Drop` без commit откатывает блокировку.
|
||||
pub struct AuthorizedResourceRead {
|
||||
publication: ResolvedResourcePublication,
|
||||
transaction: Option<Transaction<'static, Postgres>>,
|
||||
}
|
||||
|
||||
impl AuthorizedResourceRead {
|
||||
pub fn publication(&self) -> &ResolvedResourcePublication {
|
||||
&self.publication
|
||||
}
|
||||
|
||||
/// Успешное завершение удерживаемой транзакции. Ошибка commit — отказ чтения,
|
||||
/// а не выдача подготовленного content.
|
||||
pub async fn commit(mut self) -> Result<(), ResourceError> {
|
||||
let Some(transaction) = self.transaction.take() else {
|
||||
return Err(ResourceError::StorageUnavailable);
|
||||
};
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Resolve and admit exact template metadata while holding every Resource lock for the page.
|
||||
pub async fn list_admitted_resource_templates(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<BoundResourceTemplate>, ResourceError> {
|
||||
if bindings.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|b| b.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
let mut tx = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let locked = sqlx::query("select resource_id from resources where workspace_id=$1 and resource_id=any($2::text[]) order by resource_id asc for share")
|
||||
.bind(workspace_id).bind(&ids).fetch_all(&mut *tx).await.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.len() != ids.len() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let revoked = revoked_resource_ids(&mut tx, workspace_id, &ids).await?;
|
||||
let mut admitted = Vec::new();
|
||||
for binding in bindings {
|
||||
if revoked.iter().any(|id| id == binding.resource_id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let row = sqlx::query(ADMITTED_TEMPLATE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(published_version_number(binding.resource_version)?)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let Some(row) = row else { continue };
|
||||
admitted.push(bound_template_from_row(&row)?);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(admitted)
|
||||
}
|
||||
|
||||
/// Hold Resource identity stable and reject a revoked Resource while the admin
|
||||
/// test-read uses it, matching the same lock order as live template reads.
|
||||
pub async fn begin_authorized_resource_test_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
digest: &str,
|
||||
) -> Result<AuthorizedResourceTemplateRead, ResourceError> {
|
||||
let version = super::published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let row = sqlx::query("select r.status, r.current_draft_version, v.digest from resources r join resource_versions v on v.workspace_id=r.workspace_id and v.resource_id=r.resource_id and v.version=r.current_draft_version where r.workspace_id=$1 and r.resource_id=$2")
|
||||
.bind(workspace_id).bind(resource_id.as_str()).fetch_optional(&mut *transaction).await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?.ok_or(ResourceError::NotFound)?;
|
||||
let status: String = row
|
||||
.try_get("status")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let current_version: i32 = row
|
||||
.try_get("current_draft_version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let current_digest: String = row
|
||||
.try_get("digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if status == "archived" {
|
||||
return Err(ResourceError::InvalidLifecycleTransition {
|
||||
from: crank_core::resource::ResourceStatus::Archived,
|
||||
to: crank_core::resource::ResourceStatus::Draft,
|
||||
});
|
||||
}
|
||||
if current_version != version || current_digest != digest {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
Ok(AuthorizedResourceTemplateRead {
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the live Resource revocation lock until a dynamic template read completes.
|
||||
pub async fn begin_authorized_resource_template_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<AuthorizedResourceTemplateRead, ResourceError> {
|
||||
let version = published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let exists: bool = sqlx::query_scalar("select exists(select 1 from resource_template_sources s join resource_publications p using(workspace_id,resource_id,version) where s.workspace_id=$1 and s.resource_id=$2 and s.version=$3 and p.source_kind='template')")
|
||||
.bind(workspace_id).bind(resource_id.as_str()).bind(version)
|
||||
.fetch_one(&mut *transaction).await.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if !exists {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
Ok(AuthorizedResourceTemplateRead {
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Необратимый audited отзыв Resource.
|
||||
///
|
||||
/// READ COMMITTED: `resources FOR UPDATE` → отдельный свежий tombstone-lookup →
|
||||
/// INSERT первого события → COMMIT. Повтор и две конкурентные команды дают одну
|
||||
/// строку с actor/time первого успеха; ошибка INSERT/commit не даёт ложный 204.
|
||||
pub async fn revoke_resource(
|
||||
&self,
|
||||
request: RevokeResourceRequest,
|
||||
) -> Result<(), ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let locked = sqlx::query(
|
||||
"select 1 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)?;
|
||||
if locked.is_none() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
|
||||
// Отдельный statement после блокировки: видит только закоммиченный отзыв,
|
||||
// поэтому конкурент, ждавший на FOR UPDATE, не пишет второе событие.
|
||||
if !is_revoked(
|
||||
&mut transaction,
|
||||
request.workspace_id.as_str(),
|
||||
request.resource_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
sqlx::query(
|
||||
"insert into resource_security_revocations (
|
||||
workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id
|
||||
) values ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(request.revoked_at)
|
||||
.bind(request.actor_user_id.as_str())
|
||||
.bind(request.request_id.as_str())
|
||||
.bind(request.trace_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
}
|
||||
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Живой MCP-gate чтения: `FOR SHARE` на Resource, свежий tombstone-check,
|
||||
/// затем metadata/integrity. `Revoked` возвращается до любого artifact byte.
|
||||
pub async fn begin_authorized_resource_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<AuthorizedResourceRead, ResourceError> {
|
||||
let version = published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let publication = resolved_publication(&row)?;
|
||||
Ok(AuthorizedResourceRead {
|
||||
publication,
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Живой MCP-gate страницы списка: shared-блокировки всех Resource диапазона в
|
||||
/// порядке `resource_id ASC`, затем свежие tombstones. Revoked пропускается;
|
||||
/// corruption/отсутствие publication — ошибка страницы, не partial success.
|
||||
pub async fn list_admitted_resource_publications(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<BoundResourceAdmission>, ResourceError> {
|
||||
if bindings.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
resource_ids.sort();
|
||||
resource_ids.dedup();
|
||||
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let locked = sqlx::query(
|
||||
"select resource_id from resources
|
||||
where workspace_id = $1 and resource_id = any($2::text[])
|
||||
order by resource_id asc
|
||||
for share",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.len() != resource_ids.len() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let revoked = revoked_resource_ids(&mut transaction, workspace_id, &resource_ids).await?;
|
||||
|
||||
let mut admissions = Vec::with_capacity(bindings.len());
|
||||
for binding in bindings {
|
||||
if revoked.iter().any(|id| id == binding.resource_id.as_str()) {
|
||||
admissions.push(BoundResourceAdmission::Revoked);
|
||||
continue;
|
||||
}
|
||||
let version = published_version_number(binding.resource_version)?;
|
||||
// A published Resource template has no owning artifact, so the artifact join of
|
||||
// `PUBLICATION_SELECT` can never match it: resolve its own metadata instead of
|
||||
// turning a valid binding into an internal error for the whole page.
|
||||
let template_row = sqlx::query(ADMITTED_TEMPLATE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if let Some(row) = template_row {
|
||||
// Integrity contract kept: publication digest must equal the definition digest.
|
||||
bound_template_from_row(&row)?;
|
||||
admissions.push(BoundResourceAdmission::Template);
|
||||
continue;
|
||||
}
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
admissions.push(BoundResourceAdmission::Admitted(Box::new(
|
||||
resolved_publication(&row)?,
|
||||
)));
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(admissions)
|
||||
}
|
||||
}
|
||||
|
||||
/// Точная шаблонная публикация из строки `ADMITTED_TEMPLATE_SELECT`: metadata плюс определение.
|
||||
/// Digest определения обязан совпадать с digest публикации, иначе это integrity-отказ, а не
|
||||
/// «нет шаблона».
|
||||
fn bound_template_from_row(row: &PgRow) -> Result<BoundResourceTemplate, ResourceError> {
|
||||
let version = u32::try_from(
|
||||
row.try_get::<i32, _>("version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let publication = ResourcePublicationRecord {
|
||||
resource_id: ResourceId::new(
|
||||
row.try_get::<String, _>("resource_id")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
),
|
||||
version,
|
||||
uri: row
|
||||
.try_get("uri")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
name: row
|
||||
.try_get("name")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
description: row
|
||||
.try_get("description")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
kind: row
|
||||
.try_get("kind")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
mime_type: row
|
||||
.try_get("mime_type")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
size_bytes: row
|
||||
.try_get("size_bytes")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
digest: row
|
||||
.try_get("digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
sensitivity: row
|
||||
.try_get("sensitivity")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
source_kind: row
|
||||
.try_get("source_kind")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
published_at: row
|
||||
.try_get("published_at")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
};
|
||||
let source = ResourceTemplateSourceRecord {
|
||||
definition_json: row
|
||||
.try_get("definition_json")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
definition_digest: row
|
||||
.try_get("definition_digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
};
|
||||
if source.definition_digest != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(BoundResourceTemplate {
|
||||
publication,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Есть ли закоммиченный отзыв этого Resource в текущей транзакции.
|
||||
pub(super) async fn is_revoked(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
) -> Result<bool, ResourceError> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Shared-блокировка якорной строки Resource; отсутствующая/чужая строка — NotFound.
|
||||
async fn lock_resource_shared(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
) -> Result<(), ResourceError> {
|
||||
let locked = sqlx::query(
|
||||
"select 1 from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for share",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.is_none() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Id отозванных Resource из заданного набора (одна свежая проверка на страницу).
|
||||
async fn revoked_resource_ids(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_ids: &[String],
|
||||
) -> Result<Vec<String>, ResourceError> {
|
||||
let rows = sqlx::query(
|
||||
"select resource_id from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = any($2::text[])",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_ids)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
row.try_get::<String, _>("resource_id")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
//! Persistence Story 3.10 (FR-16): byte-less REST-backed Resource templates (V20).
|
||||
//!
|
||||
//! Определение шаблона хранится version-keyed строкой `resource_template_sources`;
|
||||
//! версия помечена `source_kind='template'`, не имеет owning artifact-ссылки и
|
||||
//! несёт `size_bytes = 0`, а `digest` — детерминированный digest определения.
|
||||
//! Прежние artifact-строки сохраняют собственные CHECK/FK без изменений.
|
||||
//!
|
||||
//! Все мутации — одна транзакция: строка `resources` блокируется первой, затем
|
||||
//! optimistic precondition, затем версия/определение. Publication snapshot
|
||||
//! неизменяем, потому что определение insert-only (UPDATE запрещён trigger-ом).
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use crate::model::resource::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
ResourcePublicationRecord, ResourceTemplateDraftRecord, ResourceTemplateSourceRecord,
|
||||
UpdateResourceTemplateDraftRequest,
|
||||
};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::super::artifact_source::require_workspace;
|
||||
use super::{
|
||||
DRAFT_SELECT, integrity, map_registry_error, map_write_error, read_draft, revocation,
|
||||
truncate_to_micros, version_number,
|
||||
};
|
||||
|
||||
const TEMPLATE_SOURCE_SELECT: &str = "select definition_json, definition_digest
|
||||
from resource_template_sources
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3";
|
||||
|
||||
const TEMPLATE_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
|
||||
from resource_publications p
|
||||
where p.workspace_id = $1 and p.resource_id = $2 and p.version = $3
|
||||
and p.source_kind = 'template'";
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Создание template Draft без байтов: ресурс, версия 1 и определение в одной транзакции.
|
||||
pub async fn create_resource_template_draft(
|
||||
&self,
|
||||
request: CreateResourceTemplateDraftRequest,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
require_workspace(&mut transaction, &request.workspace_id)
|
||||
.await
|
||||
.map_err(map_registry_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)?;
|
||||
|
||||
// Template-версия: artifact_source_id null и size 0 допускаются только
|
||||
// CHECK-ом для source_kind='template'.
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, source_kind, created_at, superseded_at
|
||||
) values ($1, $2, 1, $3, $4, 0, $5, $6, null, 'template', $7, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(&request.kind)
|
||||
.bind(&request.mime_type)
|
||||
.bind(&request.definition_digest)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
insert_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
1,
|
||||
&request.definition_json,
|
||||
&request.definition_digest,
|
||||
request.created_at,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let record = read_template(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Новая версия template Draft: прежняя версия остаётся (superseded) вместе со
|
||||
/// своим определением, поэтому уже опубликованный snapshot не меняется.
|
||||
pub async fn update_resource_template_draft(
|
||||
&self,
|
||||
request: UpdateResourceTemplateDraftRequest,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
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(integrity)?;
|
||||
let recorded_updated_at: time::OffsetDateTime =
|
||||
row.try_get("updated_at").map_err(integrity)?;
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let current_version =
|
||||
u32::try_from(current_version).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let source_kind: String = sqlx::query(
|
||||
"select source_kind
|
||||
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)?
|
||||
.try_get("source_kind")
|
||||
.map_err(integrity)?;
|
||||
if source_kind != "template" {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
let now = truncate_to_micros(time::OffsetDateTime::now_utc());
|
||||
let next_version = current_version
|
||||
.checked_add(1)
|
||||
.ok_or(ResourceError::StorageUnavailable)?;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, source_kind, created_at, superseded_at
|
||||
) select r.workspace_id, r.resource_id, $3, r.kind, $4, 0, $5, $6, null,
|
||||
'template', $7, 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(&request.definition_digest)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
insert_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
next_version,
|
||||
&request.definition_json,
|
||||
&request.definition_digest,
|
||||
now,
|
||||
)
|
||||
.await?;
|
||||
|
||||
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_template(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Публикация template Draft: publication-снимок ссылается на ту же
|
||||
/// version-keyed definition-строку (artifact-ссылки нет).
|
||||
pub async fn publish_resource_template_version(
|
||||
&self,
|
||||
request: PublishResourceTemplateVersionRequest,
|
||||
) -> Result<(ResourcePublicationRecord, ResourceTemplateSourceRecord), 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(integrity)?;
|
||||
if revocation::is_revoked(
|
||||
&mut transaction,
|
||||
request.workspace_id.as_str(),
|
||||
request.resource_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
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(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let version_row = sqlx::query(
|
||||
"select version, mime_type, size_bytes, digest, sensitivity, source_kind
|
||||
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(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let digest: String = version_row.try_get("digest").map_err(integrity)?;
|
||||
let size_bytes: i64 = version_row.try_get("size_bytes").map_err(integrity)?;
|
||||
let mime_type: String = version_row.try_get("mime_type").map_err(integrity)?;
|
||||
let sensitivity: String = version_row.try_get("sensitivity").map_err(integrity)?;
|
||||
let source_kind: String = version_row.try_get("source_kind").map_err(integrity)?;
|
||||
// TOCTOU: Draft мог измениться между проверкой и коммитом — stale, не дубль.
|
||||
if source_kind != "template"
|
||||
|| size_bytes != 0
|
||||
|| version != request.expected_version
|
||||
|| current_draft_version != version
|
||||
|| digest != request.expected_digest
|
||||
{
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
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)
|
||||
};
|
||||
sqlx::query(
|
||||
"insert into resource_publications (
|
||||
workspace_id, resource_id, version, uri, name, description, kind,
|
||||
mime_type, size_bytes, digest, sensitivity, artifact_source_id, source_kind,
|
||||
published_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, 0, $9, $10, null, 'template', $11)",
|
||||
)
|
||||
.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(&digest)
|
||||
.bind(&sensitivity)
|
||||
.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 publication = read_template_publication(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
version,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
let source = read_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
version,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok((publication, source))
|
||||
}
|
||||
|
||||
/// Текущий template Draft вместе с определением. `NotFound` для static Resource.
|
||||
pub async fn get_resource_template_draft(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let row = sqlx::query(DRAFT_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let source_kind: String = row.try_get("version_source_kind").map_err(integrity)?;
|
||||
if source_kind != "template" {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let snapshot = super::map_draft(&row)?;
|
||||
let source =
|
||||
read_definition_on_pool(self, workspace_id, resource_id, snapshot.version.version)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
Ok(ResourceTemplateDraftRecord { snapshot, source })
|
||||
}
|
||||
|
||||
/// Определение точной версии (draft или published — строка та же).
|
||||
pub async fn get_resource_template_source(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResourceTemplateSourceRecord, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
map_definition(&row)
|
||||
}
|
||||
|
||||
/// Точная Published Version шаблона вместе с его определения снимком.
|
||||
pub async fn resolve_resource_template_publication(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<(ResourcePublicationRecord, ResourceTemplateSourceRecord), ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
// Exact published version вне i32-диапазона — sanitized NotFound, не storage.
|
||||
.bind(super::published_version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let publication = super::map_publication(&row)?;
|
||||
let source = self
|
||||
.get_resource_template_source(workspace_id, resource_id, version)
|
||||
.await?;
|
||||
if source.definition_digest != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok((publication, source))
|
||||
}
|
||||
}
|
||||
|
||||
async fn insert_definition(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
definition_json: &str,
|
||||
definition_digest: &str,
|
||||
created_at: time::OffsetDateTime,
|
||||
) -> Result<(), ResourceError> {
|
||||
sqlx::query(
|
||||
"insert into resource_template_sources (
|
||||
workspace_id, resource_id, version, definition_json, definition_digest, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.bind(definition_json)
|
||||
.bind(definition_digest)
|
||||
.bind(created_at)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_definition(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourceTemplateSourceRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_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_definition).transpose()
|
||||
}
|
||||
|
||||
async fn read_definition_on_pool(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourceTemplateSourceRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(registry.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_definition).transpose()
|
||||
}
|
||||
|
||||
async fn read_template(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<Option<ResourceTemplateDraftRecord>, ResourceError> {
|
||||
let Some(snapshot) = read_draft(transaction, workspace_id, resource_id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let version = snapshot.version.version;
|
||||
let source = read_definition(transaction, workspace_id, resource_id, version)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
Ok(Some(ResourceTemplateDraftRecord { snapshot, source }))
|
||||
}
|
||||
|
||||
async fn read_template_publication(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourcePublicationRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_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(super::map_publication).transpose()
|
||||
}
|
||||
|
||||
fn map_definition(
|
||||
row: &sqlx::postgres::PgRow,
|
||||
) -> Result<ResourceTemplateSourceRecord, ResourceError> {
|
||||
Ok(ResourceTemplateSourceRecord {
|
||||
definition_json: row.try_get("definition_json").map_err(integrity)?,
|
||||
definition_digest: row.try_get("definition_digest").map_err(integrity)?,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user