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

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:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

+45
View File
@@ -91,6 +91,12 @@ pub enum RegistryError {
},
#[error("operation {operation_id} is archived")]
OperationArchived { operation_id: String },
#[error("resource {resource_id} is archived and cannot receive new Agent bindings")]
ResourceArchived { resource_id: String },
#[error(
"resource {resource_id} is revoked and cannot receive new Agent bindings or publications"
)]
ResourceRevoked { resource_id: String },
#[error("operation {operation_id} has a stale base version: expected {expected}, got {actual}")]
OperationStaleVersion {
operation_id: String,
@@ -202,4 +208,43 @@ pub enum RegistryError {
ArtifactClaimInProgress,
#[error("artifact source metadata is invalid for field {field}")]
InvalidArtifactSource { field: &'static str },
#[error("prompt {prompt_id} was not found in this workspace")]
PromptNotFound { prompt_id: String },
#[error("prompt {prompt_id} is not in Draft state")]
PromptNotDraft { prompt_id: String },
#[error("prompt {prompt_id} changed since it was read")]
PromptStaleRevision { prompt_id: String },
#[error("prompt {prompt_id} version counter overflowed")]
PromptVersionOverflow { prompt_id: String },
#[error("prompt {prompt_id} has invalid stored data")]
PromptCorrupt { prompt_id: String },
#[error("prompt {prompt_id} is archived and cannot receive new bindings")]
PromptArchived { prompt_id: String },
#[error("published prompt version for {prompt_id} was not found in this workspace")]
PromptPublicationNotFound { prompt_id: String },
#[error("prompt {prompt_id} version is already published")]
PromptPublicationConflict { prompt_id: String },
#[error("prompt {prompt_id} dependency at position {position} cannot be resolved")]
PromptDependencyUnresolved {
prompt_id: String,
position: usize,
resource_id: String,
version: u32,
},
#[error("prompt {prompt_id} dependency at position {position} has no text representation")]
PromptDependencyRepresentationUnsupported {
prompt_id: String,
position: usize,
resource_id: String,
version: u32,
},
#[error("prompt {prompt_id} dependency at position {position} is not referenced by a message")]
PromptDependencyUnused {
prompt_id: String,
position: usize,
resource_id: String,
version: u32,
},
#[error("prompt {prompt_id} dependency at position {position} is unavailable")]
PromptDependencyUnavailable { prompt_id: String, position: usize },
}
+23 -20
View File
@@ -1,7 +1,7 @@
mod error;
mod ext;
mod migrations;
mod model;
pub mod model;
mod postgres;
pub use error::RegistryError;
@@ -13,15 +13,15 @@ pub use migrations::{
pub mod records {
pub use crate::model::{
AdminBootstrapContractRecord, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
AppliedImportOperation, ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord,
ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome,
ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe,
ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord,
ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind, DescriptorMetadata, ImportJob,
ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
AdminBootstrapContractRecord, AgentResourceBinding, AgentSummary, AgentVersionRecord,
AppendProductEventOutcome, AppliedImportOperation, ApprovalRequestRecord,
ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind,
DescriptorMetadata, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef,
ImportPlanId, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
@@ -72,15 +72,15 @@ pub mod infrastructure {
}
pub use model::{
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentStateExpectation, AgentSummary,
AgentVersionRecord, AppendProductEventOutcome, AppendProductEventRequest,
AppliedImportOperation, ApplyImportJobRequest, ApplyImportPlanRequest, ApplyImportPlanResult,
ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord,
ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentResourceBinding,
AgentStateExpectation, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
AppendProductEventRequest, AppliedImportOperation, ApplyImportJobRequest,
ApplyImportPlanRequest, ApplyImportPlanResult, ApprovalRequestRecord, ArtifactBlobLifecycle,
ArtifactBlobRecord, ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome,
ArtifactClaimOutcome, ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest,
ArtifactExpiredClaimProbe, ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord, ArtifactSourceSensitivity,
AuthUserRecord, ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
@@ -115,4 +115,7 @@ pub use model::{
WorkspaceMembershipRecord, WorkspaceRecord, WorkspaceUpstream, WorkspaceUpstreamId,
YamlImportJob, YamlImportJobCompletion, YamlImportJobId, YamlImportJobStatus,
};
pub use postgres::{PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry};
pub use postgres::{
AuthorizedResourceRead, BoundResourceAdmission, PostgresPoolConfig, PostgresPoolConfigError,
PostgresRegistry,
};
+15
View File
@@ -1,5 +1,6 @@
mod admin_auth_lifecycle_v8;
mod agent_catalog_lifecycle_v9;
mod agent_resource_bindings_v18;
mod approval_side_effects_v10;
mod artifact_cleanup_indexes_v13;
mod artifact_metadata_v12;
@@ -12,6 +13,13 @@ mod onboarding_import_selection_v15;
mod onboarding_product_events_v11;
mod owned_relations;
mod platform_key_name_reuse_v6;
mod prompt_dependencies_v23;
mod prompt_publications_v22;
mod prompts_v21;
mod resource_drafts_v16;
mod resource_publications_v17;
mod resource_security_revocations_v19;
mod resource_template_sources_v20;
mod schema_guard;
mod schema_guard_legacy_v1;
mod schema_guard_v10;
@@ -20,6 +28,13 @@ mod schema_guard_v12;
mod schema_guard_v13;
mod schema_guard_v14;
mod schema_guard_v15;
mod schema_guard_v16;
mod schema_guard_v17;
mod schema_guard_v18;
mod schema_guard_v19;
mod schema_guard_v20;
mod schema_guard_v22;
mod schema_guard_v23;
mod schema_guard_v7;
mod schema_guard_v8;
mod schema_guard_v9;
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "agent-resource-bindings-v18";
pub(super) const SOURCE: &str = include_str!("agent_resource_bindings_v18.sql");
pub(super) const SOURCE_SHA256: &str =
"cb9b82183e04eb72c1f1a9ec853fcfc618f2b1c2a73edd051245890292beeb8f";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.agent_resource_bindings",
Some(18),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(18),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,84 @@
-- V18: typed exact Resource bindings Agent (Story 3.7 AC04, FR-15/FR-16).
--
-- Отдельная typed-таблица вместо JSON-поля: строка адресует точную
-- Published Resource Version (`resource_publications`) для точной версии Agent
-- (`agent_versions`). `latest`/floating версия невозможна, потому что FK указывает
-- на конкретную строку публикации.
--
-- Workspace-равенство обеспечивается на ОБОИХ концах composite FK:
-- * (workspace_id, agent_id) -> agents(workspace_id, id);
-- * (workspace_id, resource_id, resource_version) -> resource_publications(...).
-- Поэтому ни Agent другого workspace, ни чужая/неопубликованная Resource Version
-- не могут стать частью binding.
--
-- Published Agent Version immutable: V18-local trigger function проверяет и OLD,
-- и NEW ключ строки. Canonical V9 function при UPDATE смотрит только на NEW,
-- поэтому перенос binding из опубликованного snapshot в Draft-версию другого
-- Agent проходил бы через неё без отказа. V9/V17 SQL не изменяются.
-- Immutable guard V18: отказ, если затронута опубликованная версия Agent —
-- либо покидаемая (OLD), либо новая (NEW).
create function crank_reject_published_agent_resource_binding_mutation()
returns trigger
language plpgsql
as $$
declare
bound_status text;
begin
if tg_op in ('UPDATE', 'DELETE') then
select status
into bound_status
from agent_versions
where agent_id = old.agent_id and version = old.agent_version;
if bound_status = 'published' then
raise exception 'published Agent catalog bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select status
into bound_status
from agent_versions
where agent_id = new.agent_id and version = new.agent_version;
if bound_status = 'published' then
raise exception 'published Agent catalog bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create unique index agents_workspace_id_idx on agents(workspace_id, id);
create table agent_resource_bindings (
workspace_id text not null,
agent_id text not null,
agent_version integer not null,
resource_id text not null,
resource_version integer not null,
constraint agent_resource_bindings_agent_version_check check (agent_version >= 1),
constraint agent_resource_bindings_resource_version_check check (resource_version >= 1),
primary key (agent_id, agent_version, resource_id, resource_version),
constraint agent_resource_bindings_agent_workspace_fkey
foreign key (workspace_id, agent_id)
references agents(workspace_id, id) on delete cascade,
constraint agent_resource_bindings_agent_version_fkey
foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade,
constraint agent_resource_bindings_publication_fkey
foreign key (workspace_id, resource_id, resource_version)
references resource_publications(workspace_id, resource_id, version)
on delete cascade
);
create trigger agent_resource_bindings_immutable_guard
before insert or update or delete on agent_resource_bindings
for each row
execute function crank_reject_published_agent_resource_binding_mutation();
create index agent_resource_bindings_resource_idx
on agent_resource_bindings (workspace_id, resource_id, resource_version);
+84 -403
View File
@@ -1,5 +1,6 @@
use super::admin_auth_lifecycle_v8;
use super::agent_catalog_lifecycle_v9;
use super::agent_resource_bindings_v18;
use super::approval_side_effects_v10;
use super::artifact_cleanup_indexes_v13;
use super::artifact_metadata_v12;
@@ -10,6 +11,13 @@ use super::onboarding_import_selection_v15;
use super::onboarding_product_events_v11;
use super::owned_relations;
use super::platform_key_name_reuse_v6;
use super::prompt_dependencies_v23;
use super::prompt_publications_v22;
use super::prompts_v21;
use super::resource_drafts_v16;
use super::resource_publications_v17;
use super::resource_security_revocations_v19;
use super::resource_template_sources_v20;
use super::schema_guard::{
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
};
@@ -23,12 +31,18 @@ use std::fmt;
mod contract;
mod preflight;
use preflight::*;
#[cfg(test)]
use contract::baseline_source_digest;
use contract::validate_descriptors;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 15;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const CURRENT_VERSION: i64 = 23;
const IMPLEMENTED_VERSIONS: &[i64] = &[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
@@ -273,6 +287,49 @@ impl MigrationAuthority {
onboarding_import_selection_v15::SOURCE_SHA256,
14,
),
expand_descriptor(
16,
resource_drafts_v16::NAME,
resource_drafts_v16::SOURCE_SHA256,
15,
),
expand_descriptor(
17,
resource_publications_v17::NAME,
resource_publications_v17::SOURCE_SHA256,
16,
),
expand_descriptor(
18,
agent_resource_bindings_v18::NAME,
agent_resource_bindings_v18::SOURCE_SHA256,
17,
),
expand_descriptor(
19,
resource_security_revocations_v19::NAME,
resource_security_revocations_v19::SOURCE_SHA256,
18,
),
expand_descriptor(
20,
resource_template_sources_v20::NAME,
resource_template_sources_v20::SOURCE_SHA256,
19,
),
expand_descriptor(21, prompts_v21::NAME, prompts_v21::SOURCE_SHA256, 20),
expand_descriptor(
22,
prompt_publications_v22::NAME,
prompt_publications_v22::SOURCE_SHA256,
21,
),
expand_descriptor(
23,
prompt_dependencies_v23::NAME,
prompt_dependencies_v23::SOURCE_SHA256,
22,
),
]
}
pub fn validate_sequence() -> Result<(), MigrationError> {
@@ -407,6 +464,31 @@ impl MigrationAuthority {
if from < 15 {
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
}
if from < 16 {
resource_drafts_v16::apply(&mut transaction, &Self::sequence()[15]).await?;
}
if from < 17 {
resource_publications_v17::apply(&mut transaction, &Self::sequence()[16]).await?;
}
if from < 18 {
agent_resource_bindings_v18::apply(&mut transaction, &Self::sequence()[17]).await?;
}
if from < 19 {
resource_security_revocations_v19::apply(&mut transaction, &Self::sequence()[18])
.await?;
}
if from < 20 {
resource_template_sources_v20::apply(&mut transaction, &Self::sequence()[19]).await?;
}
if from < 21 {
prompts_v21::apply(&mut transaction, &Self::sequence()[20]).await?;
}
if from < 22 {
prompt_publications_v22::apply(&mut transaction, &Self::sequence()[21]).await?;
}
if from < 23 {
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
}
match inspect(&mut transaction).await? {
MigrationPreflight::Current {
version: CURRENT_VERSION,
@@ -430,407 +512,6 @@ impl MigrationAuthority {
})
}
}
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
owned_exists |= relation_exists(connection, relation).await?;
}
if owned_exists {
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_missing",
None,
"restore_known_good_backup",
));
}
inspect_optional_legacy(connection).await?;
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if rows.is_empty() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
None,
"restore_known_good_backup",
));
}
for (index, row) in rows.iter().enumerate() {
let version = row
.try_get::<i64, _>("version")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if version > CURRENT_VERSION {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
}
let Some(expected) = descriptors.get(index) else {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
};
if version != expected.version {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let checksum = row
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if checksum != expected.checksum {
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let name = row
.try_get::<String, _>("name")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let phase = row
.try_get::<String, _>("phase")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let compatibility = row
.try_get::<String, _>("compatibility")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if name != expected.name
|| phase != expected.phase
|| compatibility != expected.compatibility
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.metadata",
Some(version),
"restore_known_good_backup",
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
if rows.len() != usize::try_from(current).unwrap_or_default() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(current),
"restore_known_good_backup",
));
}
validate_schema_fingerprint(connection, current).await?;
if current < CURRENT_VERSION {
Ok(MigrationPreflight::MigrationRequired {
current,
target: CURRENT_VERSION,
})
} else {
validate_required_relations(connection, owned_relations::CONSOLIDATION, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_PRODUCT_EVENTS,
CURRENT_VERSION,
)
.await?;
validate_required_relations(
connection,
owned_relations::ARTIFACT_METADATA,
CURRENT_VERSION,
)
.await?;
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_IMPORT_SELECTION,
CURRENT_VERSION,
)
.await?;
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
async fn is_ledgerless_legacy_baseline(
connection: &mut PgConnection,
canonical_exists: bool,
) -> Result<bool, MigrationError> {
if canonical_exists {
return Ok(false);
}
for relation in [
"__crank_migration_legacy_audit",
"master_key_identities",
"master_key_rotations",
"admin_bootstrap_contracts",
"admin_login_backoff",
"admin_security_audit_events",
"product_events",
"product_event_daily_rollups",
"onboarding_selections",
"onboarding_import_selections",
"artifact_blobs",
"artifact_sources",
] {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
for relation in owned_relations::BASELINE {
if !relation_exists(connection, relation).await? {
return Ok(false);
}
}
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
validate_ledgerless_baseline_fingerprint(connection).await?;
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
if mcp_ledger {
return Ok(false);
}
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
Ok(true)
}
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
.await
.map_err(|_| MigrationError::storage("preflight.core"))?;
if rows.len() != 1 {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_cardinality",
None,
"restore_known_good_backup",
));
}
let version = rows[0]
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let checksum = rows[0]
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let description = rows[0]
.try_get::<String, _>("description")
.map_err(|_| MigrationError::storage("preflight.core"))?;
if version != BASELINE_VERSION
|| description != "community baseline"
|| checksum != BASELINE_CHECKSUM
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.core",
Some(i64::from(version)),
"restore_known_good_backup",
));
}
Ok(())
}
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, false).await
}
async fn inspect_optional_legacy_for_ledgerless_baseline(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, true).await
}
async fn inspect_optional_legacy_with_policy(
connection: &mut PgConnection,
allow_sessions_without_ledger: bool,
) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
if mcp_ledger {
let rows =
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
if rows.len() != 1
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
!= Some("mcp-transport-sessions-v1")
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
}
if relation_exists(connection, "__crank_ext_migrations").await? {
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<i64, _>("count")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if count > 1_000 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
if count > 0 {
let checksum_column = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = '__crank_ext_migrations'
and column_name = 'checksum'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if !checksum_column {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
let rows = query(
"select extension_name, version, checksum
from __crank_ext_migrations
order by extension_name, version
limit 1001",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
for row in rows {
let name = row
.try_get::<String, _>("extension_name")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let version = row
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let checksum = row
.try_get::<Option<String>, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let registered = MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& descriptor.version == u32::try_from(version).unwrap_or_default()
&& checksum.as_deref() == Some(descriptor.checksum)
});
if !registered {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
Some(i64::from(version)),
"contact_operator",
));
}
}
}
}
Ok(())
}
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
from __crank_migration_legacy_audit
order by source, source_version
limit 1002",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
if rows.len() > 1001 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
None,
"contact_operator",
));
}
for row in rows {
let source = row
.try_get::<String, _>("source")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let version = row
.try_get::<i64, _>("source_version")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let checksum = row
.try_get::<String, _>("source_checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|| source.strip_prefix("extension:").is_some_and(|name| {
MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& i64::from(descriptor.version) == version
&& descriptor.checksum == checksum
})
});
if !valid {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
Some(version),
"restore_known_good_backup",
));
}
}
Ok(())
}
async fn create_core_ledger(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
@@ -133,6 +133,13 @@ pub(super) fn validate_descriptors(
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
!= onboarding_import_selection_v15::SOURCE_SHA256
|| sha256_hex(resource_drafts_v16::SOURCE.as_bytes()) != resource_drafts_v16::SOURCE_SHA256
|| sha256_hex(resource_publications_v17::SOURCE.as_bytes())
!= resource_publications_v17::SOURCE_SHA256
|| sha256_hex(agent_resource_bindings_v18::SOURCE.as_bytes())
!= agent_resource_bindings_v18::SOURCE_SHA256
|| sha256_hex(resource_security_revocations_v19::SOURCE.as_bytes())
!= resource_security_revocations_v19::SOURCE_SHA256
{
return Err(MigrationError::new(
"invalid_contract",
@@ -0,0 +1,409 @@
//! Preflight/legacy-state inspection (вынесено из `authority.rs`, чтобы файл
//! оставался в пределах rust-code-health); поведение не меняется.
use super::*;
pub(super) async fn inspect(
connection: &mut PgConnection,
) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
owned_exists |= relation_exists(connection, relation).await?;
}
if owned_exists {
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_missing",
None,
"restore_known_good_backup",
));
}
inspect_optional_legacy(connection).await?;
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if rows.is_empty() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
None,
"restore_known_good_backup",
));
}
for (index, row) in rows.iter().enumerate() {
let version = row
.try_get::<i64, _>("version")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if version > CURRENT_VERSION {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
}
let Some(expected) = descriptors.get(index) else {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
};
if version != expected.version {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let checksum = row
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if checksum != expected.checksum {
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let name = row
.try_get::<String, _>("name")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let phase = row
.try_get::<String, _>("phase")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let compatibility = row
.try_get::<String, _>("compatibility")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if name != expected.name
|| phase != expected.phase
|| compatibility != expected.compatibility
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.metadata",
Some(version),
"restore_known_good_backup",
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
if rows.len() != usize::try_from(current).unwrap_or_default() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(current),
"restore_known_good_backup",
));
}
validate_schema_fingerprint(connection, current).await?;
if current < CURRENT_VERSION {
Ok(MigrationPreflight::MigrationRequired {
current,
target: CURRENT_VERSION,
})
} else {
for relations in [
owned_relations::CONSOLIDATION,
owned_relations::ONBOARDING_PRODUCT_EVENTS,
owned_relations::ARTIFACT_METADATA,
owned_relations::IMPORT_PLAN,
owned_relations::ONBOARDING_IMPORT_SELECTION,
owned_relations::RESOURCE_DRAFTS,
owned_relations::RESOURCE_PUBLICATIONS,
owned_relations::AGENT_RESOURCE_BINDINGS,
owned_relations::RESOURCE_SECURITY_REVOCATIONS,
owned_relations::RESOURCE_TEMPLATE_SOURCES,
owned_relations::PROMPTS,
owned_relations::PROMPT_PUBLICATIONS,
owned_relations::PROMPT_DEPENDENCIES,
] {
validate_required_relations(connection, relations, CURRENT_VERSION).await?;
}
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
pub(super) async fn is_ledgerless_legacy_baseline(
connection: &mut PgConnection,
canonical_exists: bool,
) -> Result<bool, MigrationError> {
if canonical_exists {
return Ok(false);
}
for relation in [
"__crank_migration_legacy_audit",
"master_key_identities",
"master_key_rotations",
"admin_bootstrap_contracts",
"admin_login_backoff",
"admin_security_audit_events",
"product_events",
"product_event_daily_rollups",
"onboarding_selections",
"onboarding_import_selections",
"artifact_blobs",
"artifact_sources",
] {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
for relation in owned_relations::BASELINE {
if !relation_exists(connection, relation).await? {
return Ok(false);
}
}
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
validate_ledgerless_baseline_fingerprint(connection).await?;
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
if mcp_ledger {
return Ok(false);
}
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
Ok(true)
}
pub(super) async fn validate_core_ledger(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
.await
.map_err(|_| MigrationError::storage("preflight.core"))?;
if rows.len() != 1 {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_cardinality",
None,
"restore_known_good_backup",
));
}
let version = rows[0]
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let checksum = rows[0]
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let description = rows[0]
.try_get::<String, _>("description")
.map_err(|_| MigrationError::storage("preflight.core"))?;
if version != BASELINE_VERSION
|| description != "community baseline"
|| checksum != BASELINE_CHECKSUM
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.core",
Some(i64::from(version)),
"restore_known_good_backup",
));
}
Ok(())
}
pub(super) async fn inspect_optional_legacy(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, false).await
}
pub(super) async fn inspect_optional_legacy_for_ledgerless_baseline(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, true).await
}
pub(super) async fn inspect_optional_legacy_with_policy(
connection: &mut PgConnection,
allow_sessions_without_ledger: bool,
) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
if mcp_ledger {
let rows =
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
if rows.len() != 1
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
!= Some("mcp-transport-sessions-v1")
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
}
if relation_exists(connection, "__crank_ext_migrations").await? {
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<i64, _>("count")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if count > 1_000 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
if count > 0 {
let checksum_column = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = '__crank_ext_migrations'
and column_name = 'checksum'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if !checksum_column {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
let rows = query(
"select extension_name, version, checksum
from __crank_ext_migrations
order by extension_name, version
limit 1001",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
for row in rows {
let name = row
.try_get::<String, _>("extension_name")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let version = row
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let checksum = row
.try_get::<Option<String>, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let registered = MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& descriptor.version == u32::try_from(version).unwrap_or_default()
&& checksum.as_deref() == Some(descriptor.checksum)
});
if !registered {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
Some(i64::from(version)),
"contact_operator",
));
}
}
}
}
Ok(())
}
pub(super) async fn validate_legacy_audit(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
from __crank_migration_legacy_audit
order by source, source_version
limit 1002",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
if rows.len() > 1001 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
None,
"contact_operator",
));
}
for row in rows {
let source = row
.try_get::<String, _>("source")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let version = row
.try_get::<i64, _>("source_version")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let checksum = row
.try_get::<String, _>("source_checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|| source.strip_prefix("extension:").is_some_and(|name| {
MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& i64::from(descriptor.version) == version
&& descriptor.checksum == checksum
})
});
if !valid {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
Some(version),
"restore_known_good_backup",
));
}
}
Ok(())
}
@@ -8,7 +8,9 @@ fn sequence_is_deterministic_and_append_only() {
MigrationAuthority::validate_sequence().unwrap();
assert_eq!(
first.iter().map(|item| item.version).collect::<Vec<_>>(),
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
vec![
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
]
);
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
@@ -33,6 +33,28 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
pub(super) const RESOURCE_DRAFTS: &[&str] = &["resources", "resource_versions"];
pub(super) const RESOURCE_PUBLICATIONS: &[&str] = &["resource_publications"];
pub(super) const AGENT_RESOURCE_BINDINGS: &[&str] = &["agent_resource_bindings"];
pub(super) const RESOURCE_SECURITY_REVOCATIONS: &[&str] = &["resource_security_revocations"];
pub(super) const RESOURCE_TEMPLATE_SOURCES: &[&str] = &["resource_template_sources"];
pub(super) const PROMPTS: &[&str] = &[
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
];
pub(super) const PROMPT_PUBLICATIONS: &[&str] = &["prompt_publications", "agent_prompt_bindings"];
pub(super) const PROMPT_DEPENDENCIES: &[&str] =
&["prompt_dependencies", "prompt_message_resource_refs"];
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompt-dependencies-v23";
pub(super) const SOURCE: &str = include_str!("prompt_dependencies_v23.sql");
pub(super) const SOURCE_SHA256: &str =
"15799d41e73021386bf1bae5952cbd34df93317cbce1a97fa8f99b3bd15cac64";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompt_dependencies_v23",
Some(23),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(23),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,74 @@
-- V23: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
--
-- `prompt_dependencies` фиксирует точную опубликованную версию Resource, которую Draft/Prompt
-- объявил в `dependencies`, вместе с разрешёнными на момент сохранения метаданными пина
-- (digest/kind/mime/source_class/sensitivity). Строки version-keyed: правка зависимости
-- требует нового Draft и новой публикации, поэтому уже опубликованная версия не меняется.
--
-- `prompt_message_resource_refs` хранит объявленные точки вставки: упорядоченный список
-- индексов `dependencies` у конкретного сообщения. Отдельная таблица (а не колонка в
-- `prompt_messages`) сохраняет уже принятую схему сообщений без изменения её отпечатка.
--
-- Guard-функция v22 (`crank_reject_published_prompt_version_mutation`) применяется к обеим
-- новым таблицам тем же способом, что к arguments/messages: опубликованная версия immutable.
create table prompt_dependencies (
workspace_id text not null,
prompt_id text not null,
version integer not null,
dependency_position integer not null,
resource_id text not null,
resource_version integer not null,
digest text not null,
kind text not null,
mime_type text not null,
source_class text not null,
sensitivity text not null,
constraint prompt_dependencies_pkey primary key (workspace_id, prompt_id, version, dependency_position),
constraint prompt_dependencies_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_dependencies_position_check check (dependency_position between 0 and 15),
constraint prompt_dependencies_resource_version_check check (resource_version >= 1),
constraint prompt_dependencies_kind_check check (kind in ('text', 'json', 'binary')),
constraint prompt_dependencies_source_class_check check (source_class in ('static', 'dynamic')),
constraint prompt_dependencies_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint prompt_dependencies_digest_check check (octet_length(digest) between 1 and 256),
constraint prompt_dependencies_mime_check check (octet_length(mime_type) between 1 and 255),
constraint prompt_dependencies_resource_id_check check (
octet_length(resource_id) between 1 and 160
)
);
create table prompt_message_resource_refs (
workspace_id text not null,
prompt_id text not null,
version integer not null,
message_position integer not null,
ref_position integer not null,
dependency_position integer not null,
constraint prompt_message_resource_refs_pkey primary key (
workspace_id, prompt_id, version, message_position, ref_position
),
constraint prompt_message_resource_refs_version_fkey
foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_message_resource_refs_message_check check (
message_position between 0 and 63
),
constraint prompt_message_resource_refs_ref_check check (ref_position between 0 and 15),
constraint prompt_message_resource_refs_dependency_check check (
dependency_position between 0 and 15
)
);
create trigger prompt_dependencies_immutable_guard
before insert or update or delete on prompt_dependencies
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_message_resource_refs_immutable_guard
before insert or update or delete on prompt_message_resource_refs
for each row
execute function crank_reject_published_prompt_version_mutation();
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompt-publications-v22";
pub(super) const SOURCE: &str = include_str!("prompt_publications_v22.sql");
pub(super) const SOURCE_SHA256: &str =
"b330b248f164fc6f3635739668f5ea94dc48f0e84d18f0d3dfceb92ff6c445e7";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompt_publications_v22",
Some(22),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(22),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,195 @@
-- V22: immutable Published Prompt Versions и typed exact Prompt bindings Agent
-- (Story 3.13, FR-17).
--
-- `prompt_publications` фиксирует lifecycle-снимок публикации: точная версия,
-- name/description/sensitivity на момент publish и `published_at`. Сама
-- definition (arguments/messages) остаётся в version-keyed `prompt_arguments` и
-- `prompt_messages`; поэтому снимок не дублирует байты, а отдельная guard-функция
-- запрещает менять definition уже опубликованной версии. Archive — не revoke:
-- immutable строки остаются.
--
-- `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
-- Published Prompt Version для точной версии Agent. Composite FK проверяет
-- workspace на обоих концах, поэтому `latest`-версия и чужая публикация в
-- binding попасть не могут.
alter table prompts
add column latest_published_version integer,
add constraint prompts_latest_published_version_check check (
latest_published_version is null or latest_published_version >= 1
);
create table prompt_publications (
workspace_id text not null,
prompt_id text not null,
version integer not null,
name text not null,
description text not null,
sensitivity text not null,
published_at timestamptz not null,
constraint prompt_publications_pkey primary key (workspace_id, prompt_id, version),
constraint prompt_publications_version_check check (version >= 1),
constraint prompt_publications_name_length_check check (
octet_length(name) between 1 and 16384
),
constraint prompt_publications_description_length_check check (
octet_length(description) between 1 and 16384
),
constraint prompt_publications_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint prompt_publications_prompt_fkey
foreign key (workspace_id, prompt_id)
references prompts(workspace_id, prompt_id) on delete cascade,
constraint prompt_publications_version_fkey
foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version)
on delete cascade
);
-- Опубликованная definition immutable: guard смотрит и OLD, и NEW ключ строки.
-- Удаление допускается только вместе с owning prompt (cascade), потому что archive
-- является lifecycle-состоянием, а не удалением снимка.
create function crank_reject_published_prompt_version_mutation()
returns trigger
language plpgsql
as $$
declare
published boolean;
owner_present boolean;
begin
if tg_op in ('UPDATE', 'DELETE') then
select exists (
select 1 from prompt_publications
where workspace_id = old.workspace_id
and prompt_id = old.prompt_id
and version = old.version
), exists (
select 1 from prompts
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
)
into published, owner_present;
if published and owner_present then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select exists (
select 1 from prompt_publications
where workspace_id = new.workspace_id
and prompt_id = new.prompt_id
and version = new.version
) into published;
if published then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create function crank_reject_prompt_publication_mutation()
returns trigger
language plpgsql
as $$
declare
owner_present boolean;
begin
if tg_op = 'DELETE' then
select exists (
select 1 from prompts
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
) into owner_present;
if owner_present then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
return old;
end if;
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end;
$$;
create trigger prompt_arguments_immutable_guard
before insert or update or delete on prompt_arguments
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_messages_immutable_guard
before insert or update or delete on prompt_messages
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_publications_immutable_guard
before update or delete on prompt_publications
for each row
execute function crank_reject_prompt_publication_mutation();
create table agent_prompt_bindings (
workspace_id text not null,
agent_id text not null,
agent_version integer not null,
prompt_id text not null,
prompt_version integer not null,
constraint agent_prompt_bindings_agent_version_check check (agent_version >= 1),
constraint agent_prompt_bindings_prompt_version_check check (prompt_version >= 1),
primary key (agent_id, agent_version, prompt_id),
constraint agent_prompt_bindings_agent_workspace_fkey
foreign key (workspace_id, agent_id)
references agents(workspace_id, id) on delete cascade,
constraint agent_prompt_bindings_agent_version_fkey
foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade,
constraint agent_prompt_bindings_publication_fkey
foreign key (workspace_id, prompt_id, prompt_version)
references prompt_publications(workspace_id, prompt_id, version)
on delete cascade
);
create function crank_reject_published_agent_prompt_binding_mutation()
returns trigger
language plpgsql
as $$
declare
bound_status text;
begin
if tg_op in ('UPDATE', 'DELETE') then
select status
into bound_status
from agent_versions
where agent_id = old.agent_id and version = old.agent_version;
if bound_status = 'published' then
raise exception 'published Agent Prompt bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select status
into bound_status
from agent_versions
where agent_id = new.agent_id and version = new.agent_version;
if bound_status = 'published' then
raise exception 'published Agent Prompt bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create trigger agent_prompt_bindings_immutable_guard
before insert or update or delete on agent_prompt_bindings
for each row
execute function crank_reject_published_agent_prompt_binding_mutation();
create index agent_prompt_bindings_publication_idx
on agent_prompt_bindings (workspace_id, prompt_id, prompt_version);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompts-v21";
pub(super) const SOURCE: &str = include_str!("prompts_v21.sql");
pub(super) const SOURCE_SHA256: &str =
"c62717f8eb87b249b7771c74517ce99baeaf2793bfd5fca5d15e8412112bc53e";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompts_v21",
Some(21),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(21),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,71 @@
-- V21: typed Prompt Draft aggregate and ordered arguments/messages (Story 3.12).
create table prompts (
workspace_id text not null references workspaces(id) on delete cascade,
prompt_id text not null,
name text not null,
description text not null,
status text not null default 'draft',
sensitivity text not null,
current_draft_version integer not null default 1,
created_at timestamptz not null,
updated_at timestamptz not null,
constraint prompts_pkey primary key (workspace_id, prompt_id),
constraint prompts_id_check check (prompt_id ~ '^prm_[A-Za-z0-9_-]{1,128}$'),
constraint prompts_name_length_check check (octet_length(name) between 1 and 16384),
constraint prompts_description_length_check check (octet_length(description) between 1 and 16384),
constraint prompts_status_check check (status in ('draft', 'published', 'archived')),
constraint prompts_sensitivity_check check (sensitivity in ('public', 'internal', 'secret')),
constraint prompts_draft_version_check check (current_draft_version >= 1)
);
create table prompt_versions (
workspace_id text not null,
prompt_id text not null,
version integer not null,
created_at timestamptz not null,
constraint prompt_versions_pkey primary key (workspace_id, prompt_id, version),
constraint prompt_versions_prompt_fkey foreign key (workspace_id, prompt_id)
references prompts(workspace_id, prompt_id) on delete cascade,
constraint prompt_versions_version_check check (version >= 1)
);
create table prompt_arguments (
workspace_id text not null,
prompt_id text not null,
version integer not null,
argument_name text not null,
argument_type text not null,
required boolean not null,
default_value jsonb,
enumeration jsonb,
position integer not null,
constraint prompt_arguments_pkey primary key (workspace_id, prompt_id, version, argument_name),
constraint prompt_arguments_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_arguments_type_check check (argument_type in ('string', 'number', 'integer', 'boolean')),
constraint prompt_arguments_name_check check (octet_length(argument_name) between 1 and 16384),
constraint prompt_arguments_position_check check (position >= 0),
constraint prompt_arguments_default_size_check check (default_value is null or octet_length(default_value::text) <= 16384),
constraint prompt_arguments_enum_size_check check (
enumeration is null or case
when jsonb_typeof(enumeration) = 'array'
then jsonb_array_length(enumeration) between 1 and 64
else false
end
)
);
create table prompt_messages (
workspace_id text not null,
prompt_id text not null,
version integer not null,
position integer not null,
role text not null,
content text not null,
constraint prompt_messages_pkey primary key (workspace_id, prompt_id, version, position),
constraint prompt_messages_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_messages_position_check check (position between 0 and 63),
constraint prompt_messages_role_check check (role in ('system', 'user', 'assistant')),
constraint prompt_messages_content_check check (octet_length(content) between 1 and 16384)
);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-drafts-v16";
pub(super) const SOURCE: &str = include_str!("resource_drafts_v16.sql");
pub(super) const SOURCE_SHA256: &str =
"0ed07dabd37f97e212923650b80278898c4e9519cee0cda4170f6b2b2a3d92d7";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_drafts",
Some(16),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(16),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,76 @@
-- V16: typed static Resource drafts (Story 3.6, D-15).
--
-- Байты не хранятся здесь: содержимое версии — это content-addressed blob
-- (`artifact_blobs`) и owning-ссылка (`artifact_sources`), поэтому Resource
-- участвует в существующем учёте владения и sweep-е (AD-10).
-- Filesystem path, raw filename и mutable external reference намеренно
-- отсутствуют (D-12).
create table resources (
workspace_id text not null references workspaces(id) on delete cascade,
resource_id text not null,
uri text not null,
name text not null,
description text not null default '',
status text not null default 'draft',
kind text not null,
current_draft_version integer not null,
created_at timestamptz not null,
updated_at timestamptz not null,
constraint resources_resource_id_check check (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'),
constraint resources_uri_len_check check (octet_length(uri) between 10 and 200),
constraint resources_name_len_check check (octet_length(name) between 1 and 64),
constraint resources_description_len check (octet_length(description) <= 1024),
constraint resources_status_check check (status in ('draft', 'published', 'archived')),
constraint resources_kind_check check (kind in ('text', 'json', 'binary')),
constraint resources_current_version_check check (current_draft_version >= 1),
constraint resources_timestamps_check check (updated_at >= created_at),
constraint resources_workspace_uri_unique unique (workspace_id, uri),
constraint resources_workspace_name_unique unique (workspace_id, name),
primary key (workspace_id, resource_id)
);
create table resource_versions (
workspace_id text not null,
resource_id text not null,
version integer not null,
kind text not null,
mime_type text not null,
size_bytes bigint not null,
digest text not null,
sensitivity text not null,
artifact_source_id text not null,
created_at timestamptz not null,
superseded_at timestamptz null,
constraint resource_versions_version_check check (version >= 1),
constraint resource_versions_kind_check check (kind in ('text', 'json', 'binary')),
constraint resource_versions_mime_type_check check (
octet_length(mime_type) between 3 and 255
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
),
constraint resource_versions_size_check check (size_bytes between 1 and 262144),
constraint resource_versions_digest_check check (digest ~ '^[0-9a-f]{64}$'),
constraint resource_versions_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint resource_versions_source_id_check check (
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
),
constraint resource_versions_supersede_check check (
superseded_at is null or superseded_at >= created_at
),
primary key (workspace_id, resource_id, version),
constraint resource_versions_resource_fkey foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete cascade,
constraint resource_versions_source_fkey foreign key (workspace_id, artifact_source_id)
references artifact_sources(workspace_id, source_id)
);
-- Ровно одна текущая черновая версия на Resource: пометка прежней версии
-- обязана произойти до вставки новой (D-15 шаг 4), индекс не ослабляется.
create unique index resource_versions_current_draft_unique
on resource_versions (workspace_id, resource_id)
where superseded_at is null;
create index resources_workspace_created_idx
on resources (workspace_id, created_at, resource_id);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-publications-v17";
pub(super) const SOURCE: &str = include_str!("resource_publications_v17.sql");
pub(super) const SOURCE_SHA256: &str =
"eaefc08d25ba5ab92775dd9263ced14d927e28b558444f83ea789f1f0023c092";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_publications",
Some(17),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(17),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,67 @@
-- V17: immutable Published Resource Versions (Story 3.7, FR-15/FR-16).
--
-- Строка публикации — снимок публичных metadata на момент publish. Байты не
-- дублируются: отдельная owning-ссылка (`artifact_source_id`) указывает на тот же
-- content-addressed blob, поэтому Draft update не может отсоединить published bytes.
-- Filesystem path, raw upload filename и mutable external reference отсутствуют.
--
-- Закрытая таблица не является универсальным JSON blob: exact published version
-- адресуется composite PK (workspace_id, resource_id, version) и FK на
-- `resource_versions`.
create table resource_publications (
workspace_id text not null,
resource_id text not null,
version integer not null,
uri text not null,
name text not null,
description text not null default '',
kind text not null,
mime_type text not null,
size_bytes bigint not null,
digest text not null,
sensitivity text not null,
artifact_source_id text not null,
published_at timestamptz not null,
constraint resource_publications_version_check check (version >= 1),
constraint resource_publications_uri_len_check check (
octet_length(uri) between 10 and 200
),
constraint resource_publications_name_len_check check (
octet_length(name) between 1 and 64
),
constraint resource_publications_description_len check (
octet_length(description) <= 1024
),
constraint resource_publications_kind_check check (
kind in ('text', 'json', 'binary')
),
constraint resource_publications_mime_type_check check (
octet_length(mime_type) between 3 and 255
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
),
constraint resource_publications_size_check check (
size_bytes between 1 and 262144
),
constraint resource_publications_digest_check check (digest ~ '^[0-9a-f]{64}$'),
constraint resource_publications_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint resource_publications_source_id_check check (
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
),
primary key (workspace_id, resource_id, version),
constraint resource_publications_resource_fkey
foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete cascade,
constraint resource_publications_version_fkey
foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade,
constraint resource_publications_source_fkey
foreign key (workspace_id, artifact_source_id)
references artifact_sources(workspace_id, source_id)
);
create index resource_publications_workspace_uri_idx
on resource_publications (workspace_id, uri, published_at desc);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-security-revocations-v19";
pub(super) const SOURCE: &str = include_str!("resource_security_revocations_v19.sql");
pub(super) const SOURCE_SHA256: &str =
"e66493a4014af5cbf1ed7532ab7140ce773dc30b0995dea242b791f51dad5bc0";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_security_revocations",
Some(19),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(19),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,47 @@
-- V19: Resource-wide security revocation (Story 3.8, FR-15/FR-16).
--
-- Owner decision A (`t_6f76be08`): revoking a Resource denies every version of it
-- in every Agent, including already published snapshots, and forbids new
-- publications/bindings. The tombstone is also its own immutable transition
-- record: one row per workspace/Resource, the first successful actor/time is
-- never rewritten, and no UPDATE/DELETE/restore path exists in this slice.
--
-- Only the stable identity is stored. No content, URI, name, MIME, digest,
-- reason or secret is duplicated here; archive and the immutable published
-- snapshot bytes stay untouched.
--
-- The composite FK pins the tombstone to an existing Resource of the same
-- workspace, and the actor FK to a real user without cascading deletion, so the
-- audit row cannot outlive its referents or be detached by deleting a user.
-- An empty table means the previous (unrevoked) behaviour, so old installations
-- need no data migration.
create function crank_reject_resource_security_revocation_mutation()
returns trigger
language plpgsql
as $$
begin
raise exception 'resource security revocations are immutable'
using errcode = '23514';
end;
$$;
create table resource_security_revocations (
workspace_id text not null,
resource_id text not null,
revoked_at timestamptz not null,
actor_user_id text not null,
request_id text not null,
trace_id text not null,
primary key (workspace_id, resource_id),
constraint resource_security_revocations_resource_fkey
foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete restrict,
constraint resource_security_revocations_actor_fkey
foreign key (actor_user_id) references users(id) on delete restrict
);
create trigger resource_security_revocations_immutable_guard
before update or delete on resource_security_revocations
for each row
execute function crank_reject_resource_security_revocation_mutation();
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-template-sources-v20";
pub(super) const SOURCE: &str = include_str!("resource_template_sources_v20.sql");
pub(super) const SOURCE_SHA256: &str =
"1537f7267f4bb5317242f3c20d613dd9a5b4e5b01cec5c578949f431e91f7502";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_template_sources",
Some(20),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(20),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,111 @@
-- V20: byte-less REST-backed Resource template definitions (Story 3.10, FR-16).
--
-- Шаблон не имеет файла содержимого: определение живёт отдельной version-keyed
-- строкой (`resource_template_sources`) рядом с версией, а не в artifact blob.
-- Поэтому `source_kind` отделяет artifact-строки (прежние инварианты байт
-- сохранены буквально) от template-строк (artifact_source_id null, size 0,
-- digest = digest определения).
--
-- Publication snapshot остаётся неизменяемым: `resource_template_sources`
-- insert-only (UPDATE запрещён trigger-ом), а published-версия адресует ту же
-- version-keyed строку, поэтому правка Draft не меняет опубликованное определение.
alter table resource_versions
add column source_kind text not null default 'artifact';
alter table resource_versions
alter column artifact_source_id drop not null;
alter table resource_versions
drop constraint resource_versions_size_check;
alter table resource_versions
add constraint resource_versions_size_check check (
(source_kind = 'artifact' and size_bytes between 1 and 262144)
or (source_kind = 'template' and size_bytes = 0)
);
alter table resource_versions
drop constraint resource_versions_source_id_check;
alter table resource_versions
add constraint resource_versions_source_id_check check (
(
source_kind = 'artifact'
and artifact_source_id is not null
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
)
or (source_kind = 'template' and artifact_source_id is null)
);
alter table resource_versions
add constraint resource_versions_source_kind_check check (
source_kind in ('artifact', 'template')
);
alter table resource_publications
add column source_kind text not null default 'artifact';
alter table resource_publications
alter column artifact_source_id drop not null;
alter table resource_publications
drop constraint resource_publications_size_check;
alter table resource_publications
add constraint resource_publications_size_check check (
(source_kind = 'artifact' and size_bytes between 1 and 262144)
or (source_kind = 'template' and size_bytes = 0)
);
alter table resource_publications
drop constraint resource_publications_source_id_check;
alter table resource_publications
add constraint resource_publications_source_id_check check (
(
source_kind = 'artifact'
and artifact_source_id is not null
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
)
or (source_kind = 'template' and artifact_source_id is null)
);
alter table resource_publications
add constraint resource_publications_source_kind_check check (
source_kind in ('artifact', 'template')
);
create table resource_template_sources (
workspace_id text not null,
resource_id text not null,
version integer not null,
definition_json text not null,
definition_digest text not null,
created_at timestamptz not null,
constraint resource_template_sources_version_check check (version >= 1),
constraint resource_template_sources_definition_len_check check (
octet_length(definition_json) between 2 and 65536
),
constraint resource_template_sources_digest_check check (
definition_digest ~ '^[0-9a-f]{64}$'
),
primary key (workspace_id, resource_id, version),
constraint resource_template_sources_version_fkey
foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade
);
create function crank_guard_resource_template_source_immutable()
returns trigger
language plpgsql
as $$
begin
raise exception 'resource template source definitions are immutable';
end;
$$;
create trigger crank_guard_resource_template_source_immutable
before update on resource_template_sources
for each row execute function crank_guard_resource_template_source_immutable();
@@ -2,269 +2,10 @@ use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
pub(super) const OWNED_RELATIONS: &[&str] = &[
"__crank_core_migrations",
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"__crank_ext_migrations",
"mcp_transport_sessions",
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"master_key_identities",
"master_key_rotations",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
"artifact_blobs",
"artifact_sources",
"import_plans",
"import_plan_applications",
"onboarding_import_selections",
];
mod required_tables;
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
(
"__crank_core_migrations",
&["version", "description", "checksum", "applied_at"],
),
(
"__crank_migrations",
&[
"version",
"name",
"checksum",
"phase",
"compatibility",
"applied_at",
],
),
(
"__crank_migration_legacy_audit",
&["source", "source_version", "source_checksum", "imported_at"],
),
(
"__crank_mcp_migrations",
&["version", "checksum", "applied_at"],
),
(
"__crank_ext_migrations",
&["extension_name", "version", "checksum", "applied_at"],
),
(
"mcp_transport_sessions",
&[
"id",
"protocol_version",
"initialized",
"supports_elicitation",
"workspace_slug",
"agent_slug",
"created_at",
"updated_at",
"expires_at",
],
),
(
"master_key_identities",
&[
"epoch",
"fingerprint",
"cipher_contract",
"status",
"backup_ref",
"created_at",
"activated_at",
"retired_at",
],
),
(
"master_key_rotations",
&[
"id",
"source_epoch",
"target_epoch",
"target_fingerprint",
"state",
"backup_ref",
"checkpoint_secret_id",
"total_secret_versions",
"processed_secret_versions",
"verified_secret_versions",
"failure_code",
"created_at",
"updated_at",
],
),
];
const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
("__crank_core_migrations", "version", "integer", false),
("__crank_core_migrations", "description", "text", false),
("__crank_core_migrations", "checksum", "text", false),
(
"__crank_core_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migrations", "version", "bigint", false),
("__crank_migrations", "name", "text", false),
("__crank_migrations", "checksum", "text", false),
("__crank_migrations", "phase", "text", false),
("__crank_migrations", "compatibility", "text", false),
(
"__crank_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migration_legacy_audit", "source", "text", false),
(
"__crank_migration_legacy_audit",
"source_version",
"bigint",
false,
),
(
"__crank_migration_legacy_audit",
"source_checksum",
"text",
false,
),
(
"__crank_migration_legacy_audit",
"imported_at",
"timestamp with time zone",
false,
),
("__crank_mcp_migrations", "version", "integer", false),
("__crank_mcp_migrations", "checksum", "text", false),
(
"__crank_mcp_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_ext_migrations", "extension_name", "text", false),
("__crank_ext_migrations", "version", "integer", false),
("__crank_ext_migrations", "checksum", "text", true),
(
"__crank_ext_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("mcp_transport_sessions", "id", "text", false),
("mcp_transport_sessions", "protocol_version", "text", false),
("mcp_transport_sessions", "initialized", "boolean", false),
(
"mcp_transport_sessions",
"supports_elicitation",
"boolean",
false,
),
("mcp_transport_sessions", "workspace_slug", "text", false),
("mcp_transport_sessions", "agent_slug", "text", false),
(
"mcp_transport_sessions",
"created_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"updated_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"expires_at",
"timestamp with time zone",
true,
),
("master_key_identities", "epoch", "bigint", false),
("master_key_identities", "fingerprint", "text", false),
("master_key_identities", "cipher_contract", "text", false),
("master_key_identities", "status", "text", false),
("master_key_identities", "backup_ref", "text", true),
(
"master_key_identities",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_identities",
"activated_at",
"timestamp with time zone",
true,
),
(
"master_key_identities",
"retired_at",
"timestamp with time zone",
true,
),
("master_key_rotations", "id", "text", false),
("master_key_rotations", "source_epoch", "bigint", false),
("master_key_rotations", "target_epoch", "bigint", false),
("master_key_rotations", "target_fingerprint", "text", false),
("master_key_rotations", "state", "text", false),
("master_key_rotations", "backup_ref", "text", true),
("master_key_rotations", "checkpoint_secret_id", "text", true),
(
"master_key_rotations",
"total_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"processed_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"verified_secret_versions",
"bigint",
false,
),
("master_key_rotations", "failure_code", "text", true),
(
"master_key_rotations",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_rotations",
"updated_at",
"timestamp with time zone",
false,
),
];
pub(super) use required_tables::OWNED_RELATIONS;
use required_tables::{REQUIRED_COLUMN_TYPES, REQUIRED_COLUMNS};
pub(super) async fn relation_exists(
connection: &mut PgConnection,
@@ -662,6 +403,71 @@ pub(super) async fn validate_schema_fingerprint(
} else {
super::schema_guard_v15::validate_v15_onboarding_import_selection(connection).await?;
}
if current_version < 16 {
if !super::schema_guard_v16::validate_v16_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v16::validate_v16_resource_drafts(connection, current_version).await?;
}
if current_version < 17 {
if !super::schema_guard_v17::validate_v17_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v17::validate_v17_resource_publications(connection, current_version)
.await?;
}
if current_version < 18 {
if !super::schema_guard_v18::validate_v18_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v18::validate_v18_agent_resource_bindings(connection).await?;
}
if current_version < 19 {
if !super::schema_guard_v19::validate_v19_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v19::validate_v19_resource_security_revocations(connection).await?;
}
if current_version < 20 {
if !super::schema_guard_v20::validate_v20_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v20::validate_v20_resource_template_sources(connection).await?;
}
if current_version < 21 {
for relation in [
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
] {
if relation_exists(connection, relation).await? {
return Err(schema_error(current_version));
}
}
} else {
validate_required_relations(connection, super::owned_relations::PROMPTS, current_version)
.await?;
}
if current_version < 22 {
if !super::schema_guard_v22::validate_v22_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v22::validate_v22_prompt_publications(connection).await?;
}
if current_version < 23 {
if !super::schema_guard_v23::validate_v23_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v23::validate_v23_prompt_dependencies(connection).await?;
}
Ok(())
}
@@ -0,0 +1,414 @@
//! Статические таблицы ожидаемой схемы (вынесены из `schema_guard.rs`, чтобы
//! файл оставался в пределах rust-code-health); поведение guard не меняется.
pub(crate) const OWNED_RELATIONS: &[&str] = &[
"__crank_core_migrations",
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"__crank_ext_migrations",
"mcp_transport_sessions",
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"master_key_identities",
"master_key_rotations",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
"artifact_blobs",
"artifact_sources",
"import_plans",
"import_plan_applications",
"onboarding_import_selections",
"resources",
"resource_versions",
"resource_publications",
"agent_resource_bindings",
"resource_security_revocations",
"resource_template_sources",
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
"prompt_dependencies",
"prompt_message_resource_refs",
];
pub(crate) const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
(
"__crank_core_migrations",
&["version", "description", "checksum", "applied_at"],
),
(
"__crank_migrations",
&[
"version",
"name",
"checksum",
"phase",
"compatibility",
"applied_at",
],
),
(
"__crank_migration_legacy_audit",
&["source", "source_version", "source_checksum", "imported_at"],
),
(
"__crank_mcp_migrations",
&["version", "checksum", "applied_at"],
),
(
"__crank_ext_migrations",
&["extension_name", "version", "checksum", "applied_at"],
),
(
"mcp_transport_sessions",
&[
"id",
"protocol_version",
"initialized",
"supports_elicitation",
"workspace_slug",
"agent_slug",
"created_at",
"updated_at",
"expires_at",
],
),
(
"master_key_identities",
&[
"epoch",
"fingerprint",
"cipher_contract",
"status",
"backup_ref",
"created_at",
"activated_at",
"retired_at",
],
),
(
"master_key_rotations",
&[
"id",
"source_epoch",
"target_epoch",
"target_fingerprint",
"state",
"backup_ref",
"checkpoint_secret_id",
"total_secret_versions",
"processed_secret_versions",
"verified_secret_versions",
"failure_code",
"created_at",
"updated_at",
],
),
(
"prompts",
&[
"workspace_id",
"prompt_id",
"name",
"description",
"status",
"sensitivity",
"current_draft_version",
"latest_published_version",
"created_at",
"updated_at",
],
),
(
"prompt_versions",
&["workspace_id", "prompt_id", "version", "created_at"],
),
(
"prompt_arguments",
&[
"workspace_id",
"prompt_id",
"version",
"argument_name",
"argument_type",
"required",
"default_value",
"enumeration",
"position",
],
),
(
"prompt_messages",
&[
"workspace_id",
"prompt_id",
"version",
"position",
"role",
"content",
],
),
(
"prompt_dependencies",
&[
"workspace_id",
"prompt_id",
"version",
"dependency_position",
"resource_id",
"resource_version",
"digest",
"kind",
"mime_type",
"source_class",
"sensitivity",
],
),
(
"prompt_message_resource_refs",
&[
"workspace_id",
"prompt_id",
"version",
"message_position",
"ref_position",
"dependency_position",
],
),
];
pub(crate) const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
("__crank_core_migrations", "version", "integer", false),
("__crank_core_migrations", "description", "text", false),
("__crank_core_migrations", "checksum", "text", false),
(
"__crank_core_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migrations", "version", "bigint", false),
("__crank_migrations", "name", "text", false),
("__crank_migrations", "checksum", "text", false),
("__crank_migrations", "phase", "text", false),
("__crank_migrations", "compatibility", "text", false),
(
"__crank_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migration_legacy_audit", "source", "text", false),
(
"__crank_migration_legacy_audit",
"source_version",
"bigint",
false,
),
(
"__crank_migration_legacy_audit",
"source_checksum",
"text",
false,
),
(
"__crank_migration_legacy_audit",
"imported_at",
"timestamp with time zone",
false,
),
("__crank_mcp_migrations", "version", "integer", false),
("__crank_mcp_migrations", "checksum", "text", false),
(
"__crank_mcp_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_ext_migrations", "extension_name", "text", false),
("__crank_ext_migrations", "version", "integer", false),
("__crank_ext_migrations", "checksum", "text", true),
(
"__crank_ext_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("mcp_transport_sessions", "id", "text", false),
("mcp_transport_sessions", "protocol_version", "text", false),
("mcp_transport_sessions", "initialized", "boolean", false),
(
"mcp_transport_sessions",
"supports_elicitation",
"boolean",
false,
),
("mcp_transport_sessions", "workspace_slug", "text", false),
("mcp_transport_sessions", "agent_slug", "text", false),
(
"mcp_transport_sessions",
"created_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"updated_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"expires_at",
"timestamp with time zone",
true,
),
("master_key_identities", "epoch", "bigint", false),
("master_key_identities", "fingerprint", "text", false),
("master_key_identities", "cipher_contract", "text", false),
("master_key_identities", "status", "text", false),
("master_key_identities", "backup_ref", "text", true),
(
"master_key_identities",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_identities",
"activated_at",
"timestamp with time zone",
true,
),
(
"master_key_identities",
"retired_at",
"timestamp with time zone",
true,
),
("master_key_rotations", "id", "text", false),
("master_key_rotations", "source_epoch", "bigint", false),
("master_key_rotations", "target_epoch", "bigint", false),
("master_key_rotations", "target_fingerprint", "text", false),
("master_key_rotations", "state", "text", false),
("master_key_rotations", "backup_ref", "text", true),
("master_key_rotations", "checkpoint_secret_id", "text", true),
(
"master_key_rotations",
"total_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"processed_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"verified_secret_versions",
"bigint",
false,
),
("master_key_rotations", "failure_code", "text", true),
(
"master_key_rotations",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_rotations",
"updated_at",
"timestamp with time zone",
false,
),
("prompts", "workspace_id", "text", false),
("prompts", "prompt_id", "text", false),
("prompts", "name", "text", false),
("prompts", "description", "text", false),
("prompts", "status", "text", false),
("prompts", "sensitivity", "text", false),
("prompts", "current_draft_version", "integer", false),
("prompts", "created_at", "timestamp with time zone", false),
("prompts", "updated_at", "timestamp with time zone", false),
("prompt_versions", "workspace_id", "text", false),
("prompt_versions", "prompt_id", "text", false),
("prompt_versions", "version", "integer", false),
(
"prompt_versions",
"created_at",
"timestamp with time zone",
false,
),
("prompt_arguments", "workspace_id", "text", false),
("prompt_arguments", "prompt_id", "text", false),
("prompt_arguments", "version", "integer", false),
("prompt_arguments", "argument_name", "text", false),
("prompt_arguments", "argument_type", "text", false),
("prompt_arguments", "required", "boolean", false),
("prompt_arguments", "default_value", "jsonb", true),
("prompt_arguments", "enumeration", "jsonb", true),
("prompt_arguments", "position", "integer", false),
("prompt_messages", "workspace_id", "text", false),
("prompt_messages", "prompt_id", "text", false),
("prompt_messages", "version", "integer", false),
("prompt_messages", "position", "integer", false),
("prompt_messages", "role", "text", false),
("prompt_messages", "content", "text", false),
("prompt_dependencies", "workspace_id", "text", false),
(
"prompt_dependencies",
"dependency_position",
"integer",
false,
),
("prompt_dependencies", "resource_id", "text", false),
("prompt_dependencies", "resource_version", "integer", false),
("prompt_dependencies", "digest", "text", false),
("prompt_dependencies", "kind", "text", false),
("prompt_dependencies", "mime_type", "text", false),
("prompt_dependencies", "source_class", "text", false),
("prompt_dependencies", "sensitivity", "text", false),
(
"prompt_message_resource_refs",
"message_position",
"integer",
false,
),
(
"prompt_message_resource_refs",
"ref_position",
"integer",
false,
),
(
"prompt_message_resource_refs",
"dependency_position",
"integer",
false,
),
];
@@ -0,0 +1,571 @@
//! V16 schema guard: typed static Resource drafts (Story 3.6).
//!
//! Проверяет, что схема V16 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: таблицы, колонки,
//! constraints (точные определения и CHECK-выражения с сохранением SQL-литералов)
//! и частичный unique-index «одна текущая черновая версия».
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &[
"resources",
"resource_versions",
"resources_workspace_created_idx",
"resource_versions_current_draft_unique",
];
const RESOURCE_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("status", "text", false),
("kind", "text", false),
("current_draft_version", "integer", false),
("created_at", "timestamp with time zone", false),
("updated_at", "timestamp with time zone", false),
];
const VERSION_COLUMNS_V16: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", false),
("created_at", "timestamp with time zone", false),
("superseded_at", "timestamp with time zone", true),
];
/// V20 добавляет `source_kind` и допускает byte-less template-версии: колонки
/// проверяются относительно фактической версии схемы.
const VERSION_COLUMNS_V20: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", true),
("source_kind", "text", false),
("created_at", "timestamp with time zone", false),
("superseded_at", "timestamp with time zone", true),
];
fn version_columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
if current_version >= 20 {
VERSION_COLUMNS_V20
} else {
VERSION_COLUMNS_V16
}
}
/// V20 переопределяет два CHECK-а `resource_versions`: template-строки не имеют
/// artifact-ссылки и байтов, artifact-строки сохраняют прежние границы.
const VERSION_CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
(
"resource_versions_size_check",
"v16.version_size_check",
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
OR source_kind = 'template'::text AND size_bytes = 0)",
),
(
"resource_versions_source_id_check",
"v16.version_source_id_check",
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
),
];
fn version_check_expectations(
current_version: i64,
) -> Vec<(&'static str, &'static str, &'static str)> {
VERSION_CHECK_EXPRESSIONS
.iter()
.map(|(constraint, stage, legacy)| {
let expected = if current_version >= 20 {
VERSION_CHECK_EXPRESSIONS_V20
.iter()
.find(|(name, _, _)| name == constraint)
.map(|(_, _, expected)| *expected)
.unwrap_or(*legacy)
} else {
*legacy
};
(*constraint, *stage, expected)
})
.collect()
}
/// Определения constraints V16, у которых guard сверяет семантику целиком.
///
/// Имя и `contype` сохраняются у всех однофакторных мутаций (`check (true)`,
/// другая цель/колонки/действие удаления, `NOT VALID`), поэтому ожидание
/// сравнивается с нормализованным `pg_get_constraintdef` и требует
/// `convalidated = true` (P4, TL run105 F06).
const RESOURCE_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resources_pkey",
"p",
"v16.resources_pkey",
"primarykeyworkspace_id,resource_id",
),
(
"resources_workspace_id_fkey",
"f",
"v16.resources_workspace_id_fkey",
"foreignkeyworkspace_idreferencesworkspacesidondeletecascade",
),
(
"resources_workspace_uri_unique",
"u",
"v16.resources_workspace_uri_unique",
"uniqueworkspace_id,uri",
),
(
"resources_workspace_name_unique",
"u",
"v16.resources_workspace_name_unique",
"uniqueworkspace_id,name",
),
];
const VERSION_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_versions_pkey",
"p",
"v16.version_pkey",
"primarykeyworkspace_id,resource_id,version",
),
(
"resource_versions_resource_fkey",
"f",
"v16.version_resource_fkey",
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
),
(
"resource_versions_source_fkey",
"f",
"v16.version_source_fkey",
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
),
];
/// CHECK-выражения V16: сверяется **точное** каноническое определение constraint-а
/// (`pg_get_constraintdef(c.oid, true)`) и `convalidated = true`.
///
/// Ожидания записаны ровно так, как их печатает PostgreSQL 16 (снято из `pg_catalog`
/// на канонической схеме V16), и сравниваются через `normalize_v16_definition`,
/// который убирает пробелы и приводит регистр только вне строковых литералов.
///
/// Подстрочная сверка пропускала `check (octet_length(description) <= 1024 or
/// resource_id is not null)` (TL run109 F5), а сверка «по набору литералов» —
/// перечисляющий CHECK с добавленным предикатом (TL run113 EH1). Общая
/// нормализация, снимающая регистр и пробелы по всей строке, пропускала дрейф
/// **внутри** SQL-литералов: `'^[0-9a-f ]{64}$'` (класс с пробелом) и
/// lowercase-вариант MIME-маски совпадали с каноническими (TL run113 EH2).
const RESOURCE_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resources_resource_id_check",
"v16.resources_resource_id_check",
"CHECK (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'::text)",
),
(
"resources_uri_len_check",
"v16.resources_uri_len_check",
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
),
(
"resources_name_len_check",
"v16.resources_name_len_check",
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
),
(
"resources_description_len",
"v16.resources_description_len",
"CHECK (octet_length(description) <= 1024)",
),
(
"resources_status_check",
"v16.resources_status_check",
"CHECK (status = ANY (ARRAY['draft'::text, 'published'::text, 'archived'::text]))",
),
(
"resources_kind_check",
"v16.resources_kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resources_current_version_check",
"v16.resources_current_version_check",
"CHECK (current_draft_version >= 1)",
),
(
"resources_timestamps_check",
"v16.resources_timestamps_check",
"CHECK (updated_at >= created_at)",
),
];
const VERSION_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_versions_version_check",
"v16.version_version_check",
"CHECK (version >= 1)",
),
(
"resource_versions_kind_check",
"v16.version_kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resource_versions_mime_type_check",
"v16.version_mime_type_check",
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
),
(
"resource_versions_size_check",
"v16.version_size_check",
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
),
(
"resource_versions_digest_check",
"v16.version_digest_check",
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_versions_sensitivity_check",
"v16.version_sensitivity_check",
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
),
(
"resource_versions_source_id_check",
"v16.version_source_id_check",
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
),
(
"resource_versions_supersede_check",
"v16.version_supersede_check",
"CHECK (superseded_at IS NULL OR superseded_at >= created_at)",
),
];
/// Отказ guard-а V16 с указанием конкретной проверки: наблюдаемый stage помогает
/// быстро локализовать расхождение схемы, не ослабляя сам отказ.
fn v16_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(16),
"restore_known_good_backup",
)
}
/// Схема V16 отсутствует целиком (для current_version < 16).
pub(super) async fn validate_v16_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V16 присутствует в ожидаемой форме (для current_version >= 16).
pub(super) async fn validate_v16_resource_drafts(
connection: &mut PgConnection,
current_version: i64,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v16_error("v16.relations"));
}
}
validate_columns(
connection,
"resources",
RESOURCE_COLUMNS,
"v16.resources_columns",
)
.await?;
validate_columns(
connection,
"resource_versions",
version_columns(current_version),
"v16.version_columns",
)
.await?;
validate_definitions(connection, "resources", RESOURCE_DEFINITIONS).await?;
validate_definitions(connection, "resource_versions", VERSION_DEFINITIONS).await?;
validate_check_expressions(connection, "resources", RESOURCE_CHECK_EXPRESSIONS).await?;
validate_check_expressions(
connection,
"resource_versions",
&version_check_expectations(current_version),
)
.await?;
validate_current_draft_index(connection).await?;
validate_created_index(connection).await
}
/// Сверка определения constraint: `contype`, `convalidated` и **точное**
/// нормализованное `pg_get_constraintdef`.
///
/// Точное сравнение (а не вхождение ожидаемого префикса) обязательно для FK: иначе
/// дополнительные `ON DELETE`-действия и `DEFERRABLE` остаются разрешёнными
/// (TL run109 F5).
async fn validate_definitions(
connection: &mut PgConnection,
table: &str,
expectations: &[(&'static str, &'static str, &'static str, &'static str)],
) -> Result<(), MigrationError> {
for (constraint, kind, stage, expected) in expectations {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v16_error(stage));
}
}
Ok(())
}
/// Сверка CHECK-выражений (включая перечисляющие): точное каноническое определение
/// + `convalidated = true`.
///
/// `NOT VALID` сохраняет выражение, поэтому без чтения признака валидации такой дрейф
/// не наблюдается (TL run109 F5). Ожидание — полная каноническая форма PostgreSQL,
/// поэтому добавленный к перечисляющему CHECK предикат тоже виден (TL run113 EH1).
async fn validate_check_expressions(
connection: &mut PgConnection,
table: &str,
expectations: &[(&'static str, &'static str, &'static str)],
) -> Result<(), MigrationError> {
for (constraint, stage, expected) in expectations {
let (definition, convalidated) =
constraint_definition_and_validation(connection, table, constraint, stage).await?;
if !convalidated
|| normalize_v16_definition(&definition) != normalize_v16_definition(expected)
{
return Err(v16_error(stage));
}
}
Ok(())
}
/// Нормализация определения V16: пробелы и регистр снимаются только **вне** строковых
/// литералов.
///
/// Общий `normalize_definition` убирает пробелы и приводит регистр по всей строке,
/// включая содержимое литералов, поэтому `'^[0-9a-f ]{64}$'` (класс с пробелом) и
/// lowercase-вариант MIME-маски становились неотличимы от канонических выражений
/// (TL run113 EH1/EH2). Здесь значимые символы внутри литералов сохраняются, а скобки
/// и операторы вне литералов не удаляются — разные выражения не сливаются.
/// `''` внутри литерала — экранированная кавычка, а не его конец.
fn normalize_v16_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
/// Каноническое определение CHECK-constraint-а V16 и признак его валидации.
///
/// Отсутствие ожидаемого ограничения — отказ именно V16-шага (а не общий preflight
/// другой версии), поэтому stage передаётся в ошибку.
async fn constraint_definition_and_validation(
connection: &mut PgConnection,
table: &str,
constraint: &str,
stage: &'static str,
) -> Result<(String, bool), MigrationError> {
query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2
and c.contype = 'c'",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.and_then(|row| {
Some((
row.try_get::<String, _>("definition").ok()?,
row.try_get::<bool, _>("convalidated").ok()?,
))
})
.ok_or_else(|| v16_error(stage))
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
stage: &'static str,
) -> Result<(), MigrationError> {
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v16_error(stage));
}
}
Ok(())
}
async fn validate_current_draft_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column,
pg_get_expr(i.indpred, i.indrelid) as predicate
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resource_versions_current_draft_unique'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_versions")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
// У двухколоночного индекса третья позиция пуста (`""`, не NULL).
&& row
.try_get::<String, _>("third_column")
.ok()
.is_none_or(|value| value.is_empty())
&& row
.try_get::<String, _>("predicate")
.ok()
.is_some_and(|value| normalize_definition(&value) == "superseded_atisnull")
});
if valid {
Ok(())
} else {
Err(v16_error("v16.current_draft_index"))
}
}
async fn validate_created_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique, i.indnkeyatts, i.indnatts,
pg_get_expr(i.indpred, i.indrelid) as predicate,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resources_workspace_created_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resources")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
// Ровно три ключевых столбца: четвёртый (или INCLUDE-столбец) — дрейф.
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
// Частичный индекс на этом месте — тоже дрейф: предиката быть не должно.
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.is_none_or(|value| value.is_none())
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("created_at")
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_id")
});
if valid {
Ok(())
} else {
Err(v16_error("v16.created_index"))
}
}
@@ -0,0 +1,370 @@
//! V17 schema guard: typed immutable Resource publications (Story 3.7).
//!
//! Проверяет, что схема V17 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: таблица, колонки,
//! PK/FK и CHECK-выражения снимка публичных metadata плюс индекс разрешения
//! explicit `include:` цели по URI.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &[
"resource_publications",
"resource_publications_workspace_uri_idx",
];
const COLUMNS_V17: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", false),
("published_at", "timestamp with time zone", false),
];
/// V20 добавляет `source_kind` и допускает byte-less template-публикации.
const COLUMNS_V20: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", true),
("source_kind", "text", false),
("published_at", "timestamp with time zone", false),
];
fn columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
if current_version >= 20 {
COLUMNS_V20
} else {
COLUMNS_V17
}
}
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_publications_pkey",
"p",
"v17.pkey",
"primarykeyworkspace_id,resource_id,version",
),
(
"resource_publications_resource_fkey",
"f",
"v17.resource_fkey",
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
),
(
"resource_publications_version_fkey",
"f",
"v17.version_fkey",
"foreignkeyworkspace_id,resource_id,versionreferencesresource_versionsworkspace_id,resource_id,versionondeletecascade",
),
(
"resource_publications_source_fkey",
"f",
"v17.source_fkey",
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_publications_version_check",
"v17.version_check",
"CHECK (version >= 1)",
),
(
"resource_publications_uri_len_check",
"v17.uri_len_check",
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
),
(
"resource_publications_name_len_check",
"v17.name_len_check",
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
),
(
"resource_publications_description_len",
"v17.description_len",
"CHECK (octet_length(description) <= 1024)",
),
(
"resource_publications_kind_check",
"v17.kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resource_publications_mime_type_check",
"v17.mime_type_check",
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
),
(
"resource_publications_size_check",
"v17.size_check",
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
),
(
"resource_publications_digest_check",
"v17.digest_check",
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_publications_sensitivity_check",
"v17.sensitivity_check",
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
),
(
"resource_publications_source_id_check",
"v17.source_id_check",
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
),
];
/// V20 переопределяет два CHECK-а публикаций так же, как у версий.
const CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
(
"resource_publications_size_check",
"v17.size_check",
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
OR source_kind = 'template'::text AND size_bytes = 0)",
),
(
"resource_publications_source_id_check",
"v17.source_id_check",
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
),
];
fn check_expectations(current_version: i64) -> Vec<(&'static str, &'static str, &'static str)> {
CHECK_EXPRESSIONS
.iter()
.map(|(constraint, stage, legacy)| {
let expected = if current_version >= 20 {
CHECK_EXPRESSIONS_V20
.iter()
.find(|(name, _, _)| name == constraint)
.map(|(_, _, expected)| *expected)
.unwrap_or(*legacy)
} else {
*legacy
};
(*constraint, *stage, expected)
})
.collect()
}
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
/// литералов, поэтому ослабленная маска внутри литерала (`'^[0-9a-f ]{64}$'`) и
/// другой регистр в литерале не сливаются с каноническим выражением.
fn normalize_guard_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
fn v17_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(17),
"restore_known_good_backup",
)
}
/// Схема V17 отсутствует целиком (для current_version < 17).
pub(super) async fn validate_v17_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V17 присутствует в ожидаемой форме (для current_version >= 17).
pub(super) async fn validate_v17_resource_publications(
connection: &mut PgConnection,
current_version: i64,
) -> Result<(), MigrationError> {
let columns = columns(current_version);
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v17_error("v17.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_publications'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v17_error("v17.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_publications'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v17_error("v17.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'resource_publications'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v17_error(stage));
}
}
for (constraint, stage, expected) in check_expectations(current_version) {
let row = query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'resource_publications'
and c.conname = $1 and c.contype = 'c'",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_guard_definition(&definition)
== normalize_guard_definition(expected)
})
});
if !valid {
return Err(v17_error(stage));
}
}
validate_uri_index(connection).await
}
async fn validate_uri_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique, i.indnkeyatts, i.indnatts,
pg_get_expr(i.indpred, i.indrelid) as predicate,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resource_publications_workspace_uri_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_publications")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.is_none_or(|value| value.is_none())
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("uri")
&& row
.try_get::<String, _>("third_column")
.ok()
.is_some_and(|value| value == "published_at" || value == "published_at DESC")
});
if valid {
Ok(())
} else {
Err(v17_error("v17.uri_index"))
}
}
@@ -0,0 +1,333 @@
//! V18 schema guard: typed exact Resource bindings Agent (Story 3.7 AC04).
//!
//! Проверяет, что схема V18 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: отдельная таблица
//! `agent_resource_bindings`, workspace-равенство на обоих концах composite FK,
//! exact positive version, immutability trigger для published Agent Version и
//! индексы адресации.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
/// литералов, поэтому ослабленная маска (`'^[0-9a-f ]{64}$'`) не сливается с
/// каноническим выражением (тот же инвариант, что в V17 guard).
fn normalize_guard_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
const OWNED_RELATIONS: &[&str] = &[
"agent_resource_bindings",
"agent_resource_bindings_resource_idx",
"agents_workspace_id_idx",
];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("agent_id", "text", false),
("agent_version", "integer", false),
("resource_id", "text", false),
("resource_version", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"agent_resource_bindings_pkey",
"p",
"v18.pkey",
"primarykeyagent_id,agent_version,resource_id,resource_version",
),
(
"agent_resource_bindings_agent_workspace_fkey",
"f",
"v18.agent_workspace_fkey",
"foreignkeyworkspace_id,agent_idreferencesagentsworkspace_id,idondeletecascade",
),
(
"agent_resource_bindings_agent_version_fkey",
"f",
"v18.agent_version_fkey",
"foreignkeyagent_id,agent_versionreferencesagent_versionsagent_id,versionondeletecascade",
),
(
"agent_resource_bindings_publication_fkey",
"f",
"v18.publication_fkey",
"foreignkeyworkspace_id,resource_id,resource_versionreferencesresource_publicationsworkspace_id,resource_id,versionondeletecascade",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"agent_resource_bindings_agent_version_check",
"v18.agent_version_check",
"CHECK (agent_version >= 1)",
),
(
"agent_resource_bindings_resource_version_check",
"v18.resource_version_check",
"CHECK (resource_version >= 1)",
),
];
fn v18_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(18),
"restore_known_good_backup",
)
}
/// Схема V18 отсутствует целиком (для current_version < 18).
pub(super) async fn validate_v18_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if trigger_exists(connection).await? {
return Ok(false);
}
if guard_function_exists(connection).await? {
return Ok(false);
}
Ok(true)
}
/// Схема V18 присутствует в ожидаемой форме (для current_version >= 18).
pub(super) async fn validate_v18_agent_resource_bindings(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v18_error("v18.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'agent_resource_bindings'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v18_error("v18.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'agent_resource_bindings'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v18_error("v18.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v18_error(stage));
}
}
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
let row = query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
and c.conname = $1 and c.contype = 'c'",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_guard_definition(&definition)
== normalize_guard_definition(expected)
})
});
if !valid {
return Err(v18_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v18_error("v18.immutable_trigger"));
}
validate_agent_workspace_index(connection).await?;
validate_resource_index(connection).await
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'agent_resource_bindings'
and tg.tgname = 'agent_resource_bindings_immutable_guard'
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn validate_agent_workspace_index(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
i.indisready, i.indisunique, i.indnkeyatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema() and idx.relname = 'agents_workspace_id_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agents")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("id")
});
if valid {
Ok(())
} else {
Err(v18_error("v18.agents_workspace_index"))
}
}
async fn validate_resource_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
i.indisready, i.indisunique, i.indnkeyatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'agent_resource_bindings_resource_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agent_resource_bindings")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_version")
});
if valid {
Ok(())
} else {
Err(v18_error("v18.resource_index"))
}
}
@@ -0,0 +1,185 @@
//! V19 schema guard: immutable Resource security revocation tombstones (Story 3.8).
//!
//! Проверяет, что схема V19 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: одна таблица
//! `resource_security_revocations` с составным PK, FK на `resources` и `users`
//! без каскадного удаления и trigger неизменяемости. Bounded request/trace
//! значения задаются серверными типами (`RequestId`/`TraceContext`), а не
//! пользовательским вводом.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &["resource_security_revocations"];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("revoked_at", "timestamp with time zone", false),
("actor_user_id", "text", false),
("request_id", "text", false),
("trace_id", "text", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_security_revocations_pkey",
"p",
"v19.pkey",
"primary key (workspace_id, resource_id)",
),
(
"resource_security_revocations_resource_fkey",
"f",
"v19.resource_fkey",
"foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete restrict",
),
(
"resource_security_revocations_actor_fkey",
"f",
"v19.actor_fkey",
"foreign key (actor_user_id) references users(id) on delete restrict",
),
];
fn v19_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(19),
"restore_known_good_backup",
)
}
/// Схема V19 отсутствует целиком (для current_version < 19).
pub(super) async fn validate_v19_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if guard_function_exists(connection).await? {
return Ok(false);
}
Ok(!trigger_exists(connection).await?)
}
/// Схема V19 присутствует в ожидаемой форме (для current_version >= 19).
pub(super) async fn validate_v19_resource_security_revocations(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v19_error("v19.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_security_revocations'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v19_error("v19.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_security_revocations'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v19_error("v19.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'resource_security_revocations'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v19_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v19_error("v19.immutable_trigger"));
}
if !guard_function_exists(connection).await? {
return Err(v19_error("v19.immutable_trigger"));
}
Ok(())
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'resource_security_revocations'
and tg.tgname = 'resource_security_revocations_immutable_guard'
and p.proname = 'crank_reject_resource_security_revocation_mutation'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_reject_resource_security_revocation_mutation'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,293 @@
//! V20 schema guard: byte-less REST-backed Resource template sources (Story 3.10).
//!
//! Схема V20 либо полностью отсутствует (миграция ещё не применена), либо
//! присутствует ровно в ожидаемой форме: `resource_template_sources` с
//! version-keyed PK/FK на версию, insert-only trigger, а в `resource_versions` и
//! `resource_publications` — `source_kind` и CHECK-и, которые допускают byte-less
//! template-строки, сохраняя прежние ограничения artifact-строк.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &["resource_template_sources"];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("definition_json", "text", false),
("definition_digest", "text", false),
("created_at", "timestamp with time zone", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_template_sources_pkey",
"p",
"v20.pkey",
"primary key (workspace_id, resource_id, version)",
),
(
"resource_template_sources_version_fkey",
"f",
"v20.version_fkey",
"foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_template_sources_version_check",
"v20.version_check",
"CHECK (version >= 1)",
),
(
"resource_template_sources_definition_len_check",
"v20.definition_len_check",
"CHECK (octet_length(definition_json) >= 2 AND octet_length(definition_json) <= 65536)",
),
(
"resource_template_sources_digest_check",
"v20.digest_check",
"CHECK (definition_digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_versions_source_kind_check",
"v20.version_source_kind_check",
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
),
(
"resource_publications_source_kind_check",
"v20.publication_source_kind_check",
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
),
];
fn v20_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(20),
"restore_known_good_backup",
)
}
/// Схема V20 отсутствует целиком (для current_version < 20).
pub(super) async fn validate_v20_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if guard_function_exists(connection).await? {
return Ok(false);
}
if trigger_exists(connection).await? {
return Ok(false);
}
for (table, column) in [
("resource_versions", "source_kind"),
("resource_publications", "source_kind"),
] {
if column_exists(connection, table, column).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V20 присутствует в ожидаемой форме (для current_version >= 20).
pub(super) async fn validate_v20_resource_template_sources(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
if !relation_exists(connection, "resource_template_sources").await? {
return Err(v20_error("v20.relations"));
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_template_sources'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v20_error("v20.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_template_sources'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v20_error("v20.columns"));
}
}
// `source_kind` добавлен в обе существующие resource-таблицы: template-строки
// без него неотличимы от artifact-строк, поэтому его форма обязательна.
for table in ["resource_versions", "resource_publications"] {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1
and column_name = 'source_kind'",
)
.bind(table)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some("text")
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("NO")
});
if !valid {
return Err(v20_error("v20.source_kind"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(
connection,
"resource_template_sources",
constraint,
kind,
expected,
)
.await?
{
return Err(v20_error(stage));
}
}
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
let table = if constraint.starts_with("resource_template_sources") {
"resource_template_sources"
} else if constraint.starts_with("resource_versions") {
"resource_versions"
} else {
"resource_publications"
};
if !check_matches(connection, table, constraint, expected).await? {
return Err(v20_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v20_error("v20.immutable_trigger"));
}
if !guard_function_exists(connection).await? {
return Err(v20_error("v20.immutable_trigger"));
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn check_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
expected: &str,
) -> Result<bool, MigrationError> {
constraint_matches(connection, table, constraint, "c", expected).await
}
async fn column_exists(
connection: &mut PgConnection,
table: &str,
column: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2
) as present",
)
.bind(table)
.bind(column)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'resource_template_sources'
and tg.tgname = 'crank_guard_resource_template_source_immutable'
and p.proname = 'crank_guard_resource_template_source_immutable'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_guard_resource_template_source_immutable'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,299 @@
//! V22 schema guard: immutable Published Prompt Versions и typed exact Prompt
//! bindings Agent (Story 3.13, FR-17).
//!
//! Схема V22 либо полностью отсутствует (миграция ещё не применена), либо
//! присутствует ровно в ожидаемой форме: `prompt_publications` с composite PK/FK,
//! `agent_prompt_bindings` с workspace-safe FK на обоих концах, nullable
//! `prompts.latest_published_version` и guard-триггеры неизменяемости
//! опубликованной definition/публикации и bindings опубликованного Agent.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const PUBLICATION: &str = "prompt_publications";
const BINDINGS: &str = "agent_prompt_bindings";
const OWNED_RELATIONS: &[&str] = &[PUBLICATION, BINDINGS];
const PUBLICATION_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("name", "text", false),
("description", "text", false),
("sensitivity", "text", false),
("published_at", "timestamp with time zone", false),
];
const BINDING_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("agent_id", "text", false),
("agent_version", "integer", false),
("prompt_id", "text", false),
("prompt_version", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
(
PUBLICATION,
"prompt_publications_pkey",
"p",
"v22.publication_pkey",
"primary key (workspace_id, prompt_id, version)",
),
(
PUBLICATION,
"prompt_publications_prompt_fkey",
"f",
"v22.publication_prompt_fkey",
"foreign key (workspace_id, prompt_id) references prompts(workspace_id, prompt_id) on delete cascade",
),
(
PUBLICATION,
"prompt_publications_version_fkey",
"f",
"v22.publication_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_pkey",
"p",
"v22.binding_pkey",
"primary key (agent_id, agent_version, prompt_id)",
),
(
BINDINGS,
"agent_prompt_bindings_agent_workspace_fkey",
"f",
"v22.binding_agent_workspace_fkey",
"foreign key (workspace_id, agent_id) references agents(workspace_id, id) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_agent_version_fkey",
"f",
"v22.binding_agent_version_fkey",
"foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_publication_fkey",
"f",
"v22.binding_publication_fkey",
"foreign key (workspace_id, prompt_id, prompt_version)
references prompt_publications(workspace_id, prompt_id, version) on delete cascade",
),
];
const TRIGGERS: &[(&str, &str, &str)] = &[
(
"prompt_arguments",
"prompt_arguments_immutable_guard",
"crank_reject_published_prompt_version_mutation",
),
(
"prompt_messages",
"prompt_messages_immutable_guard",
"crank_reject_published_prompt_version_mutation",
),
(
PUBLICATION,
"prompt_publications_immutable_guard",
"crank_reject_prompt_publication_mutation",
),
(
BINDINGS,
"agent_prompt_bindings_immutable_guard",
"crank_reject_published_agent_prompt_binding_mutation",
),
];
fn v22_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(22),
"restore_known_good_backup",
)
}
/// Схема V22 отсутствует целиком (для current_version < 22).
pub(super) async fn validate_v22_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if super::schema_guard::column_exists(connection, "prompts", "latest_published_version").await?
{
return Ok(false);
}
for (_, _, function) in TRIGGERS {
if function_exists(connection, function).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V22 присутствует в ожидаемой форме (для current_version >= 22).
pub(super) async fn validate_v22_prompt_publications(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v22_error("v22.relations"));
}
}
if !super::schema_guard::column_exists(connection, "prompts", "latest_published_version")
.await?
{
return Err(v22_error("v22.prompt_columns"));
}
for (table, columns) in [
(PUBLICATION, PUBLICATION_COLUMNS),
(BINDINGS, BINDING_COLUMNS),
] {
validate_columns(connection, table, columns).await?;
}
for (table, constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(connection, table, constraint, kind, expected).await? {
return Err(v22_error(stage));
}
}
for (table, trigger, function) in TRIGGERS {
if !trigger_exists(connection, table, trigger, function).await? {
return Err(v22_error("v22.immutable_trigger"));
}
}
Ok(())
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
) -> Result<(), MigrationError> {
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = $1",
)
.bind(table)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v22_error("v22.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v22_error("v22.columns"));
}
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = $1
and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn trigger_exists(
connection: &mut PgConnection,
table: &str,
trigger: &str,
function: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = $1
and tg.tgname = $2
and p.proname = $3
and not tg.tgisinternal
) as present",
)
.bind(table)
.bind(trigger)
.bind(function)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn function_exists(
connection: &mut PgConnection,
function: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema() and p.proname = $1
) as present",
)
.bind(function)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,239 @@
//! V23 schema guard: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
//!
//! Схема V23 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в
//! ожидаемой форме: `prompt_dependencies` с composite PK/FK на `prompt_versions`,
//! `prompt_message_resource_refs` с упорядоченными точками вставки и guard-триггеры
//! неизменяемости опубликованной версии на обеих таблицах.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const DEPENDENCIES: &str = "prompt_dependencies";
const RESOURCE_REFS: &str = "prompt_message_resource_refs";
const GUARD_FUNCTION: &str = "crank_reject_published_prompt_version_mutation";
const OWNED_RELATIONS: &[&str] = &[DEPENDENCIES, RESOURCE_REFS];
const DEPENDENCY_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("dependency_position", "integer", false),
("resource_id", "text", false),
("resource_version", "integer", false),
("digest", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("source_class", "text", false),
("sensitivity", "text", false),
];
const REF_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("message_position", "integer", false),
("ref_position", "integer", false),
("dependency_position", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
(
DEPENDENCIES,
"prompt_dependencies_pkey",
"p",
"v23.dependencies_pkey",
"primary key (workspace_id, prompt_id, version, dependency_position)",
),
(
DEPENDENCIES,
"prompt_dependencies_version_fkey",
"f",
"v23.dependencies_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
(
RESOURCE_REFS,
"prompt_message_resource_refs_pkey",
"p",
"v23.refs_pkey",
"primary key (workspace_id, prompt_id, version, message_position, ref_position)",
),
(
RESOURCE_REFS,
"prompt_message_resource_refs_version_fkey",
"f",
"v23.refs_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
];
fn v23_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(23),
"restore_known_good_backup",
)
}
/// Схема V23 отсутствует целиком (для current_version < 23).
pub(super) async fn validate_v23_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if trigger_exists(
connection,
DEPENDENCIES,
"prompt_dependencies_immutable_guard",
)
.await?
{
return Ok(false);
}
Ok(true)
}
/// Схема V23 присутствует в ожидаемой форме (для current_version >= 23).
pub(super) async fn validate_v23_prompt_dependencies(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v23_error("v23.relations"));
}
}
for (table, columns) in [
(DEPENDENCIES, DEPENDENCY_COLUMNS),
(RESOURCE_REFS, REF_COLUMNS),
] {
validate_columns(connection, table, columns).await?;
}
for (table, constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(connection, table, constraint, kind, expected).await? {
return Err(v23_error(stage));
}
}
for (table, trigger) in [
(DEPENDENCIES, "prompt_dependencies_immutable_guard"),
(
RESOURCE_REFS,
"prompt_message_resource_refs_immutable_guard",
),
] {
if !trigger_exists(connection, table, trigger).await? {
return Err(v23_error("v23.immutable_trigger"));
}
}
Ok(())
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
) -> Result<(), MigrationError> {
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = $1",
)
.bind(table)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v23_error("v23.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v23_error("v23.columns"));
}
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = $1
and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn trigger_exists(
connection: &mut PgConnection,
table: &str,
trigger: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = $1
and tg.tgname = $2
and p.proname = $3
and not tg.tgisinternal
) as present",
)
.bind(table)
.bind(trigger)
.bind(GUARD_FUNCTION)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
+44 -155
View File
@@ -1,4 +1,5 @@
use crank_artifacts::ArtifactRef;
use crank_core::ids::{PromptId, ResourceId};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, DescriptorId, ExecutionErrorCode,
@@ -48,6 +49,14 @@ mod artifact_source;
pub use artifact_source::*;
pub mod resource;
mod prompt;
pub use prompt::*;
pub use resource::*;
mod import_plan;
pub use import_plan::*;
@@ -56,6 +65,10 @@ mod onboarding_import;
pub use onboarding_import::*;
mod usage;
pub use usage::*;
define_registry_id!(YamlImportJobId);
define_registry_id!(ImportJobId);
define_registry_id!(ImportPlanId);
@@ -243,161 +256,6 @@ pub struct WorkspaceUpstream {
pub updated_at: OffsetDateTime,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationLogRecord {
pub log: InvocationLog,
pub operation_name: String,
pub operation_display_name: String,
pub agent_slug: Option<String>,
pub agent_display_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageRollupRecord {
pub rollup: UsageRollup,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageTimelinePoint {
#[serde(with = "time::serde::rfc3339")]
pub bucket_start: OffsetDateTime,
pub calls_ok: u64,
pub calls_error: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageOperationBreakdown {
pub operation_id: OperationId,
pub operation_name: String,
pub operation_display_name: String,
pub protocol: Protocol,
pub calls_total: u64,
pub calls_error: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageAgentBreakdown {
pub agent_id: AgentId,
pub agent_slug: String,
pub agent_display_name: String,
pub calls_total: u64,
pub calls_error: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UsageOutcomeGroup {
Success,
Upstream,
Client,
Schema,
Crank,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageOutcomeBreakdown {
pub group: UsageOutcomeGroup,
pub execution_error_code: Option<ExecutionErrorCode>,
pub calls_total: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AppendProductEventOutcome {
Recorded,
Duplicate,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProductEventRecord {
pub event: ProductEvent,
}
#[derive(Clone, Debug)]
pub struct AppendProductEventRequest<'a> {
pub event: &'a ProductEvent,
}
#[derive(Clone, Debug)]
pub struct ListProductEventsQuery<'a> {
pub workspace_id: &'a WorkspaceId,
pub kind: Option<ProductEventKind>,
pub created_after: OffsetDateTime,
pub created_before: OffsetDateTime,
pub limit: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnboardingPresentationMilestone {
Eligible,
Started,
Resumed,
Dismissed,
Abandoned,
}
#[derive(Clone, Debug)]
pub struct RecordOnboardingMilestoneRequest<'a> {
pub workspace_id: &'a WorkspaceId,
pub event_id: &'a ProductEventId,
pub milestone: OnboardingPresentationMilestone,
pub idempotency_key: &'a str,
pub expected_revision: i64,
pub occurred_at: OffsetDateTime,
pub eligible_since: Option<OffsetDateTime>,
}
#[derive(Clone, Debug)]
pub struct RecordOnboardingCompletionRequest<'a> {
pub workspace_id: &'a WorkspaceId,
pub event_id: &'a ProductEventId,
pub idempotency_key: &'a str,
pub expected_revision: i64,
pub occurred_at: OffsetDateTime,
pub eligible_since: OffsetDateTime,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnboardingMilestoneResult {
pub accepted: bool,
pub projection: OnboardingProjection,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationRetentionStatus {
Noop,
Completed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationRetentionPolicy {
#[serde(with = "time::serde::rfc3339")]
pub requested_cutoff: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub effective_cutoff: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub usage_preservation_floor: OffsetDateTime,
pub preserved_usage_window_days: u16,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationRetentionOutcome {
pub status: InvocationRetentionStatus,
pub deleted_records: u64,
pub policy: InvocationRetentionPolicy,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentSummary {
pub id: AgentId,
@@ -414,6 +272,21 @@ pub struct AgentSummary {
pub published_at: Option<OffsetDateTime>,
}
/// Точная опубликованная Resource Version, закреплённая за конкретной версией
/// Agent (Story 3.7 AC04): typed binding, а не JSON-заместитель и не `latest`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentResourceBinding {
pub resource_id: ResourceId,
pub resource_version: u32,
}
/// Точная Published Prompt Version в snapshot версии Agent (Story 3.13).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentPromptBinding {
pub prompt_id: PromptId,
pub prompt_version: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentVersionRecord {
pub agent_id: AgentId,
@@ -423,6 +296,12 @@ pub struct AgentVersionRecord {
pub created_at: OffsetDateTime,
pub snapshot: AgentVersion,
pub bindings: Vec<AgentOperationBinding>,
/// Отдельный typed список exact Published Resource Versions рядом с Operation bindings.
#[serde(default)]
pub resource_bindings: Vec<AgentResourceBinding>,
/// Отдельный typed список exact Published Prompt Versions (Story 3.13).
#[serde(default)]
pub prompt_bindings: Vec<AgentPromptBinding>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -452,6 +331,14 @@ pub struct PublishedAgentCatalog {
pub catalog_revision: String,
pub tool_selection_policy: ToolSelectionPolicy,
pub tools: Vec<PublishedAgentTool>,
/// Точные Resource bindings того же `agent_version`/`catalog_revision` из той же
/// read-транзакции каталога (Story 3.7 AC04).
#[serde(default)]
pub resources: Vec<AgentResourceBinding>,
/// Точные Prompt bindings того же `agent_version`/`catalog_revision` из той же
/// read-транзакции каталога (Story 3.14).
#[serde(default)]
pub prompts: Vec<AgentPromptBinding>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -883,6 +770,8 @@ pub struct SaveAgentCatalogConfigRequest<'a> {
pub agent_version: u32,
pub bindings: &'a [AgentOperationBinding],
pub tool_selection_policy: &'a ToolSelectionPolicy,
/// Точный список Published Resource Versions для Draft-версии (Story 3.7 AC04).
pub resource_bindings: &'a [AgentResourceBinding],
pub expected_state: Option<&'a AgentStateExpectation>,
}
+67
View File
@@ -0,0 +1,67 @@
use crank_core::{
WorkspaceId,
ids::PromptId,
prompt::{PromptDefinition, PromptDraft, PromptSensitivity},
prompt_composition::PromptDependencyPin,
};
use time::OffsetDateTime;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptDraftRecord {
pub prompt: PromptDraft,
/// Точная опубликованная версия, если Prompt уже публиковался (Story 3.13).
pub latest_published_version: Option<u32>,
/// Разрешённые пины зависимостей этой версии в порядке объявления (Story 3.16).
pub dependencies: Vec<PromptDependencyPin>,
pub created_at: OffsetDateTime,
pub updated_at: OffsetDateTime,
}
/// Immutable Published Prompt Version, прочитанная по точному номеру версии.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptPublicationRecord {
pub prompt_id: PromptId,
pub version: u32,
pub name: String,
pub description: String,
pub sensitivity: PromptSensitivity,
pub definition: PromptDefinition,
/// Пины зависимостей, зафиксированные публикацией (Story 3.16).
pub dependencies: Vec<PromptDependencyPin>,
pub published_at: OffsetDateTime,
}
#[derive(Debug)]
pub struct PublishPromptRequest {
pub workspace_id: WorkspaceId,
pub prompt_id: PromptId,
pub expected_updated_at: OffsetDateTime,
pub published_at: OffsetDateTime,
}
#[derive(Debug)]
pub struct ArchivePromptRequest {
pub workspace_id: WorkspaceId,
pub prompt_id: PromptId,
pub expected_updated_at: OffsetDateTime,
pub archived_at: OffsetDateTime,
}
#[derive(Debug)]
pub struct CreatePromptDraftRequest {
pub workspace_id: WorkspaceId,
pub prompt_id: PromptId,
pub sensitivity: PromptSensitivity,
pub definition: PromptDefinition,
pub created_at: OffsetDateTime,
}
#[derive(Debug)]
pub struct UpdatePromptDraftRequest {
pub workspace_id: WorkspaceId,
pub prompt_id: PromptId,
pub sensitivity: PromptSensitivity,
pub definition: PromptDefinition,
pub expected_updated_at: OffsetDateTime,
pub updated_at: OffsetDateTime,
}
+243
View File
@@ -0,0 +1,243 @@
//! Registry-модели Story 3.6: typed static Resource Drafts (V16).
//!
//! Мутирующие запросы получают `RegisteredArtifact` — доказательство уже
//! зарегистрированных durable bytes (`ArtifactStore::put_registered`), а не сырые
//! bytes и не digest строкой: реестр получает durable metadata/owning ref и **не**
//! становится владельцем записи файла (D-15 шаг 3 `ensure_blob`).
//!
//! `resource_versions` не имеет `updated_at`: optimistic-precondition берётся из
//! `resources.updated_at`, а CAS прежней owning-ссылки — из
//! `artifact_sources.updated_at` через `get_source_in_transaction` (D-15 шаг 2).
use crank_artifacts::{ArtifactRef, RegisteredArtifact};
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::ResourceStatus;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
/// Максимальный размер страницы списка Draft-ов.
pub const MAX_RESOURCE_DRAFT_PAGE_SIZE: u32 = 100;
/// Создание Draft: одна транзакция, строгий insert без `on conflict do nothing`.
#[derive(Debug)]
pub struct CreateResourceDraftRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub sensitivity: String,
pub artifact: RegisteredArtifact,
pub created_at: OffsetDateTime,
}
/// Обновление Draft. `uri`/`name`/`kind` неизменяемы и в запросе отсутствуют (D-16).
#[derive(Debug)]
pub struct UpdateResourceDraftRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub description: String,
pub mime_type: String,
pub sensitivity: String,
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
pub expected_updated_at: OffsetDateTime,
pub artifact: RegisteredArtifact,
}
/// Строка `resources` вместе с её текущей черновой версией.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceDraftRecord {
pub resource: ResourceRecord,
pub version: ResourceVersionRecord,
}
/// Story 3.10: version-keyed определение REST-шаблона (canonical JSON + digest).
/// Отдельная таблица: у шаблона нет файла содержимого и нет фейкового blob.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceTemplateSourceRecord {
pub definition_json: String,
pub definition_digest: String,
}
/// Template Draft: карточка/версия того же снимка и её определение.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceTemplateDraftRecord {
pub snapshot: ResourceDraftRecord,
pub source: ResourceTemplateSourceRecord,
}
/// Создание template Draft: bytes отсутствуют, определение version-keyed.
#[derive(Debug)]
pub struct CreateResourceTemplateDraftRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub sensitivity: String,
pub definition_json: String,
pub definition_digest: String,
pub created_at: OffsetDateTime,
}
/// Обновление template Draft: uri/name/kind неизменяемы, определение заменяется
/// целиком новой версией (прежняя остаётся для уже опубликованного снимка).
#[derive(Debug)]
pub struct UpdateResourceTemplateDraftRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub description: String,
pub mime_type: String,
pub sensitivity: String,
pub expected_updated_at: OffsetDateTime,
pub definition_json: String,
pub definition_digest: String,
}
/// Публикация template Draft: CAS по ревизии карточки и по exact определению.
#[derive(Debug)]
pub struct PublishResourceTemplateVersionRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub expected_updated_at: OffsetDateTime,
pub expected_version: u32,
pub expected_digest: String,
pub published_at: OffsetDateTime,
}
/// Публикация текущего Draft (Story 3.7): точная CAS-ревизия карточки плюс
/// повторно проверенные version/digest/size, которые транзакция сверяет под
/// блокировкой строки Resource (TOCTOU между чтением bytes и коммитом).
/// Снимок публичных metadata строится в транзакции из заблокированных строк
/// `resources`/`resource_versions`, а не из переданного клиентом тела.
#[derive(Debug)]
pub struct PublishResourceVersionRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
pub expected_updated_at: OffsetDateTime,
pub expected_version: u32,
pub expected_digest: String,
pub expected_size_bytes: i64,
/// Уже зарегистрированные immutable bytes (`ArtifactStore::put_registered`).
pub artifact: RegisteredArtifact,
/// Момент публикации (монотонно сдвигает CAS-ревизию карточки).
pub published_at: OffsetDateTime,
}
/// Immutable Published Resource Version (V17): публичные metadata снимка.
/// Owning-ссылка на хранилище и raw upload filename сюда не входят.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourcePublicationRecord {
pub resource_id: ResourceId,
pub version: u32,
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub size_bytes: i64,
pub digest: String,
pub sensitivity: String,
/// Story 3.10: `artifact` (static) или `template` (byte-less definition).
pub source_kind: String,
pub published_at: OffsetDateTime,
}
/// Exact admitted Published template definition from the same live Resource-lock transaction.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoundResourceTemplate {
pub publication: ResourcePublicationRecord,
pub source: ResourceTemplateSourceRecord,
}
/// Точная опубликованная версия вместе с owning-ссылкой для физического чтения
/// bytes сервисом. `artifact_ref` не сериализуется и никогда не попадает в wire.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedResourcePublication {
pub publication: ResourcePublicationRecord,
pub artifact_ref: ArtifactRef,
}
/// Архив текущего Resource (Story 3.7 AC05): тот же CAS, что у PUT/publish.
/// Транзакция меняет только lifecycle/ревизию карточки; artifacts, publications и
/// Agent snapshots не затрагиваются.
#[derive(Debug)]
pub struct ArchiveResourceRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
pub expected_updated_at: OffsetDateTime,
/// Момент архивации (монотонно сдвигает CAS-ревизию карточки).
pub archived_at: OffsetDateTime,
}
/// Отзыв Resource (Story 3.8, owner decision A). Actor и корреляция берутся
/// только из серверной сессии/RequestContext, не из тела запроса. Повтор
/// существующего отзыва сохраняет первую запись и не создаёт новую.
#[derive(Clone, Debug)]
pub struct RevokeResourceRequest {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub actor_user_id: String,
pub request_id: String,
pub trace_id: String,
pub revoked_at: OffsetDateTime,
}
/// Проекция `resources`: без filesystem path, raw filename и storage ref (D-12).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceRecord {
pub resource_id: ResourceId,
pub uri: String,
pub name: String,
pub description: String,
pub status: ResourceStatus,
pub kind: String,
pub current_draft_version: u32,
/// Workspace-scoped максимум Published версий: discovery-указатель точной версии,
/// не latest-alias для bytes (`/versions/{integer}` остаётся единственным чтением).
pub latest_published_version: Option<u32>,
pub created_at: OffsetDateTime,
pub updated_at: OffsetDateTime,
}
/// Проекция `resource_versions` без owning-ссылки на хранилище.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceVersionRecord {
pub version: u32,
pub kind: String,
pub mime_type: String,
pub size_bytes: i64,
pub digest: String,
pub sensitivity: String,
/// Story 3.10: `artifact` (static) или `template` (byte-less definition).
pub source_kind: String,
pub created_at: OffsetDateTime,
pub superseded_at: Option<OffsetDateTime>,
}
impl ResourceVersionRecord {
pub fn is_current(&self) -> bool {
self.superseded_at.is_none()
}
}
/// Результат workspace-scoped разрешения версии **одним** запросом: строки
/// `resources`/`resource_versions` одного снимка и `artifact_ref` для физического
/// чтения байт сервисом (D-19: точка чтения байт — в сервисе).
///
/// Один снимок обязателен, чтобы ответ не смешивал metadata одной версии с bytes
/// другой (P3): разрешение версии происходит ровно один раз на запрос.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedResourceVersion {
/// Строки `resources` и `resource_versions` того же снимка.
pub snapshot: ResourceDraftRecord,
/// Ссылка на физические bytes этой версии.
pub artifact_ref: ArtifactRef,
}
+160
View File
@@ -0,0 +1,160 @@
//! Usage / product-event / retention DTO (вынесены из `model.rs`, чтобы файл
//! оставался в пределах rust-code-health). Публичные пути сохранены через
//! `pub use usage::*;` в родительском модуле.
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationLogRecord {
pub log: InvocationLog,
pub operation_name: String,
pub operation_display_name: String,
pub agent_slug: Option<String>,
pub agent_display_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageRollupRecord {
pub rollup: UsageRollup,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageTimelinePoint {
#[serde(with = "time::serde::rfc3339")]
pub bucket_start: OffsetDateTime,
pub calls_ok: u64,
pub calls_error: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageOperationBreakdown {
pub operation_id: OperationId,
pub operation_name: String,
pub operation_display_name: String,
pub protocol: Protocol,
pub calls_total: u64,
pub calls_error: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageAgentBreakdown {
pub agent_id: AgentId,
pub agent_slug: String,
pub agent_display_name: String,
pub calls_total: u64,
pub calls_error: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UsageOutcomeGroup {
Success,
Upstream,
Client,
Schema,
Crank,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageOutcomeBreakdown {
pub group: UsageOutcomeGroup,
pub execution_error_code: Option<ExecutionErrorCode>,
pub calls_total: u64,
pub p50_ms: u64,
pub p95_ms: u64,
pub p99_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AppendProductEventOutcome {
Recorded,
Duplicate,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProductEventRecord {
pub event: ProductEvent,
}
#[derive(Clone, Debug)]
pub struct AppendProductEventRequest<'a> {
pub event: &'a ProductEvent,
}
#[derive(Clone, Debug)]
pub struct ListProductEventsQuery<'a> {
pub workspace_id: &'a WorkspaceId,
pub kind: Option<ProductEventKind>,
pub created_after: OffsetDateTime,
pub created_before: OffsetDateTime,
pub limit: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnboardingPresentationMilestone {
Eligible,
Started,
Resumed,
Dismissed,
Abandoned,
}
#[derive(Clone, Debug)]
pub struct RecordOnboardingMilestoneRequest<'a> {
pub workspace_id: &'a WorkspaceId,
pub event_id: &'a ProductEventId,
pub milestone: OnboardingPresentationMilestone,
pub idempotency_key: &'a str,
pub expected_revision: i64,
pub occurred_at: OffsetDateTime,
pub eligible_since: Option<OffsetDateTime>,
}
#[derive(Clone, Debug)]
pub struct RecordOnboardingCompletionRequest<'a> {
pub workspace_id: &'a WorkspaceId,
pub event_id: &'a ProductEventId,
pub idempotency_key: &'a str,
pub expected_revision: i64,
pub occurred_at: OffsetDateTime,
pub eligible_since: OffsetDateTime,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnboardingMilestoneResult {
pub accepted: bool,
pub projection: OnboardingProjection,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationRetentionStatus {
Noop,
Completed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationRetentionPolicy {
#[serde(with = "time::serde::rfc3339")]
pub requested_cutoff: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub effective_cutoff: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub usage_preservation_floor: OffsetDateTime,
pub preserved_usage_window_days: u16,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationRetentionOutcome {
pub status: InvocationRetentionStatus,
pub deleted_records: u64,
pub policy: InvocationRetentionPolicy,
}
+86 -2
View File
@@ -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,
+27 -16
View File
@@ -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)?,
})
}