feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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
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.
This commit is contained in:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -1,3 +1,9 @@
|
||||
use super::agent_prompt_bindings::{
|
||||
ensure_agent_prompt_bindings_not_archived, replace_agent_prompt_bindings_rows,
|
||||
};
|
||||
use super::agent_resource_bindings::{
|
||||
ensure_agent_bindings_not_revoked, replace_agent_resource_bindings_rows,
|
||||
};
|
||||
use super::*;
|
||||
use crate::model::{AgentStateExpectation, UpdateAgentSummaryRequest};
|
||||
|
||||
@@ -224,6 +230,8 @@ impl PostgresRegistry {
|
||||
};
|
||||
|
||||
let bindings = self.list_agent_bindings(agent_id, version).await?;
|
||||
let resource_bindings = self.list_agent_resource_bindings(agent_id, version).await?;
|
||||
let prompt_bindings = self.list_agent_prompt_bindings(agent_id, version).await?;
|
||||
Ok(Some(build_agent_version_record(
|
||||
&summary,
|
||||
row.version,
|
||||
@@ -232,6 +240,8 @@ impl PostgresRegistry {
|
||||
row.tool_selection_policy_json,
|
||||
row.created_at,
|
||||
bindings,
|
||||
resource_bindings,
|
||||
prompt_bindings,
|
||||
)?))
|
||||
}
|
||||
|
||||
@@ -265,7 +275,7 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<(), RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, false)
|
||||
self.save_agent_catalog_config_inner(request, false, &[])
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
@@ -274,13 +284,27 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<u32, RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, true).await
|
||||
self.save_agent_catalog_config_inner(request, true, &[])
|
||||
.await
|
||||
}
|
||||
|
||||
/// Как [`Self::save_agent_catalog_config_editable`], но с точными Prompt
|
||||
/// bindings Draft-версии (Story 3.13). Существующие вызовы без Prompt
|
||||
/// сохраняют прежнюю сигнатуру и семантику.
|
||||
pub async fn save_agent_catalog_config_editable_with_prompts(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) -> Result<u32, RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, true, prompt_bindings)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn save_agent_catalog_config_inner(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
allow_fork: bool,
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) -> Result<u32, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let agent_row = Self::lock_agent_and_validate_expected_state(
|
||||
@@ -350,6 +374,22 @@ impl PostgresRegistry {
|
||||
request.bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_resource_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
draft.version,
|
||||
request.resource_bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_prompt_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
draft.version,
|
||||
prompt_bindings,
|
||||
)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update agents
|
||||
set current_draft_version = $3,
|
||||
@@ -394,6 +434,22 @@ impl PostgresRegistry {
|
||||
request.bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_resource_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.agent_version,
|
||||
request.resource_bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_prompt_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.agent_version,
|
||||
prompt_bindings,
|
||||
)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update agents
|
||||
set updated_at = now()
|
||||
@@ -645,6 +701,14 @@ impl PostgresRegistry {
|
||||
actual: request.version,
|
||||
});
|
||||
}
|
||||
// Повторная публикация уже опубликованной версии идемпотентна и не даёт
|
||||
// второго bump catalog_revision (Story 3.13 AC2). После unpublish Agent
|
||||
// снова Draft, поэтому такое состояние требует обычной публикации.
|
||||
if latest_published_version == Some(request.version)
|
||||
&& agent_status == AgentStatus::Published
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let catalog_revision: i64 = agent_row.try_get("catalog_revision")?;
|
||||
let next_catalog_revision = catalog_revision
|
||||
.checked_add(1)
|
||||
@@ -670,6 +734,26 @@ impl PostgresRegistry {
|
||||
});
|
||||
}
|
||||
|
||||
// Story 3.8: публикация Agent — тоже точка выдачи Resource-доступа. Текущая
|
||||
// версия bindings перечитывается внутри этой транзакции после Agent lock,
|
||||
// Resources блокируются в порядке resource_id ASC, и отозванный Resource
|
||||
// отменяет публикацию до любой мутации каталога.
|
||||
ensure_agent_bindings_not_revoked(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.version,
|
||||
)
|
||||
.await?;
|
||||
// Story 3.13: archived Prompt не может войти в новую публикацию Agent.
|
||||
ensure_agent_prompt_bindings_not_archived(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.version,
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"update agent_versions
|
||||
set status = $1
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use super::agent_prompt_bindings::read_agent_prompt_bindings;
|
||||
use super::agent_resource_bindings::read_agent_resource_bindings;
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -12,6 +14,7 @@ impl PostgresRegistry {
|
||||
.await?;
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
a.id as agent_id,
|
||||
pa.version,
|
||||
pa.catalog_revision,
|
||||
av.tool_selection_policy_json
|
||||
@@ -35,6 +38,13 @@ impl PostgresRegistry {
|
||||
let tools = query_published_agent_tools(&mut tx, workspace_slug, agent_slug).await?;
|
||||
|
||||
let agent_version = from_db_version(row.try_get("version")?, "agent_version")?;
|
||||
let agent_id = AgentId::new(row.try_get::<String, _>("agent_id")?);
|
||||
// Точные Resource bindings того же agent_version читаются в этой же
|
||||
// repeatable-read транзакции: resources/version/revision всегда согласованы.
|
||||
let resources = read_agent_resource_bindings(&mut tx, &agent_id, agent_version).await?;
|
||||
// Story 3.14: точные Prompt bindings того же snapshot читаются здесь же, поэтому
|
||||
// prompts/list и prompts/get видят только версии, закреплённые в опубликованной версии.
|
||||
let prompts = read_agent_prompt_bindings(&mut tx, &agent_id, agent_version).await?;
|
||||
let catalog_revision: i64 = row.try_get("catalog_revision")?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -47,9 +57,42 @@ impl PostgresRegistry {
|
||||
row.try_get("tool_selection_policy_json")?,
|
||||
)?,
|
||||
tools,
|
||||
resources,
|
||||
prompts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Workspace of the published Agent addressed by slug, for scoped Resource reads.
|
||||
///
|
||||
/// The workspace identity of a slug is immutable, so reading it separately from the catalog is
|
||||
/// not a second, mutable snapshot; a missing/unpublished Agent yields the same safe error as the
|
||||
/// catalog read.
|
||||
pub async fn published_agent_workspace_id(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
) -> Result<WorkspaceId, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select w.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?
|
||||
.ok_or_else(|| RegistryError::PublishedAgentNotFound {
|
||||
workspace_slug: workspace_slug.to_owned(),
|
||||
agent_slug: agent_slug.to_owned(),
|
||||
})?;
|
||||
|
||||
Ok(WorkspaceId::new(row.try_get::<String, _>("id")?))
|
||||
}
|
||||
|
||||
pub async fn get_published_agent_tools_by_slug(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Typed exact Prompt bindings Agent (Story 3.13, V22).
|
||||
//!
|
||||
//! `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
//! Published Prompt Version (`prompt_publications`) для точной версии Agent
|
||||
//! (`agent_versions`). Composite FK на обоих концах фиксирует workspace, поэтому
|
||||
//! ни чужой Agent, ни чужая/неопубликованная Prompt Version не могут стать частью
|
||||
//! binding, а floating `latest` невозможен.
|
||||
//!
|
||||
//! Archive — lifecycle-состояние, а не удаление immutable снимка: строка
|
||||
//! публикации остаётся, поэтому новый binding на archived Prompt обязан
|
||||
//! отклоняться проверкой состояния в той же транзакции, что и запись.
|
||||
|
||||
use super::*;
|
||||
use crank_core::ids::PromptId;
|
||||
use sqlx::{PgConnection, Row};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Точные Prompt bindings версии Agent (публичный read path).
|
||||
pub async fn list_agent_prompt_bindings(
|
||||
&self,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let mut connection = self.pool.acquire().await?;
|
||||
read_agent_prompt_bindings(&mut connection, agent_id, version).await
|
||||
}
|
||||
|
||||
/// Возвращает bindings, для которых в **этом** workspace нет точной строки
|
||||
/// `prompt_publications`. Пустой результат — все версии опубликованы.
|
||||
pub async fn unresolved_published_prompt_versions(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let mut unresolved = Vec::new();
|
||||
for binding in bindings {
|
||||
let version = i32::try_from(binding.prompt_version).map_err(|_| {
|
||||
RegistryError::InvalidNumericValue {
|
||||
field: "prompt_version",
|
||||
value: i64::from(binding.prompt_version),
|
||||
}
|
||||
})?;
|
||||
let exists = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = $1 and prompt_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(binding.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if !exists {
|
||||
unresolved.push(binding.clone());
|
||||
}
|
||||
}
|
||||
Ok(unresolved)
|
||||
}
|
||||
}
|
||||
|
||||
/// Полная замена Prompt bindings конкретной версии Agent внутри открытой
|
||||
/// транзакции save/publish/fork. FK-нарушение откатывает всю транзакцию целиком.
|
||||
pub(super) async fn replace_agent_prompt_bindings_rows(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<(), RegistryError> {
|
||||
if let Some(archived) = first_archived_prompt(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::PromptArchived {
|
||||
prompt_id: archived,
|
||||
});
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"delete from agent_prompt_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
for binding in bindings {
|
||||
sqlx::query(
|
||||
"insert into agent_prompt_bindings (
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
prompt_id,
|
||||
prompt_version
|
||||
) values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.bind(binding.prompt_id.as_str())
|
||||
.bind(to_db_version(binding.prompt_version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Archive блокирует только *новые* binding: immutable publication уже созданной
|
||||
/// версии не удаляется. Кандидаты блокируются в детерминированном порядке, чтобы
|
||||
/// concurrent archive либо успел раньше (отказ), либо ждал commit транзакции.
|
||||
async fn first_archived_prompt(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let prompt_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.prompt_id.as_str().to_owned())
|
||||
.collect();
|
||||
if prompt_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let rows = sqlx::query(
|
||||
"select prompt_id, status
|
||||
from prompts
|
||||
where workspace_id = $1
|
||||
and prompt_id = any($2::text[])
|
||||
order by prompt_id asc
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&prompt_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
for row in rows {
|
||||
if row.try_get::<String, _>("status")? == "archived" {
|
||||
return Ok(Some(row.try_get("prompt_id")?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Fail-closed проверка перед публикацией Agent: ни один binding не должен
|
||||
/// указывать на archived Prompt. Отказ не меняет ни snapshot, ни catalog_revision.
|
||||
pub(super) async fn ensure_agent_prompt_bindings_not_archived(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<(), RegistryError> {
|
||||
let bindings = read_agent_prompt_bindings(tx, agent_id, version).await?;
|
||||
if let Some(archived) = first_archived_prompt(tx, workspace_id, &bindings).await? {
|
||||
return Err(RegistryError::PromptArchived {
|
||||
prompt_id: archived,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn read_agent_prompt_bindings(
|
||||
connection: &mut PgConnection,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select prompt_id, prompt_version
|
||||
from agent_prompt_bindings
|
||||
where agent_id = $1 and agent_version = $2
|
||||
order by prompt_id asc",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.fetch_all(&mut *connection)
|
||||
.await?;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(AgentPromptBinding {
|
||||
prompt_id: PromptId::new(row.try_get::<String, _>("prompt_id")?),
|
||||
prompt_version: from_db_version(row.try_get("prompt_version")?, "prompt_version")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Typed exact Resource bindings Agent (Story 3.7 AC04, V18).
|
||||
//!
|
||||
//! `agent_resource_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
//! Published Resource Version (`resource_publications`) для точной версии Agent
|
||||
//! (`agent_versions`). Composite FK на обоих концах фиксирует workspace:
|
||||
//! `(workspace_id, agent_id) -> agents(workspace_id, id)` и
|
||||
//! `(workspace_id, resource_id, resource_version) -> resource_publications`,
|
||||
//! поэтому ни чужой Agent, ни чужая/неопубликованная Resource Version не могут
|
||||
//! стать частью binding.
|
||||
//!
|
||||
//! Здесь же проверка «точная опубликованная версия существует в этом workspace»
|
||||
//! для API-слоя: отсутствующая, чужая и неопубликованная версии дают один и тот
|
||||
//! же sanitized 404 без утечки существования.
|
||||
|
||||
use super::*;
|
||||
use crank_core::ids::ResourceId;
|
||||
use sqlx::{PgConnection, Row};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Точные Resource bindings версии Agent (публичный read path).
|
||||
pub async fn list_agent_resource_bindings(
|
||||
&self,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let mut connection = self.pool.acquire().await?;
|
||||
read_agent_resource_bindings(&mut connection, agent_id, version).await
|
||||
}
|
||||
|
||||
/// Возвращает bindings, для которых в **этом** workspace нет точной строки
|
||||
/// `resource_publications`. Пустой результат — все версии опубликованы.
|
||||
/// Различие «чужая/неопубликованная/отсутствующая» наружу не раскрывается.
|
||||
pub async fn unresolved_published_resource_versions(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let mut unresolved = Vec::new();
|
||||
for binding in bindings {
|
||||
let version = i32::try_from(binding.resource_version).map_err(|_| {
|
||||
RegistryError::InvalidNumericValue {
|
||||
field: "resource_version",
|
||||
value: i64::from(binding.resource_version),
|
||||
}
|
||||
})?;
|
||||
let exists = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if !exists {
|
||||
unresolved.push(binding.clone());
|
||||
}
|
||||
}
|
||||
Ok(unresolved)
|
||||
}
|
||||
}
|
||||
|
||||
/// Полная замена Resource bindings конкретной версии Agent внутри уже открытой
|
||||
/// транзакции save/publish/fork. FK-нарушение откатывает всю транзакцию целиком.
|
||||
pub(super) async fn replace_agent_resource_bindings_rows(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<(), RegistryError> {
|
||||
// AC04: archive forbids *new* bindings. The immutable `resource_publications` row is untouched by
|
||||
// archive, so the composite FK alone would still accept an archived Resource here; the lifecycle
|
||||
// state is checked in the same transaction that writes the bindings (fail-closed, no partial rows).
|
||||
if let Some(archived) = first_archived_resource(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::ResourceArchived {
|
||||
resource_id: archived,
|
||||
});
|
||||
}
|
||||
// Story 3.8: отзыв блокирует и новые привязки. Tombstones читаются после тех же
|
||||
// упорядоченных `resources` locks, поэтому revoke не может проскочить между
|
||||
// проверкой и INSERT.
|
||||
if let Some(revoked) = first_revoked_resource(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::ResourceRevoked {
|
||||
resource_id: revoked,
|
||||
});
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"delete from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
for binding in bindings {
|
||||
sqlx::query(
|
||||
"insert into agent_resource_bindings (
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
resource_id,
|
||||
resource_version
|
||||
) values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(to_db_version(binding.resource_version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first `archived` Resource among the requested bindings, if any (workspace-scoped).
|
||||
///
|
||||
/// AC04 («archive forbids *new* bindings») must not be a check-then-write race: an unlocked status
|
||||
/// read can miss an archive that commits between this SELECT and the INSERT below, which would
|
||||
/// leave a binding created after the Resource was archived. Every candidate `resources` row is
|
||||
/// therefore locked in deterministic (ascending id) order in this transaction *before* its status is
|
||||
/// inspected, and those locks are held until the binding writes commit. A concurrent archive of any
|
||||
/// candidate then either commits first (its `archived` state is what we read: refused) or waits for
|
||||
/// this transaction to end (the binding legally precedes the archive).
|
||||
async fn first_archived_resource(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// `for update` after the deterministic `order by`, and *without* the status predicate: a row
|
||||
// filtered out by `status = 'archived'` would never be locked and could be archived mid-write.
|
||||
let rows = sqlx::query(
|
||||
"select r.resource_id, r.status
|
||||
from resources r
|
||||
where r.workspace_id = $1
|
||||
and r.resource_id = any($2::text[])
|
||||
order by r.resource_id asc
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
for row in rows {
|
||||
if row.try_get::<String, _>("status")? == "archived" {
|
||||
return Ok(Some(row.try_get::<String, _>("resource_id")?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The first revoked Resource among the requested bindings, if any (workspace-scoped).
|
||||
///
|
||||
/// Callers must already hold the `resources` rows of these bindings (the same
|
||||
/// deterministic ascending order as `first_archived_resource`), so a revoke cannot
|
||||
/// commit between this fresh tombstone query and the following INSERT.
|
||||
async fn first_revoked_resource(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let row = sqlx::query(
|
||||
"select resource_id
|
||||
from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = any($2::text[])
|
||||
order by resource_id asc
|
||||
limit 1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|row| row.try_get::<String, _>("resource_id"))
|
||||
.transpose()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Live security gate for `Agent publish`: re-read the exact bindings of the version
|
||||
/// being published inside the Agent transaction, lock their Resources in `resource_id
|
||||
/// ASC` order and reject revoked ones before any publication mutation.
|
||||
pub(super) async fn ensure_agent_bindings_not_revoked(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<(), RegistryError> {
|
||||
let bindings = read_agent_resource_bindings(&mut *tx, agent_id, version).await?;
|
||||
let mut resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
resource_ids.sort();
|
||||
resource_ids.dedup();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
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.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
if locked.len() != resource_ids.len() {
|
||||
return Err(RegistryError::Storage(sqlx::Error::RowNotFound));
|
||||
}
|
||||
if let Some(resource_id) = first_revoked_resource(tx, workspace_id, &bindings).await? {
|
||||
return Err(RegistryError::ResourceRevoked { resource_id });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Чтение exact bindings внутри транзакции: каталог обязан брать resources из
|
||||
/// той же read-транзакции, что `agent_version`/`catalog_revision`/`tools`.
|
||||
pub(super) async fn read_agent_resource_bindings(
|
||||
executor: &mut PgConnection,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select resource_id, resource_version
|
||||
from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = $2
|
||||
order by resource_id asc, resource_version asc",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.fetch_all(&mut *executor)
|
||||
.await?;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(AgentResourceBinding {
|
||||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id")?),
|
||||
resource_version: from_db_version(
|
||||
row.try_get::<i32, _>("resource_version")?,
|
||||
"resource_version",
|
||||
)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -583,7 +583,7 @@ const SOURCE_SELECT: &str = "select
|
||||
join artifact_blobs b on b.digest = s.blob_digest
|
||||
where s.workspace_id = $1 and s.source_id = $2";
|
||||
|
||||
async fn require_workspace(
|
||||
pub(super) async fn require_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -601,7 +601,7 @@ async fn require_workspace(
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_blob(
|
||||
pub(super) async fn ensure_blob(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
request: &CreateArtifactSourceRequest<'_>,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -736,7 +736,7 @@ async fn global_detached_reference_in_grace(
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn get_source_in_transaction(
|
||||
pub(super) async fn get_source_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
source_id: &ArtifactSourceId,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
mod agent;
|
||||
mod agent_catalog;
|
||||
mod agent_prompt_bindings;
|
||||
mod agent_resource_bindings;
|
||||
mod api_key;
|
||||
mod approval;
|
||||
mod artifact_source;
|
||||
@@ -15,6 +17,8 @@ mod operation_artifact;
|
||||
mod operation_published;
|
||||
mod pool_config;
|
||||
mod product_event;
|
||||
mod prompt;
|
||||
mod resource;
|
||||
mod secret;
|
||||
mod upstream;
|
||||
mod workspace;
|
||||
@@ -33,26 +37,28 @@ use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgRow, types::Json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
pub use pool_config::{PostgresPoolConfig, PostgresPoolConfigError};
|
||||
pub use resource::{AuthorizedResourceRead, BoundResourceAdmission};
|
||||
|
||||
use crate::{
|
||||
error::RegistryError,
|
||||
model::{
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentSummary, AgentVersionRecord,
|
||||
AppendProductEventOutcome, AppendProductEventRequest, AppliedImportOperation,
|
||||
ApplyImportJobRequest, ApprovalRequestRecord, AuthUserRecord,
|
||||
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
|
||||
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
|
||||
CreateImportJobRequest, CreateInvitationRequest, CreateInvocationLogRequest,
|
||||
CreatePlatformApiKeyRequest, CreateSecretRequest, CreateVersionRequest,
|
||||
CreateWorkspaceRequest, CreateYamlImportJobRequest, DecideApprovalRequest,
|
||||
DescriptorMetadata, ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest,
|
||||
ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobStatus, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus,
|
||||
MembershipRecord, OnboardingEventSnapshot, OnboardingImportChoice, OnboardingImportContext,
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentPromptBinding,
|
||||
AgentResourceBinding, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppendProductEventRequest, AppliedImportOperation, ApplyImportJobRequest,
|
||||
ApprovalRequestRecord, AuthUserRecord, ConsumeAdminBootstrapContractRequest,
|
||||
CreateAdminBootstrapContractRequest, CreateAgentDraftVersionRequest, CreateAgentRequest,
|
||||
CreateApprovalRequest, CreateImportJobRequest, CreateInvitationRequest,
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DescriptorMetadata, ExpireApprovalRequest, FinishApprovalRequest,
|
||||
FinishImportJobRequest, ImportConflictMode, ImportJob, ImportJobApplyResult,
|
||||
ImportJobCleanupReport, ImportJobId, ImportJobStatus, InvitationRecord,
|
||||
InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome,
|
||||
InvocationLogRecord, InvocationRetentionOutcome, InvocationRetentionPolicy,
|
||||
InvocationRetentionStatus, ListApprovalRequestsQuery, ListInvocationLogsQuery,
|
||||
ListProductEventsQuery, MasterKeyIdentityCandidate, MasterKeyIdentityRecord,
|
||||
MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
||||
OnboardingEventSnapshot, OnboardingImportChoice, OnboardingImportContext,
|
||||
OnboardingImportDrift, OnboardingMilestoneResult, OnboardingPresentationMilestone,
|
||||
OnboardingSnapshot, OperationAgentRef, OperationSampleMetadata, OperationStateExpectation,
|
||||
OperationSummary, OperationUsageSummary, OperationVersionRecord, PlatformApiKeyRecord,
|
||||
@@ -615,6 +621,7 @@ fn build_operation_agent_ref(
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_agent_version_record(
|
||||
summary: &AgentSummary,
|
||||
version: i32,
|
||||
@@ -623,6 +630,8 @@ fn build_agent_version_record(
|
||||
tool_selection_policy_json: Value,
|
||||
created_at: OffsetDateTime,
|
||||
bindings: Vec<AgentOperationBinding>,
|
||||
resource_bindings: Vec<AgentResourceBinding>,
|
||||
prompt_bindings: Vec<AgentPromptBinding>,
|
||||
) -> Result<AgentVersionRecord, RegistryError> {
|
||||
let version = from_db_version(version, "version")?;
|
||||
let status = deserialize_enum_text(&status, "status")?;
|
||||
@@ -634,6 +643,8 @@ fn build_agent_version_record(
|
||||
status,
|
||||
created_at,
|
||||
bindings,
|
||||
resource_bindings,
|
||||
prompt_bindings,
|
||||
snapshot: AgentVersion {
|
||||
agent_id: summary.id.clone(),
|
||||
version,
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
use crank_core::{
|
||||
WorkspaceId,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{
|
||||
ArgumentKind, PromptDefinition, PromptDraft, PromptRole, PromptSensitivity, PromptStatus,
|
||||
},
|
||||
prompt_composition::{
|
||||
PromptDependencyPin, PromptDependencySourceClass, effective_sensitivity, unused_dependency,
|
||||
},
|
||||
resource::{ResourceError, ResourceKind},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, types::Json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{PostgresRegistry, artifact_source::require_workspace};
|
||||
use crate::{
|
||||
RegistryError,
|
||||
model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PromptDraftRecord,
|
||||
PromptPublicationRecord, PublishPromptRequest, ResourcePublicationRecord,
|
||||
UpdatePromptDraftRequest,
|
||||
},
|
||||
};
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn create_prompt_draft(
|
||||
&self,
|
||||
request: CreatePromptDraftRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
&request.definition,
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
require_workspace(&mut tx, &request.workspace_id).await?;
|
||||
sqlx::query("insert into prompts (workspace_id,prompt_id,name,description,status,sensitivity,current_draft_version,created_at,updated_at) values ($1,$2,$3,$4,'draft',$5,1,$6,$6)")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.bind(request.definition.name()).bind(request.definition.description())
|
||||
.bind(sensitivity_name(request.sensitivity)).bind(request.created_at)
|
||||
.execute(&mut *tx).await?;
|
||||
insert_version(
|
||||
&mut tx,
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
1,
|
||||
&request.definition,
|
||||
&dependencies,
|
||||
request.created_at,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_prompt_draft(
|
||||
&self,
|
||||
request: UpdatePromptDraftRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
&request.definition,
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query("select current_draft_version,status,updated_at from prompts where workspace_id=$1 and prompt_id=$2 for update")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx).await?.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: request.prompt_id.to_string() })?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let status: String = row.try_get("status")?;
|
||||
// Правка опубликованного Prompt открывает новый Draft; archived остаётся
|
||||
// терминальным lifecycle-состоянием.
|
||||
if status == "archived" {
|
||||
return Err(RegistryError::PromptNotDraft {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let next = version
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| RegistryError::PromptVersionOverflow {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
})?;
|
||||
sqlx::query("update prompts set name=$3,description=$4,sensitivity=$5,status='draft',current_draft_version=$6,updated_at=$7 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.bind(request.definition.name()).bind(request.definition.description()).bind(sensitivity_name(request.sensitivity)).bind(next).bind(request.updated_at)
|
||||
.execute(&mut *tx).await?;
|
||||
insert_version(
|
||||
&mut tx,
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
next,
|
||||
&request.definition,
|
||||
&dependencies,
|
||||
request.updated_at,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Публикует текущий Draft как immutable Published Prompt Version.
|
||||
///
|
||||
/// Строка `prompts` блокируется на время транзакции, поэтому два конкурентных
|
||||
/// publish с одинаковым `expected_updated_at` сериализуются: один создаёт
|
||||
/// публикацию, второй видит stale revision и получает 409.
|
||||
pub async fn publish_prompt_draft(
|
||||
&self,
|
||||
request: PublishPromptRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
// Publication re-resolves every pinned dependency in declaration order: a version that was
|
||||
// resolvable when the Draft was saved but is revoked/archived now must block the
|
||||
// publication with the exact position (contract §2), never ship an unusable pin.
|
||||
//
|
||||
// Resolution reads through the pool, so it runs before the write transaction; the version
|
||||
// it resolved is compared with the locked row below, so a concurrent Draft edit can never
|
||||
// publish the pins of another version.
|
||||
let draft = self
|
||||
.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await?;
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
draft.prompt.definition(),
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query("select current_draft_version,status,updated_at,name,description,sensitivity from prompts where workspace_id=$1 and prompt_id=$2 for update")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx).await?.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: request.prompt_id.to_string() })?;
|
||||
let status: String = row.try_get("status")?;
|
||||
if status == "archived" {
|
||||
return Err(RegistryError::PromptNotDraft {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
if i32::try_from(draft.prompt.version()).ok() != Some(version) {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let already_published = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (select 1 from prompt_publications
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if already_published {
|
||||
return Err(RegistryError::PromptPublicationConflict {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let local =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
// AC3: the publication stores the strictest policy of the prompt and its pins.
|
||||
let effective = effective_sensitivity(local, &dependencies);
|
||||
sqlx::query("insert into prompt_publications (workspace_id,prompt_id,version,name,description,sensitivity,published_at) values ($1,$2,$3,$4,$5,$6,$7)")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.bind(row.try_get::<String, _>("name")?)
|
||||
.bind(row.try_get::<String, _>("description")?)
|
||||
.bind(sensitivity_name(effective))
|
||||
.bind(request.published_at)
|
||||
.execute(&mut *tx).await?;
|
||||
sqlx::query("update prompts set status='published',latest_published_version=$3,updated_at=$4 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.bind(request.published_at)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Архив — lifecycle-состояние, а не security revoke: уже immutable
|
||||
/// публикации и definition остаются доступными по точной версии.
|
||||
pub async fn archive_prompt_draft(
|
||||
&self,
|
||||
request: ArchivePromptRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query(
|
||||
"select updated_at from prompts where workspace_id=$1 and prompt_id=$2 for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::PromptNotFound {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
})?;
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
sqlx::query("update prompts set status='archived',updated_at=$3 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(request.archived_at)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_prompt_drafts(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Vec<PromptDraftRecord>, RegistryError> {
|
||||
let ids = sqlx::query_scalar::<_, String>(
|
||||
"select prompt_id from prompts where workspace_id=$1 order by created_at,prompt_id",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut prompts = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
prompts.push(
|
||||
self.get_prompt_draft(workspace_id, &PromptId::new(id))
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
Ok(prompts)
|
||||
}
|
||||
|
||||
pub async fn get_prompt_draft(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let row = sqlx::query("select name,description,status,sensitivity,current_draft_version,latest_published_version,created_at,updated_at from prompts where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).fetch_optional(&self.pool).await?
|
||||
.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: prompt_id.to_string() })?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let latest_published_version = row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| db_version(value, prompt_id))
|
||||
.transpose()?;
|
||||
let (definition, dependencies) = read_definition(
|
||||
&self.pool,
|
||||
workspace_id,
|
||||
prompt_id,
|
||||
version,
|
||||
&row.try_get::<String, _>("name")?,
|
||||
&row.try_get::<String, _>("description")?,
|
||||
)
|
||||
.await?;
|
||||
let status = parse_status(&row.try_get::<String, _>("status")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
let version = db_version(version, prompt_id)?;
|
||||
let prompt =
|
||||
PromptDraft::from_parts(prompt_id.clone(), version, status, sensitivity, definition)
|
||||
.map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
Ok(PromptDraftRecord {
|
||||
prompt,
|
||||
latest_published_version,
|
||||
dependencies,
|
||||
created_at: row.try_get("created_at")?,
|
||||
updated_at: row.try_get("updated_at")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exact read immutable Published Prompt Version по точному номеру.
|
||||
pub async fn get_published_prompt_version(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: u32,
|
||||
) -> Result<PromptPublicationRecord, RegistryError> {
|
||||
let version =
|
||||
i32::try_from(version).map_err(|_| RegistryError::PromptPublicationNotFound {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
let row = sqlx::query("select name,description,sensitivity,published_at from prompt_publications where workspace_id=$1 and prompt_id=$2 and version=$3")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version)
|
||||
.fetch_optional(&self.pool).await?
|
||||
.ok_or_else(|| RegistryError::PromptPublicationNotFound { prompt_id: prompt_id.to_string() })?;
|
||||
let (definition, dependencies) = read_definition(
|
||||
&self.pool,
|
||||
workspace_id,
|
||||
prompt_id,
|
||||
version,
|
||||
&row.try_get::<String, _>("name")?,
|
||||
&row.try_get::<String, _>("description")?,
|
||||
)
|
||||
.await?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
Ok(PromptPublicationRecord {
|
||||
prompt_id: prompt_id.clone(),
|
||||
version: db_version(version, prompt_id)?,
|
||||
name: row.try_get("name")?,
|
||||
description: row.try_get("description")?,
|
||||
sensitivity,
|
||||
definition,
|
||||
dependencies,
|
||||
published_at: row.try_get("published_at")?,
|
||||
})
|
||||
}
|
||||
/// Разрешает `dependencies` определения в точные пины в порядке объявления (contract §2).
|
||||
///
|
||||
/// Тот же exact-version read path, что у 3.8/3.14: статическая версия читается из
|
||||
/// `resource_publications`, template-версия — из definition-only публикации 3.10. Отзыв,
|
||||
/// чужая или отсутствующая версия неотличимы (один код и source path), а `binary` не имеет
|
||||
/// текстового представления. Неиспользуемая зависимость отклоняется до любого чтения.
|
||||
async fn resolve_prompt_dependencies(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
definition: &PromptDefinition,
|
||||
) -> Result<Vec<PromptDependencyPin>, RegistryError> {
|
||||
if let Some(position) = unused_dependency(definition) {
|
||||
let dependency = &definition.dependencies()[position];
|
||||
return Err(RegistryError::PromptDependencyUnused {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: dependency.resource_id.clone(),
|
||||
version: dependency.version,
|
||||
});
|
||||
}
|
||||
let mut pins = Vec::with_capacity(definition.dependencies().len());
|
||||
for (position, dependency) in definition.dependencies().iter().enumerate() {
|
||||
let resource_id = ResourceId::new(dependency.resource_id.clone());
|
||||
let unresolved = || RegistryError::PromptDependencyUnresolved {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: dependency.resource_id.clone(),
|
||||
version: dependency.version,
|
||||
};
|
||||
let revoked: bool = sqlx::query_scalar(
|
||||
"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?;
|
||||
if revoked {
|
||||
return Err(unresolved());
|
||||
}
|
||||
let pin = match self
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
dependency.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => pin_from(
|
||||
prompt_id,
|
||||
position,
|
||||
&resolved.publication,
|
||||
PromptDependencySourceClass::Static,
|
||||
),
|
||||
Err(ResourceError::NotFound) => {
|
||||
match self
|
||||
.resolve_resource_template_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
dependency.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((publication, _source)) => pin_from(
|
||||
prompt_id,
|
||||
position,
|
||||
&publication,
|
||||
PromptDependencySourceClass::Dynamic,
|
||||
),
|
||||
Err(ResourceError::NotFound) => return Err(unresolved()),
|
||||
Err(_) => {
|
||||
return Err(RegistryError::PromptDependencyUnavailable {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(RegistryError::PromptDependencyUnavailable {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
}?;
|
||||
pins.push(pin);
|
||||
}
|
||||
Ok(pins)
|
||||
}
|
||||
|
||||
/// Exact reads of the immutable Published Prompt Versions bound to one published Agent
|
||||
/// snapshot (Story 3.14).
|
||||
///
|
||||
/// The bindings are the exact `agent_prompt_bindings` rows of that Agent version, so the
|
||||
/// result is the same immutable array on every call: a later Draft edit or archive of the
|
||||
/// Prompt changes neither the resolvable version nor its definition. A binding without its
|
||||
/// exact publication row is a fail-closed error — `prompts/list`/`prompts/get` must never
|
||||
/// serve a silently shortened snapshot.
|
||||
pub async fn resolve_bound_prompt_publications(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Vec<PromptPublicationRecord>, RegistryError> {
|
||||
let mut publications = Vec::with_capacity(bindings.len());
|
||||
for binding in bindings {
|
||||
publications.push(
|
||||
self.get_published_prompt_version(
|
||||
workspace_id,
|
||||
&binding.prompt_id,
|
||||
binding.prompt_version,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
Ok(publications)
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_definition(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
name: &str,
|
||||
description: &str,
|
||||
) -> Result<(PromptDefinition, Vec<PromptDependencyPin>), RegistryError> {
|
||||
let dependencies = read_dependencies(pool, workspace_id, prompt_id, version).await?;
|
||||
let arguments = sqlx::query("select argument_name,argument_type,required,default_value,enumeration from prompt_arguments where workspace_id=$1 and prompt_id=$2 and version=$3 order by position")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version).fetch_all(pool).await?;
|
||||
let mut args = Vec::with_capacity(arguments.len());
|
||||
for argument in arguments {
|
||||
let default: Option<Json<Value>> = argument.try_get("default_value")?;
|
||||
let enumeration: Option<Json<Value>> = argument.try_get("enumeration")?;
|
||||
let mut item = serde_json::Map::new();
|
||||
item.insert(
|
||||
"name".into(),
|
||||
json!(argument.try_get::<String, _>("argument_name")?),
|
||||
);
|
||||
item.insert(
|
||||
"required".into(),
|
||||
json!(argument.try_get::<bool, _>("required")?),
|
||||
);
|
||||
let mut schema = serde_json::Map::new();
|
||||
schema.insert(
|
||||
"type".into(),
|
||||
json!(argument.try_get::<String, _>("argument_type")?),
|
||||
);
|
||||
if let Some(Json(value)) = enumeration {
|
||||
schema.insert("enum".into(), value);
|
||||
}
|
||||
item.insert("schema".into(), Value::Object(schema));
|
||||
if let Some(Json(value)) = default {
|
||||
item.insert("default".into(), value);
|
||||
}
|
||||
args.push(Value::Object(item));
|
||||
}
|
||||
let messages = sqlx::query("select position,role,content from prompt_messages where workspace_id=$1 and prompt_id=$2 and version=$3 order by position")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version).fetch_all(pool).await?;
|
||||
let refs = read_resource_refs(pool, workspace_id, prompt_id, version).await?;
|
||||
let mut msgs = Vec::with_capacity(messages.len());
|
||||
for message in messages {
|
||||
let position = message.try_get::<i32, _>("position")?;
|
||||
let mut item = json!({
|
||||
"role": message.try_get::<String, _>("role")?,
|
||||
"content": message.try_get::<String, _>("content")?,
|
||||
});
|
||||
if let Some(indices) = refs.get(&position) {
|
||||
item["resource_refs"] = json!(indices);
|
||||
}
|
||||
msgs.push(item);
|
||||
}
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": description,
|
||||
"arguments": args,
|
||||
"messages": msgs,
|
||||
"dependencies": dependencies
|
||||
.iter()
|
||||
.map(|pin| json!({"resource_id": pin.resource_id, "version": pin.version}))
|
||||
.collect::<Vec<_>>(),
|
||||
}))
|
||||
.map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
Ok((definition, dependencies))
|
||||
}
|
||||
|
||||
/// Упорядоченные точки вставки по номеру сообщения: `message.position -> [dependency index]`.
|
||||
async fn read_resource_refs(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
) -> Result<std::collections::BTreeMap<i32, Vec<usize>>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select message_position,dependency_position
|
||||
from prompt_message_resource_refs
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3
|
||||
order by message_position,ref_position",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
let mut refs = std::collections::BTreeMap::<i32, Vec<usize>>::new();
|
||||
for row in rows {
|
||||
let message = row.try_get::<i32, _>("message_position")?;
|
||||
let dependency = row.try_get::<i32, _>("dependency_position")?;
|
||||
let dependency = usize::try_from(dependency).map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
refs.entry(message).or_default().push(dependency);
|
||||
}
|
||||
Ok(refs)
|
||||
}
|
||||
|
||||
/// Version-keyed pins in declaration order; a corrupt row is a fail-closed error.
|
||||
async fn read_dependencies(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
) -> Result<Vec<PromptDependencyPin>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select dependency_position,resource_id,resource_version,digest,kind,mime_type,source_class,sensitivity
|
||||
from prompt_dependencies
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3
|
||||
order by dependency_position",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
let corrupt = || RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
};
|
||||
let position = usize::try_from(row.try_get::<i32, _>("dependency_position")?)
|
||||
.map_err(|_| corrupt())?;
|
||||
let resource_version =
|
||||
u32::try_from(row.try_get::<i32, _>("resource_version")?).map_err(|_| corrupt())?;
|
||||
let kind =
|
||||
ResourceKind::parse(&row.try_get::<String, _>("kind")?).ok_or_else(corrupt)?;
|
||||
let source_class =
|
||||
PromptDependencySourceClass::parse(&row.try_get::<String, _>("source_class")?)
|
||||
.ok_or_else(corrupt)?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(corrupt)?;
|
||||
Ok(PromptDependencyPin {
|
||||
position,
|
||||
resource_id: row.try_get("resource_id")?,
|
||||
version: resource_version,
|
||||
digest: row.try_get("digest")?,
|
||||
kind,
|
||||
mime_type: row.try_get("mime_type")?,
|
||||
source_class,
|
||||
sensitivity,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn insert_version(
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
workspace: &WorkspaceId,
|
||||
prompt: &PromptId,
|
||||
version: i32,
|
||||
definition: &PromptDefinition,
|
||||
dependencies: &[PromptDependencyPin],
|
||||
at: OffsetDateTime,
|
||||
) -> Result<(), RegistryError> {
|
||||
sqlx::query("insert into prompt_versions (workspace_id,prompt_id,version,created_at) values ($1,$2,$3,$4)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(at).execute(&mut **tx).await?;
|
||||
for (position, argument) in definition.arguments().iter().enumerate() {
|
||||
let kind = match argument.kind() {
|
||||
ArgumentKind::String => "string",
|
||||
ArgumentKind::Number => "number",
|
||||
ArgumentKind::Integer => "integer",
|
||||
ArgumentKind::Boolean => "boolean",
|
||||
};
|
||||
let default = argument.default().cloned().map(Json);
|
||||
let enumeration = if argument.enumeration().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(Json(Value::Array(argument.enumeration().to_vec())))
|
||||
};
|
||||
sqlx::query("insert into prompt_arguments (workspace_id,prompt_id,version,argument_name,argument_type,required,default_value,enumeration,position) values ($1,$2,$3,$4,$5,$6,$7,$8,$9)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(argument.name()).bind(kind).bind(argument.required()).bind(default).bind(enumeration).bind(i32::try_from(position).unwrap_or(i32::MAX)).execute(&mut **tx).await?;
|
||||
}
|
||||
for (position, message) in definition.messages().iter().enumerate() {
|
||||
let role = match message.role {
|
||||
PromptRole::System => "system",
|
||||
PromptRole::User => "user",
|
||||
PromptRole::Assistant => "assistant",
|
||||
};
|
||||
let message_position = i32::try_from(position).unwrap_or(i32::MAX);
|
||||
sqlx::query("insert into prompt_messages (workspace_id,prompt_id,version,position,role,content) values ($1,$2,$3,$4,$5,$6)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(message_position).bind(role).bind(&message.content).execute(&mut **tx).await?;
|
||||
for (ref_position, dependency_position) in message.resource_refs.iter().enumerate() {
|
||||
sqlx::query("insert into prompt_message_resource_refs (workspace_id,prompt_id,version,message_position,ref_position,dependency_position) values ($1,$2,$3,$4,$5,$6)")
|
||||
.bind(workspace.as_str())
|
||||
.bind(prompt.as_str())
|
||||
.bind(version)
|
||||
.bind(message_position)
|
||||
.bind(i32::try_from(ref_position).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(*dependency_position).unwrap_or(i32::MAX))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
for pin in dependencies {
|
||||
sqlx::query("insert into prompt_dependencies (workspace_id,prompt_id,version,dependency_position,resource_id,resource_version,digest,kind,mime_type,source_class,sensitivity) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)")
|
||||
.bind(workspace.as_str())
|
||||
.bind(prompt.as_str())
|
||||
.bind(version)
|
||||
.bind(i32::try_from(pin.position).unwrap_or(i32::MAX))
|
||||
.bind(&pin.resource_id)
|
||||
.bind(i32::try_from(pin.version).unwrap_or(i32::MAX))
|
||||
.bind(&pin.digest)
|
||||
.bind(pin.kind.as_str())
|
||||
.bind(&pin.mime_type)
|
||||
.bind(pin.source_class.as_str())
|
||||
.bind(sensitivity_name(pin.sensitivity))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn db_version(value: i32, prompt_id: &PromptId) -> Result<u32, RegistryError> {
|
||||
u32::try_from(value).map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn sensitivity_name(s: PromptSensitivity) -> &'static str {
|
||||
match s {
|
||||
PromptSensitivity::Public => "public",
|
||||
PromptSensitivity::Internal => "internal",
|
||||
PromptSensitivity::Secret => "secret",
|
||||
}
|
||||
}
|
||||
fn parse_sensitivity(value: &str) -> Option<PromptSensitivity> {
|
||||
match value {
|
||||
"public" => Some(PromptSensitivity::Public),
|
||||
"internal" => Some(PromptSensitivity::Internal),
|
||||
"secret" => Some(PromptSensitivity::Secret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn parse_status(value: &str) -> Option<PromptStatus> {
|
||||
match value {
|
||||
"draft" => Some(PromptStatus::Draft),
|
||||
"published" => Some(PromptStatus::Published),
|
||||
"archived" => Some(PromptStatus::Archived),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Пин зависимости из точной опубликованной версии Resource; `binary` не имеет текстового
|
||||
/// представления и отклоняется тем же кодом, что и на рендере (contract §4).
|
||||
fn pin_from(
|
||||
prompt_id: &PromptId,
|
||||
position: usize,
|
||||
publication: &ResourcePublicationRecord,
|
||||
source_class: PromptDependencySourceClass,
|
||||
) -> Result<PromptDependencyPin, RegistryError> {
|
||||
let kind = ResourceKind::parse(&publication.kind).ok_or_else(|| {
|
||||
RegistryError::PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
}
|
||||
})?;
|
||||
if kind == ResourceKind::Binary {
|
||||
return Err(RegistryError::PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
});
|
||||
}
|
||||
let sensitivity = parse_sensitivity(&publication.sensitivity).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
Ok(PromptDependencyPin {
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
digest: publication.digest.clone(),
|
||||
kind,
|
||||
mime_type: publication.mime_type.clone(),
|
||||
source_class,
|
||||
sensitivity,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
//! 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,
|
||||
}
|
||||
}
|
||||
@@ -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