story 2-13-importplan-re-import: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
c562d5368d
commit
f69c36fa65
66 files changed
+11366
-686
No files matched your search
@@ -136,6 +136,40 @@ pub enum RegistryError {
|
||||
ImportJobNotFound { job_id: String },
|
||||
#[error("import job {job_id} was already applied with different parameters")]
|
||||
ImportJobAlreadyApplied { job_id: String },
|
||||
#[error("invalid import plan input for field {field}")]
|
||||
InvalidImportPlan { field: &'static str },
|
||||
#[error("import plan {plan_id} already exists with different material")]
|
||||
ImportPlanConflict { plan_id: String },
|
||||
#[error("import job {job_id} is unavailable for planning in this workspace")]
|
||||
ImportPlanJobUnavailable { job_id: String },
|
||||
#[error("import job {job_id} is in a terminal state and cannot be planned")]
|
||||
ImportPlanJobTerminal { job_id: String },
|
||||
#[error("import job {job_id} has expired and cannot be planned")]
|
||||
ImportPlanJobExpired { job_id: String },
|
||||
#[error("import plan {plan_id} was not found in this workspace")]
|
||||
ImportPlanNotFound { plan_id: String },
|
||||
#[error("import plan {plan_id} has expired or its anchor job changed; create a fresh preview")]
|
||||
ImportPlanExpired { plan_id: String },
|
||||
#[error(
|
||||
"import plan {plan_id} material is corrupt or no longer consistent; create a fresh preview"
|
||||
)]
|
||||
ImportPlanPayloadCorrupt { plan_id: String },
|
||||
#[error(
|
||||
"import plan {plan_id} no longer matches the revalidated preview; create a fresh preview"
|
||||
)]
|
||||
ImportPlanFingerprintStale { plan_id: String },
|
||||
#[error(
|
||||
"import plan idempotency key {idempotency_key} was already used with different plan material; create a fresh preview"
|
||||
)]
|
||||
ImportPlanKeyDigestConflict { idempotency_key: String },
|
||||
#[error("operation with name {name} already exists; confirm skip, rename, or new version")]
|
||||
ImportPlanNameConflict { name: String },
|
||||
#[error("operation {operation_id} changed after the plan was created; create a fresh preview")]
|
||||
ImportPlanTargetStale { operation_id: String },
|
||||
#[error(
|
||||
"import plan auth profile {auth_profile_id} is unavailable, revoked or mismatched; create a fresh preview"
|
||||
)]
|
||||
ImportPlanAuthUnavailable { auth_profile_id: String },
|
||||
#[error("unsupported enum representation for field {field}")]
|
||||
InvalidEnumRepresentation { field: &'static str },
|
||||
#[error("invalid numeric value for field {field}: {value}")]
|
||||
|
||||
@@ -21,40 +21,44 @@ pub mod records {
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord,
|
||||
ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind, DescriptorMetadata, ImportJob,
|
||||
ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, InvitationRecord, InvocationHistoryLoss,
|
||||
InvocationHistoryLossCategory, InvocationHistoryWriteOutcome, InvocationLogRecord,
|
||||
InvocationRetentionOutcome, InvocationRetentionPolicy, InvocationRetentionStatus,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus,
|
||||
MembershipRecord, OnboardingMilestoneResult, OnboardingPresentationMilestone,
|
||||
OperationAgentRef, OperationSampleMetadata, OperationSummary, OperationUsageSummary,
|
||||
OperationVersionRecord, Page, PlatformApiKeyRecord, ProductEventRecord,
|
||||
PublishedAgentCatalog, PublishedAgentTool, RegistryOperation, SampleKind, SecretRecord,
|
||||
SecretVersionRecord, SessionRecord, SkippedImportOperation, UsageAgentBreakdown,
|
||||
UsageBucket, UsageOperationBreakdown, UsageOutcomeBreakdown, UsageOutcomeGroup,
|
||||
UsageRollupRecord, UsageSummary, UsageTimelinePoint, VerifiedArtifactSource,
|
||||
WorkspaceMembershipRecord, WorkspaceRecord, WorkspaceUpstream, WorkspaceUpstreamId,
|
||||
YamlImportJob, YamlImportJobCompletion, YamlImportJobId, YamlImportJobStatus,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
|
||||
ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef,
|
||||
ImportPlanId, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, MasterKeyIdentityRecord,
|
||||
MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
||||
OnboardingMilestoneResult, OnboardingPresentationMilestone, OperationAgentRef,
|
||||
OperationSampleMetadata, OperationSummary, OperationUsageSummary, OperationVersionRecord,
|
||||
Page, PlatformApiKeyRecord, ProductEventRecord, PublishedAgentCatalog, PublishedAgentTool,
|
||||
RegistryOperation, SampleKind, SecretRecord, SecretVersionRecord, SessionRecord,
|
||||
SkippedImportOperation, UsageAgentBreakdown, UsageBucket, UsageOperationBreakdown,
|
||||
UsageOutcomeBreakdown, UsageOutcomeGroup, UsageRollupRecord, UsageSummary,
|
||||
UsageTimelinePoint, VerifiedArtifactSource, WorkspaceMembershipRecord, WorkspaceRecord,
|
||||
WorkspaceUpstream, WorkspaceUpstreamId, YamlImportJob, YamlImportJobCompletion,
|
||||
YamlImportJobId, YamlImportJobStatus,
|
||||
};
|
||||
}
|
||||
|
||||
pub mod requests {
|
||||
pub use crate::model::{
|
||||
AdminSecurityAuditRequest, AppendProductEventRequest, ApplyImportJobRequest,
|
||||
ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
|
||||
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateInvitationRequest,
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DetachArtifactSourceRequest, ExpireApprovalRequest,
|
||||
FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode, ImportJobSourceEnvelope,
|
||||
ImportOperationDraft, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
||||
PublishAgentRequest, PublishRequest, RecordOnboardingCompletionRequest,
|
||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RotateSecretRequest,
|
||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
||||
UpdateAgentSummaryRequest, UpdateWorkspaceRequest, UsageQuery,
|
||||
ApplyImportPlanRequest, ClaimArtifactReconciliationRequest,
|
||||
ClaimExpiredArtifactReconciliationRequest, ConsumeAdminBootstrapContractRequest,
|
||||
CreateAdminBootstrapContractRequest, CreateAgentDraftVersionRequest, CreateAgentRequest,
|
||||
CreateApprovalRequest, CreateArtifactSourceRequest, CreateImportJobRequest,
|
||||
CreateImportPlanRequest, CreateInvitationRequest, CreateInvocationLogRequest,
|
||||
CreatePlatformApiKeyRequest, CreateSecretRequest, CreateVersionRequest,
|
||||
CreateWorkspaceRequest, CreateYamlImportJobRequest, DecideApprovalRequest,
|
||||
DetachArtifactSourceRequest, ExpireApprovalRequest, FinishApprovalRequest,
|
||||
FinishImportJobRequest, ImportConflictMode, ImportJobSourceEnvelope, ImportOperationDraft,
|
||||
ListApprovalRequestsQuery, ListArtifactSourcesQuery, ListInvocationLogsQuery,
|
||||
ListProductEventsQuery, MasterKeyIdentityCandidate, PublishAgentRequest, PublishRequest,
|
||||
RecordOnboardingCompletionRequest, RecordOnboardingMilestoneRequest,
|
||||
RecoverAdminPasswordRequest, RotateSecretRequest, SaveAgentBindingsRequest,
|
||||
SaveAgentCatalogConfigRequest, SaveAuthProfileRequest, SaveDescriptorMetadataRequest,
|
||||
SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest, UpdateAgentSummaryRequest,
|
||||
UpdateWorkspaceRequest, UsageQuery,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -70,31 +74,35 @@ pub mod infrastructure {
|
||||
pub use model::{
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentStateExpectation, AgentSummary,
|
||||
AgentVersionRecord, AppendProductEventOutcome, AppendProductEventRequest,
|
||||
AppliedImportOperation, ApplyImportJobRequest, ApprovalRequestRecord, ArtifactBlobLifecycle,
|
||||
ArtifactBlobRecord, ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome,
|
||||
ArtifactClaimOutcome, ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest,
|
||||
ArtifactExpiredClaimProbe, ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord, ArtifactSourceSensitivity,
|
||||
AuthUserRecord, ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
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, CreateInvitationRequest,
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
CreateInvitationRequest, CreateInvocationLogRequest, CreatePlatformApiKeyRequest,
|
||||
CreateSecretRequest, CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DescriptorKind, DescriptorMetadata, DetachArtifactSourceRequest,
|
||||
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode,
|
||||
ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, InvitationRecord,
|
||||
InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome,
|
||||
InvocationLogRecord, InvocationRetentionOutcome, InvocationRetentionPolicy,
|
||||
InvocationRetentionStatus, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MASTER_KEY_CIPHER_CONTRACT,
|
||||
MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE, MasterKeyIdentityCandidate,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
||||
OnboardingMilestoneResult, OnboardingPresentationMilestone, OperationAgentRef,
|
||||
OperationSampleMetadata, OperationStateExpectation, OperationSummary, OperationUsageSummary,
|
||||
OperationVersionRecord, Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest,
|
||||
PublishRequest, PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, ImportPlan,
|
||||
ImportPlanApplication, ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef, ImportPlanId,
|
||||
InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||
MASTER_KEY_CIPHER_CONTRACT, MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE,
|
||||
MasterKeyIdentityCandidate, MasterKeyIdentityRecord, MasterKeyRotationRecord,
|
||||
MasterKeyRotationStatus, MembershipRecord, OnboardingMilestoneResult,
|
||||
OnboardingPresentationMilestone, OperationAgentRef, OperationSampleMetadata,
|
||||
OperationStateExpectation, OperationSummary, OperationUsageSummary, OperationVersionRecord,
|
||||
Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest, PublishRequest,
|
||||
PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RegistryOperation,
|
||||
RotateSecretRequest, SampleKind, SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest,
|
||||
SaveAuthProfileRequest, SaveDescriptorMetadataRequest, SaveSampleMetadataRequest,
|
||||
|
||||
@@ -6,6 +6,7 @@ mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod execution_outcome_v5;
|
||||
mod import_plan_v14;
|
||||
mod master_key_identity_v7;
|
||||
mod onboarding_product_events_v11;
|
||||
mod owned_relations;
|
||||
@@ -16,6 +17,7 @@ mod schema_guard_v10;
|
||||
mod schema_guard_v11;
|
||||
mod schema_guard_v12;
|
||||
mod schema_guard_v13;
|
||||
mod schema_guard_v14;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
use super::execution_outcome_v5;
|
||||
use super::import_plan_v14;
|
||||
use super::master_key_identity_v7;
|
||||
use super::onboarding_product_events_v11;
|
||||
use super::owned_relations;
|
||||
@@ -25,8 +26,8 @@ mod contract;
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 13;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
|
||||
const CURRENT_VERSION: i64 = 14;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
|
||||
@@ -264,6 +265,7 @@ impl MigrationAuthority {
|
||||
artifact_cleanup_indexes_v13::SOURCE_SHA256,
|
||||
12,
|
||||
),
|
||||
expand_descriptor(14, "import-plan-v14", import_plan_v14::SOURCE_SHA256, 13),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -392,6 +394,9 @@ impl MigrationAuthority {
|
||||
if from < 13 {
|
||||
artifact_cleanup_indexes_v13::apply(&mut transaction, &Self::sequence()[12]).await?;
|
||||
}
|
||||
if from < 14 {
|
||||
import_plan_v14::apply(&mut transaction, &Self::sequence()[13]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
@@ -558,6 +563,8 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
|
||||
@@ -130,6 +130,7 @@ pub(super) fn validate_descriptors(
|
||||
!= artifact_metadata_v12::SOURCE_SHA256
|
||||
|| sha256_hex(artifact_cleanup_indexes_v13::SOURCE.as_bytes())
|
||||
!= artifact_cleanup_indexes_v13::SOURCE_SHA256
|
||||
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"invalid_contract",
|
||||
|
||||
@@ -8,7 +8,7 @@ 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]
|
||||
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
|
||||
);
|
||||
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
|
||||
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const SOURCE: &str = include_str!("import_plan_v14.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"176c5b3cd12ddaf78dd0d312626a0c387f9c240a765194b34e88f7e0d3b4ca2a";
|
||||
|
||||
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.import_plan",
|
||||
Some(14),
|
||||
"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(14),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
-- Import plan re-import: an immutable plan snapshot bound to the source import
|
||||
-- job, plus immutable application evidence. Both are workspace-scoped and
|
||||
-- append-only; UPDATE is rejected. Retention semantics: a plan never outlives
|
||||
-- its job, so deleting the job cascades to the plan. Application rows
|
||||
-- deliberately carry no FK to the plan: they keep
|
||||
-- (workspace_id, idempotency_key, plan_digest) as replay evidence after the
|
||||
-- job and plan have been cleaned up, and their `plan_id` is a history string.
|
||||
-- No payload/report byte bounds here: the registry/service contract enforces
|
||||
-- them.
|
||||
|
||||
alter table import_jobs
|
||||
add constraint import_jobs_workspace_id_unique
|
||||
unique (workspace_id, id);
|
||||
|
||||
create table import_plans (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
id text not null,
|
||||
job_id text not null,
|
||||
digest text not null,
|
||||
payload jsonb not null,
|
||||
created_at timestamptz not null,
|
||||
expires_at timestamptz not null,
|
||||
constraint import_plans_digest_check check (digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint import_plans_payload_check check (jsonb_typeof(payload) = 'object'),
|
||||
constraint import_plans_expires_check check (expires_at > created_at),
|
||||
constraint import_plans_job_fk
|
||||
foreign key (workspace_id, job_id)
|
||||
references import_jobs(workspace_id, id)
|
||||
on delete cascade,
|
||||
primary key (workspace_id, id)
|
||||
);
|
||||
|
||||
create table import_plan_applications (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
idempotency_key text not null,
|
||||
plan_id text not null,
|
||||
plan_digest text not null,
|
||||
report jsonb not null,
|
||||
created_at timestamptz not null,
|
||||
constraint import_plan_applications_plan_digest_check
|
||||
check (plan_digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint import_plan_applications_report_check
|
||||
check (jsonb_typeof(report) = 'object'),
|
||||
primary key (workspace_id, idempotency_key)
|
||||
);
|
||||
|
||||
create index import_plans_workspace_job_idx
|
||||
on import_plans(workspace_id, job_id);
|
||||
|
||||
create index import_plan_applications_workspace_plan_idx
|
||||
on import_plan_applications(workspace_id, plan_id);
|
||||
|
||||
create function crank_reject_import_plan_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
begin
|
||||
raise exception 'import plan rows are immutable' using errcode = '23514';
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger import_plans_immutable_guard
|
||||
before update on import_plans
|
||||
for each row execute function crank_reject_import_plan_mutation();
|
||||
|
||||
create trigger import_plan_applications_immutable_guard
|
||||
before update on import_plan_applications
|
||||
for each row execute function crank_reject_import_plan_mutation();
|
||||
@@ -33,6 +33,8 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
|
||||
|
||||
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
|
||||
|
||||
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
|
||||
|
||||
pub(super) const CONSOLIDATION: &[&str] = &[
|
||||
"__crank_migrations",
|
||||
"__crank_migration_legacy_audit",
|
||||
|
||||
@@ -37,6 +37,8 @@ pub(super) const OWNED_RELATIONS: &[&str] = &[
|
||||
"usage_rollups",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
"import_plans",
|
||||
"import_plan_applications",
|
||||
];
|
||||
|
||||
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
|
||||
@@ -645,6 +647,13 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
} else {
|
||||
super::schema_guard_v13::validate_v13_artifact_cleanup_indexes(connection).await?;
|
||||
}
|
||||
if current_version < 14 {
|
||||
if !super::schema_guard_v14::validate_v14_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v14::validate_v14_import_plan(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::schema_error;
|
||||
|
||||
const PLAN_COLUMNS: &[(&str, &str, bool, Option<&str>)] = &[
|
||||
("workspace_id", "text", false, None),
|
||||
("id", "text", false, None),
|
||||
("job_id", "text", false, None),
|
||||
("digest", "text", false, None),
|
||||
("payload", "jsonb", false, None),
|
||||
("created_at", "timestamp with time zone", false, None),
|
||||
("expires_at", "timestamp with time zone", false, None),
|
||||
];
|
||||
|
||||
const APPLICATION_COLUMNS: &[(&str, &str, bool, Option<&str>)] = &[
|
||||
("workspace_id", "text", false, None),
|
||||
("idempotency_key", "text", false, None),
|
||||
("plan_id", "text", false, None),
|
||||
("plan_digest", "text", false, None),
|
||||
("report", "jsonb", false, None),
|
||||
("created_at", "timestamp with time zone", false, None),
|
||||
];
|
||||
|
||||
const PLAN_CONSTRAINTS: &[(&str, &str, &str)] = &[
|
||||
("import_plans_pkey", "p", "PRIMARY KEY (workspace_id, id)"),
|
||||
(
|
||||
"import_plans_job_fk",
|
||||
"f",
|
||||
"FOREIGN KEY (workspace_id, job_id) REFERENCES import_jobs (workspace_id, id) ON DELETE CASCADE",
|
||||
),
|
||||
(
|
||||
"import_plans_workspace_id_fkey",
|
||||
"f",
|
||||
"FOREIGN KEY (workspace_id) REFERENCES workspaces (id) ON DELETE CASCADE",
|
||||
),
|
||||
(
|
||||
"import_plans_digest_check",
|
||||
"c",
|
||||
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
|
||||
),
|
||||
(
|
||||
"import_plans_payload_check",
|
||||
"c",
|
||||
"CHECK (jsonb_typeof(payload) = 'object'::text)",
|
||||
),
|
||||
(
|
||||
"import_plans_expires_check",
|
||||
"c",
|
||||
"CHECK (expires_at > created_at)",
|
||||
),
|
||||
];
|
||||
|
||||
const APPLICATION_CONSTRAINTS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"import_plan_applications_pkey",
|
||||
"p",
|
||||
"PRIMARY KEY (workspace_id, idempotency_key)",
|
||||
),
|
||||
(
|
||||
"import_plan_applications_workspace_id_fkey",
|
||||
"f",
|
||||
"FOREIGN KEY (workspace_id) REFERENCES workspaces (id) ON DELETE CASCADE",
|
||||
),
|
||||
(
|
||||
"import_plan_applications_plan_digest_check",
|
||||
"c",
|
||||
"CHECK (plan_digest ~ '^[0-9a-f]{64}$'::text)",
|
||||
),
|
||||
(
|
||||
"import_plan_applications_report_check",
|
||||
"c",
|
||||
"CHECK (jsonb_typeof(report) = 'object'::text)",
|
||||
),
|
||||
];
|
||||
|
||||
pub(super) async fn validate_v14_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
let mut absent = true;
|
||||
for table in ["import_plans", "import_plan_applications"] {
|
||||
if relation_exists(connection, table).await? {
|
||||
absent = false;
|
||||
}
|
||||
}
|
||||
if absent
|
||||
&& query(
|
||||
"select exists (
|
||||
select 1 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 = 'import_jobs'
|
||||
and c.conname = 'import_jobs_workspace_id_unique'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
{
|
||||
absent = false;
|
||||
}
|
||||
if absent && function_exists(connection, "crank_reject_import_plan_mutation").await? {
|
||||
absent = false;
|
||||
}
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v14_import_plan(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
validate_table_properties(connection).await?;
|
||||
validate_columns(connection, "import_plans", PLAN_COLUMNS).await?;
|
||||
validate_columns(connection, "import_plan_applications", APPLICATION_COLUMNS).await?;
|
||||
validate_constraints(connection, "import_plans", PLAN_CONSTRAINTS).await?;
|
||||
validate_constraints(
|
||||
connection,
|
||||
"import_plan_applications",
|
||||
APPLICATION_CONSTRAINTS,
|
||||
)
|
||||
.await?;
|
||||
validate_jobs_unique(connection).await?;
|
||||
validate_deferred_flags(connection).await?;
|
||||
validate_indexes(connection).await?;
|
||||
validate_immutable_guards(connection).await
|
||||
}
|
||||
|
||||
async fn validate_table_properties(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select c.relname, c.relpersistence::text as persistence,
|
||||
c.relrowsecurity, c.relforcerowsecurity, c.reloptions
|
||||
from pg_catalog.pg_class c
|
||||
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and c.relname in ('import_plans', 'import_plan_applications')
|
||||
order by c.relname",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = rows.len() == 2
|
||||
&& rows.iter().all(|row| {
|
||||
row.try_get::<String, _>("persistence").ok().as_deref() == Some("p")
|
||||
&& row.try_get::<bool, _>("relrowsecurity").ok() == Some(false)
|
||||
&& row.try_get::<bool, _>("relforcerowsecurity").ok() == Some(false)
|
||||
&& row
|
||||
.try_get::<Option<Vec<String>>, _>("reloptions")
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_none()
|
||||
});
|
||||
if valid { Ok(()) } else { Err(schema_error(14)) }
|
||||
}
|
||||
|
||||
async fn validate_columns(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
expected: &[(&str, &str, bool, Option<&str>)],
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select column_name, data_type, is_nullable, column_default,
|
||||
datetime_precision, collation_name
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
order by ordinal_position",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if rows.len() != expected.len() {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
for (row, (name, data_type, nullable, default)) in rows.iter().zip(expected) {
|
||||
let actual_default = row
|
||||
.try_get::<Option<String>, _>("column_default")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let datetime_precision = row
|
||||
.try_get::<Option<i32>, _>("datetime_precision")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let collation = row
|
||||
.try_get::<Option<String>, _>("collation_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if row.try_get::<String, _>("column_name").ok().as_deref() != Some(*name)
|
||||
|| 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" })
|
||||
|| actual_default.as_deref() != *default
|
||||
|| (data_type == &"timestamp with time zone" && datetime_precision != Some(6))
|
||||
|| collation.is_some()
|
||||
{
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_constraints(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
expected: &[(&str, &str, &str)],
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select c.conname, c.contype::text as contype, 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
|
||||
order by c.conname",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if rows.len() != expected.len() {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
for row in rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("conname")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let kind = row
|
||||
.try_get::<String, _>("contype")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let definition = row
|
||||
.try_get::<String, _>("definition")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let Some((_, _, expected_definition)) =
|
||||
expected.iter().find(|(expected_name, expected_kind, _)| {
|
||||
name == *expected_name && kind == *expected_kind
|
||||
})
|
||||
else {
|
||||
return Err(schema_error(14));
|
||||
};
|
||||
if canonical_definition(&definition) != canonical_definition(expected_definition) {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_deferred_flags(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
for (deferrable, deferred, constraint) in [
|
||||
(false, false, "import_plans_job_fk"),
|
||||
(false, false, "import_plans_workspace_id_fkey"),
|
||||
(false, false, "import_plan_applications_workspace_id_fkey"),
|
||||
] {
|
||||
let row = query(
|
||||
"select c.conname, c.condeferrable, c.condeferred
|
||||
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 c.conname = $1 and c.contype = 'f'",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<bool, _>("condeferrable").ok() == Some(deferrable)
|
||||
&& row.try_get::<bool, _>("condeferred").ok() == Some(deferred)
|
||||
});
|
||||
if !valid {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_jobs_unique(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select c.conname, 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 = 'import_jobs'
|
||||
and c.conname = 'import_jobs_workspace_id_unique'
|
||||
and c.contype = 'u'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.as_deref()
|
||||
.is_some_and(|definition| {
|
||||
canonical_definition(definition)
|
||||
== canonical_definition("UNIQUE (workspace_id, id)")
|
||||
})
|
||||
});
|
||||
if valid { Ok(()) } else { Err(schema_error(14)) }
|
||||
}
|
||||
|
||||
async fn validate_indexes(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
struct IndexContract {
|
||||
name: &'static str,
|
||||
table: &'static str,
|
||||
unique: bool,
|
||||
columns: &'static [&'static str],
|
||||
}
|
||||
const CONTRACTS: &[IndexContract] = &[
|
||||
IndexContract {
|
||||
name: "import_plans_workspace_job_idx",
|
||||
table: "import_plans",
|
||||
unique: false,
|
||||
columns: &["workspace_id", "job_id"],
|
||||
},
|
||||
IndexContract {
|
||||
name: "import_plan_applications_workspace_plan_idx",
|
||||
table: "import_plan_applications",
|
||||
unique: false,
|
||||
columns: &["workspace_id", "plan_id"],
|
||||
},
|
||||
IndexContract {
|
||||
name: "import_jobs_workspace_id_unique",
|
||||
table: "import_jobs",
|
||||
unique: true,
|
||||
columns: &["workspace_id", "id"],
|
||||
},
|
||||
IndexContract {
|
||||
name: "import_plans_pkey",
|
||||
table: "import_plans",
|
||||
unique: true,
|
||||
columns: &["workspace_id", "id"],
|
||||
},
|
||||
IndexContract {
|
||||
name: "import_plan_applications_pkey",
|
||||
table: "import_plan_applications",
|
||||
unique: true,
|
||||
columns: &["workspace_id", "idempotency_key"],
|
||||
},
|
||||
];
|
||||
for contract in CONTRACTS {
|
||||
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_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_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 = $1",
|
||||
)
|
||||
.bind(contract.name)
|
||||
.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(contract.table)
|
||||
&& 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(contract.unique)
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
|
||||
&& row.try_get::<i16, _>("indnatts").ok() == Some(2)
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref()
|
||||
== Some(contract.columns[0])
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref()
|
||||
== Some(contract.columns[1])
|
||||
&& row
|
||||
.try_get::<Option<String>, _>("predicate")
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_none()
|
||||
});
|
||||
if !valid {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_immutable_guards(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select tg.tgname, t.relname as table_name, tg.tgtype::int as tgtype,
|
||||
tg.tgenabled::text as tgenabled, tg.tgisinternal,
|
||||
pg_get_triggerdef(tg.oid, true) as definition
|
||||
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
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('import_plans', 'import_plan_applications')
|
||||
and not tg.tgisinternal
|
||||
order by tg.tgname",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let contracts = [
|
||||
("import_plans_immutable_guard", "import_plans"),
|
||||
(
|
||||
"import_plan_applications_immutable_guard",
|
||||
"import_plan_applications",
|
||||
),
|
||||
];
|
||||
let mut seen = [false; 2];
|
||||
for row in &rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("tgname")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let table = row
|
||||
.try_get::<String, _>("table_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let tgtype = row
|
||||
.try_get::<i32, _>("tgtype")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let enabled = row
|
||||
.try_get::<String, _>("tgenabled")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let internal = row
|
||||
.try_get::<bool, _>("tgisinternal")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let definition = row
|
||||
.try_get::<String, _>("definition")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let index = contracts
|
||||
.iter()
|
||||
.position(|(expected_name, expected_table)| {
|
||||
name == *expected_name && table == *expected_table
|
||||
})
|
||||
.ok_or_else(|| schema_error(14))?;
|
||||
let before_update_row = (tgtype & 1) != 0 && (tgtype & 2) != 0 && (tgtype & 16) != 0;
|
||||
let calls_guard = definition
|
||||
.to_lowercase()
|
||||
.contains("execute function crank_reject_import_plan_mutation()");
|
||||
if !(before_update_row && enabled == "O" && !internal && calls_guard) {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
seen[index] = true;
|
||||
}
|
||||
if !seen.iter().all(|present| *present) {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
if !function_exists(connection, "crank_reject_import_plan_mutation").await? {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
let policy_count = sqlx::query_scalar::<_, i64>(
|
||||
"select
|
||||
(select count(*) from pg_catalog.pg_policy p
|
||||
join pg_catalog.pg_class t on t.oid = p.polrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('import_plans', 'import_plan_applications'))",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if policy_count != 0 {
|
||||
return Err(schema_error(14));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonical_definition(value: &str) -> String {
|
||||
let mut quoted = false;
|
||||
value
|
||||
.chars()
|
||||
.filter_map(|character| {
|
||||
if character == '\'' {
|
||||
quoted = !quoted;
|
||||
return Some(character);
|
||||
}
|
||||
if character.is_ascii_whitespace() {
|
||||
None
|
||||
} else if quoted {
|
||||
Some(character)
|
||||
} else {
|
||||
Some(character.to_ascii_lowercase())
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn relation_exists(
|
||||
connection: &mut PgConnection,
|
||||
relation: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query("select to_regclass(format('%I.%I', current_schema(), $1))::text is not null as present")
|
||||
.bind(relation)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.inventory"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.inventory"))
|
||||
}
|
||||
|
||||
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
|
||||
and p.pronargs = 0
|
||||
and p.prokind = 'f'
|
||||
) 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"))
|
||||
}
|
||||
@@ -48,8 +48,13 @@ mod artifact_source;
|
||||
|
||||
pub use artifact_source::*;
|
||||
|
||||
mod import_plan;
|
||||
|
||||
pub use import_plan::*;
|
||||
|
||||
define_registry_id!(YamlImportJobId);
|
||||
define_registry_id!(ImportJobId);
|
||||
define_registry_id!(ImportPlanId);
|
||||
define_registry_id!(WorkspaceUpstreamId);
|
||||
|
||||
pub type RegistryOperation = Operation<Schema, MappingSet>;
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
use super::*;
|
||||
|
||||
/// A server-authored, immutable OpenAPI import plan.
|
||||
///
|
||||
/// The `digest` is not supplied by callers: the registry derives it from the
|
||||
/// deterministic byte encoding of `payload` at creation time, so a replay can
|
||||
/// be recognized as byte-identical material versus a changed conflict.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImportPlan {
|
||||
pub id: ImportPlanId,
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub job_id: ImportJobId,
|
||||
pub digest: String,
|
||||
pub payload: Value,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub created_at: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub expires_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Request to persist a new immutable import plan.
|
||||
///
|
||||
/// There is deliberately no `digest` field: the registry computes it from the
|
||||
/// server-authored `payload`, so client-supplied digests can never bind.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CreateImportPlanRequest<'a> {
|
||||
pub id: &'a ImportPlanId,
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub job_id: &'a ImportJobId,
|
||||
pub payload: &'a Value,
|
||||
pub created_at: &'a OffsetDateTime,
|
||||
pub expires_at: &'a OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Applies a stored, immutable import plan atomically.
|
||||
///
|
||||
/// The registry loads and revalidates the plan itself: client candidate
|
||||
/// material is never accepted. The request carries only the plan reference,
|
||||
/// the caller-confirmed plan digest, a bounded idempotency key and the
|
||||
/// service-recomputed preview fingerprint. A replay of a committed
|
||||
/// `(workspace, idempotency_key, plan_digest)` triple returns the stored
|
||||
/// immutable report even after the plan and its job have been cleaned up.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ApplyImportPlanRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub plan_id: &'a ImportPlanId,
|
||||
/// Caller-confirmed digest of the immutable plan payload (64 lowercase
|
||||
/// hex). Replays must match the digest stored with the key; a different
|
||||
/// digest under an already-used key is a typed conflict.
|
||||
pub plan_digest: &'a str,
|
||||
/// Bounded idempotency key identifying this logical apply.
|
||||
pub idempotency_key: &'a str,
|
||||
/// Preview fingerprint recomputed by the service from the revalidated
|
||||
/// source/dependencies (importer/projection/preview digests). For new
|
||||
/// attempts the registry compares it against the immutable plan
|
||||
/// fingerprint inside the apply transaction: a mismatch is a typed
|
||||
/// re-preview conflict. Committed replays skip this comparison.
|
||||
pub verified_fingerprint: &'a Value,
|
||||
pub applied_at: &'a OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Stored application evidence for a scoped idempotency key: the plan
|
||||
/// digest the apply was committed under plus the immutable report. The row
|
||||
/// outlives the plan and its job, so Admin can return committed replays
|
||||
/// (or detect a changed-digest conflict) before the plan/job can be looked
|
||||
/// up at all.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImportPlanApplication {
|
||||
pub plan_digest: String,
|
||||
pub result: ApplyImportPlanResult,
|
||||
}
|
||||
|
||||
/// Result of one `apply_import_plan` call.
|
||||
///
|
||||
/// `replayed` is a separate transport marker: the stored immutable report
|
||||
/// is returned byte-for-byte on replay and never mutated.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ApplyImportPlanResult {
|
||||
/// True when the report came from committed replay evidence instead of
|
||||
/// being produced by this call.
|
||||
pub replayed: bool,
|
||||
pub report: ImportPlanApplyReport,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ImportPlanApplyStatus {
|
||||
Applied,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
/// Per-candidate outcome vocabulary of an import plan apply report.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ImportPlanCandidateOutcome {
|
||||
Created,
|
||||
Versioned,
|
||||
Renamed,
|
||||
Skipped,
|
||||
Excluded,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ImportPlanCandidateReport {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub outcome: ImportPlanCandidateOutcome,
|
||||
/// Authoritative target identifier for `renamed` (new operation),
|
||||
/// `versioned` (targeted operation) and `skipped`/`rejected` (exact
|
||||
/// authorized target, when the plan carried one).
|
||||
pub operation_id: Option<String>,
|
||||
/// Draft version produced by `created`/`versioned`/`renamed`.
|
||||
pub version: Option<u32>,
|
||||
/// Bounded redacted machine reason (for example `not_selected`, the
|
||||
/// blocked-candidate finding code, `operation_name_conflict`).
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The immutable, redacted machine view of one import plan apply.
|
||||
///
|
||||
/// Contains only digests, identifiers, names and reasons — never credentials
|
||||
/// (secret material lives in the secrets table and is only referenced here
|
||||
/// through bounded id strings). Successful applies persist this exact
|
||||
/// object as the replay evidence; rejected applies return it without
|
||||
/// persisting, so it is always readable in the Admin/UI response.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImportPlanApplyReport {
|
||||
pub schema_version: String,
|
||||
pub status: ImportPlanApplyStatus,
|
||||
pub plan_id: String,
|
||||
pub plan_digest: String,
|
||||
pub job_id: String,
|
||||
pub idempotency_key: String,
|
||||
pub source_id: String,
|
||||
pub source_digest: String,
|
||||
pub dependencies: Vec<ImportPlanDependencyRef>,
|
||||
pub counts: ImportPlanApplyCounts,
|
||||
pub outcomes: Vec<ImportPlanCandidateReport>,
|
||||
/// Bounded human summary (RU) derived from the machine fields.
|
||||
pub summary: String,
|
||||
/// Stable recovery guidance: `none`, `repreview_required` or
|
||||
/// `confirm_skip_rename_or_new_version`.
|
||||
pub recovery: String,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub applied_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ImportPlanApplyCounts {
|
||||
pub created: u32,
|
||||
pub versioned: u32,
|
||||
pub renamed: u32,
|
||||
pub skipped: u32,
|
||||
pub excluded: u32,
|
||||
pub rejected: u32,
|
||||
}
|
||||
|
||||
/// Bounded verified-source digest reference carried by an apply report.
|
||||
/// Plain strings keep the report serializable without reusing artifact
|
||||
/// internals; the registry populates it from the immutable plan material.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ImportPlanDependencyRef {
|
||||
pub source_id: String,
|
||||
pub digest: String,
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
mod plan_apply;
|
||||
|
||||
use super::*;
|
||||
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
||||
use crate::{
|
||||
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope, ImportPlan,
|
||||
ImportPlanId,
|
||||
};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::Executor;
|
||||
|
||||
const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||
const MAX_IMPORT_JOB_DOCUMENTS: usize = 32;
|
||||
const MAX_IMPORT_PLAN_ID_BYTES: usize = 128;
|
||||
const MAX_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const DANGLING_OPENAPI_SOURCE_GRACE: time::Duration = time::Duration::minutes(5);
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -79,6 +88,186 @@ impl PostgresRegistry {
|
||||
row.as_ref().map(map_import_job).transpose()
|
||||
}
|
||||
|
||||
/// Persists a new server-authored, immutable OpenAPI import plan.
|
||||
///
|
||||
/// The `digest` is derived by the registry from a deterministic byte
|
||||
/// encoding of `payload`; callers cannot bind one. Creation is validated
|
||||
/// against a workspace-owned, non-expired, non-terminal OpenAPI job that
|
||||
/// still carries a verifiable source envelope, and the plan's lifetime
|
||||
/// must not outlive the job's. Repeating the request with the same id and
|
||||
/// byte-identical material returns the existing plan; the same id with
|
||||
/// different material/job/expiry is a typed conflict (no UPDATE).
|
||||
///
|
||||
/// Concurrency is serialized under the job row lock, then the workspace
|
||||
/// row lock — the same lock order as the legacy Apply path (job ->
|
||||
/// workspace). The authoritative existence re-check under the workspace
|
||||
/// lock makes concurrent inserts of the same id converge to a replay or a
|
||||
/// typed conflict instead of a raw unique violation. Timestamps are
|
||||
/// normalized to Postgres `timestamptz` precision (microseconds) so the
|
||||
/// first returned plan is exactly what every later read returns.
|
||||
pub async fn create_import_plan(
|
||||
&self,
|
||||
request: CreateImportPlanRequest<'_>,
|
||||
) -> Result<ImportPlan, RegistryError> {
|
||||
validate_plan_id(request.id)?;
|
||||
let created_at = db_precision_utc(*request.created_at);
|
||||
let expires_at = db_precision_utc(*request.expires_at);
|
||||
if expires_at <= created_at {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "expires_at",
|
||||
});
|
||||
}
|
||||
let digest = plan_digest_from_payload(request.payload)?;
|
||||
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
|
||||
if let Some(existing) =
|
||||
find_plan_row(&mut *transaction, request.workspace_id, request.id).await?
|
||||
{
|
||||
match plan_replay_outcome(existing, &digest, &request, created_at, expires_at) {
|
||||
Ok(stored) => {
|
||||
transaction.commit().await?;
|
||||
return Ok(stored);
|
||||
}
|
||||
Err(error) => {
|
||||
transaction.rollback().await?;
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let job_row = sqlx::query(
|
||||
"select kind, status, preview_payload, expires_at
|
||||
from import_jobs
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.job_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
let job_row = match job_row {
|
||||
Some(row) => row,
|
||||
None => {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let kind = deserialize_enum_text::<ImportJobKind>(job_row.try_get("kind")?, "kind")?;
|
||||
if kind != ImportJobKind::OpenApi {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let status =
|
||||
deserialize_enum_text::<ImportJobStatus>(job_row.try_get("status")?, "status")?;
|
||||
if status != ImportJobStatus::Pending {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::ImportPlanJobTerminal {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let job_expires: OffsetDateTime = job_row.try_get("expires_at")?;
|
||||
if job_expires <= OffsetDateTime::now_utc() {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::ImportPlanJobExpired {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
// The plan must not outlive the job that anchors it, otherwise the
|
||||
// protected source snapshots can expire while the plan is still valid.
|
||||
if expires_at > job_expires {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "expires_at",
|
||||
});
|
||||
}
|
||||
let preview_payload: Value = job_row.try_get("preview_payload")?;
|
||||
if source_from_payload(&preview_payload)?.is_none() {
|
||||
transaction.rollback().await?;
|
||||
return Err(RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
sqlx::query("select id from workspaces where id = $1 for update")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
// Authoritative re-check: any concurrent insert of this (workspace, id)
|
||||
// must also hold the workspace lock, so a winner cannot appear between
|
||||
// the fast-path check and the insert.
|
||||
if let Some(existing) =
|
||||
find_plan_row(&mut *transaction, request.workspace_id, request.id).await?
|
||||
{
|
||||
match plan_replay_outcome(existing, &digest, &request, created_at, expires_at) {
|
||||
Ok(stored) => {
|
||||
transaction.commit().await?;
|
||||
return Ok(stored);
|
||||
}
|
||||
Err(error) => {
|
||||
transaction.rollback().await?;
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"insert into import_plans (
|
||||
workspace_id, id, job_id, digest, payload, created_at, expires_at
|
||||
) values (
|
||||
$1, $2, $3, $4, $5, $6::timestamptz, $7::timestamptz
|
||||
)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.id.as_str())
|
||||
.bind(request.job_id.as_str())
|
||||
.bind(&digest)
|
||||
.bind(request.payload)
|
||||
.bind(created_at)
|
||||
.bind(expires_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(ImportPlan {
|
||||
id: request.id.as_str().to_owned().into(),
|
||||
workspace_id: (*request.workspace_id).clone(),
|
||||
job_id: (*request.job_id).clone(),
|
||||
digest,
|
||||
payload: (*request.payload).clone(),
|
||||
created_at,
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an import plan. Returns `None` for an absent id or any id owned
|
||||
/// by another workspace so a foreign scope is never revealed by an error.
|
||||
pub async fn get_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
) -> Result<Option<ImportPlan>, RegistryError> {
|
||||
validate_plan_id(plan_id)?;
|
||||
let row = sqlx::query(
|
||||
"select id, workspace_id, job_id, digest, payload, created_at, expires_at
|
||||
from import_plans
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(plan_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
row.as_ref().map(map_import_plan).transpose()
|
||||
}
|
||||
|
||||
pub async fn finish_import_job(
|
||||
&self,
|
||||
request: FinishImportJobRequest<'_>,
|
||||
@@ -673,3 +862,96 @@ async fn next_available_operation_name(
|
||||
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn map_import_plan(row: &PgRow) -> Result<ImportPlan, RegistryError> {
|
||||
Ok(ImportPlan {
|
||||
id: ImportPlanId::new(row.try_get::<String, _>("id")?),
|
||||
workspace_id: WorkspaceId::new(row.try_get::<String, _>("workspace_id")?),
|
||||
job_id: ImportJobId::new(row.try_get::<String, _>("job_id")?),
|
||||
digest: row.try_get::<String, _>("digest")?,
|
||||
payload: row.try_get::<Value, _>("payload")?,
|
||||
created_at: row.try_get("created_at")?,
|
||||
expires_at: row.try_get("expires_at")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the canonical plan digest: the lowercase SHA-256 of the payload
|
||||
/// serialized to its deterministic byte form. `serde_json::Value` object keys
|
||||
/// are ordered (BTreeMap-backed map), so `to_vec` is stable across calls and
|
||||
/// platforms — the digest is therefore reproducible for byte-identical
|
||||
/// material without requiring a client-supplied digest.
|
||||
fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(payload)?;
|
||||
if canonical.len() > MAX_IMPORT_PLAN_PAYLOAD_BYTES {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
fn validate_plan_id(id: &ImportPlanId) -> Result<(), RegistryError> {
|
||||
if !(1..=MAX_IMPORT_PLAN_ID_BYTES).contains(&id.as_str().len()) {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "id" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a workspace-scoped plan row, locking it if it exists, inside the
|
||||
/// given executor (the creation transaction).
|
||||
async fn find_plan_row<'c, E>(
|
||||
executor: E,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
) -> Result<Option<PgRow>, RegistryError>
|
||||
where
|
||||
E: Executor<'c, Database = Postgres>,
|
||||
{
|
||||
Ok(sqlx::query(
|
||||
"select id, workspace_id, job_id, digest, payload, created_at, expires_at
|
||||
from import_plans
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(plan_id.as_str())
|
||||
.fetch_optional(executor)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Decides the outcome for an already-present plan: byte-identical material,
|
||||
/// same job and same (DB-precision) lifetime is a replay returning the stored
|
||||
/// row; anything else is a typed conflict. Pure check — no transaction side
|
||||
/// effects, so the caller keeps commit/rollback authority.
|
||||
fn plan_replay_outcome(
|
||||
existing: PgRow,
|
||||
digest: &str,
|
||||
request: &CreateImportPlanRequest<'_>,
|
||||
created_at: OffsetDateTime,
|
||||
expires_at: OffsetDateTime,
|
||||
) -> Result<ImportPlan, RegistryError> {
|
||||
let stored = map_import_plan(&existing)?;
|
||||
let replay = stored.digest == digest
|
||||
&& stored.job_id == *request.job_id
|
||||
&& stored.created_at == created_at
|
||||
&& stored.expires_at == expires_at;
|
||||
if replay {
|
||||
return Ok(stored);
|
||||
}
|
||||
Err(RegistryError::ImportPlanConflict {
|
||||
plan_id: request.id.as_str().to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reduces an instant to Postgres `timestamptz` precision (microseconds).
|
||||
///
|
||||
/// `OffsetDateTime` may carry nanosecond precision that the column silently
|
||||
/// truncates; binding the unnormalized value would make the first returned
|
||||
/// plan differ from every later read and break replay equality.
|
||||
fn db_precision_utc(instant: OffsetDateTime) -> OffsetDateTime {
|
||||
let nanos = instant.unix_timestamp_nanos();
|
||||
let micros = (nanos / 1_000) * 1_000;
|
||||
OffsetDateTime::from_unix_timestamp_nanos(micros)
|
||||
.expect("timestamp within the valid range after truncating nanoseconds")
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
use super::*;
|
||||
use crate::{
|
||||
ApplyImportPlanRequest, ApplyImportPlanResult, ImportJobKind, ImportJobSourceEnvelope,
|
||||
ImportPlanApplication, ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef,
|
||||
};
|
||||
use crank_core::{AuthProfile, OperationId, OperationStatus, Protocol};
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
mod material;
|
||||
mod mutations;
|
||||
mod verify;
|
||||
|
||||
use material::*;
|
||||
use mutations::*;
|
||||
use verify::*;
|
||||
|
||||
const PLAN_PAYLOAD_SCHEMA_VERSION: &str = "import-plan-v1";
|
||||
const APPLY_REPORT_SCHEMA_VERSION: &str = "import-plan-apply-report-v1";
|
||||
/// Same upper bound as plan creation keeps the report compatible with every
|
||||
/// plan that was accepted: at most this many candidates / names / targets.
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 512;
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
|
||||
const MAX_IMPORT_PLAN_SERVER_URL_BYTES: usize = 8_192;
|
||||
const MAX_IMPORT_PLAN_REASON_BYTES: usize = 1_024;
|
||||
const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
|
||||
/// Bound for the serialized apply report. Must accommodate a full accepted
|
||||
/// plan: report entries carry only key/name/ids (already bounded) while the
|
||||
/// plan payload — which carries far more per candidate — is capped at
|
||||
/// `MAX_IMPORT_PLAN_PAYLOAD_BYTES` (4 MiB) at creation. This keeps every
|
||||
/// accepted plan's exact outcomes inside the report without truncation.
|
||||
const MAX_IMPORT_PLAN_REPORT_BYTES: usize = MAX_IMPORT_PLAN_PAYLOAD_BYTES;
|
||||
|
||||
/// Failure of one apply transaction: a typed registry conflict, or the
|
||||
/// application-row uniqueness collision that must be reconciled after the
|
||||
/// transaction is rolled back.
|
||||
#[derive(Debug)]
|
||||
pub(super) enum ApplyTxFailure {
|
||||
Registry(RegistryError),
|
||||
KeyConflict,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The transaction itself.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Runs the whole apply: locks in the fixed order, revalidates the
|
||||
/// immutable material, applies every selected candidate and inserts the
|
||||
/// application record. All domain mutations and the report insert are one
|
||||
/// transaction.
|
||||
async fn apply_import_plan_transaction(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
) -> Result<(bool, ImportPlanApplyReport), ApplyTxFailure> {
|
||||
let fail = |error: RegistryError| ApplyTxFailure::Registry(error);
|
||||
let plan_id = request.plan_id.as_str().to_owned();
|
||||
|
||||
// Lock order is strictly `import_jobs` -> `import_plans` ->
|
||||
// `workspaces` -> artifact rows -> auth rows -> operation rows. The
|
||||
// expired-job cleanup locks the job first and cascades to the plan, so
|
||||
// a plan->job ordering could deadlock; this ordering cannot wait on the
|
||||
// cleanup.
|
||||
let plan_hint =
|
||||
sqlx::query("select job_id from import_plans where workspace_id = $1 and id = $2")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.plan_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let Some(plan_hint) = plan_hint else {
|
||||
return Err(fail(RegistryError::ImportPlanNotFound { plan_id }));
|
||||
};
|
||||
let job_id: String = plan_hint
|
||||
.try_get::<String, _>("job_id")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let job_row = sqlx::query(
|
||||
"select kind, status, preview_payload, expires_at
|
||||
from import_jobs
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(&job_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let Some(job_row) = job_row else {
|
||||
// The job was cleaned up (or the plan cascaded with it): stale.
|
||||
return Err(fail(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
};
|
||||
let job_kind_str: String = job_row
|
||||
.try_get::<String, _>("kind")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let job_kind: ImportJobKind = deserialize_enum_text(&job_kind_str, "kind").map_err(fail)?;
|
||||
if job_kind != ImportJobKind::OpenApi {
|
||||
return Err(fail(RegistryError::ImportPlanPayloadCorrupt {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
let job_status_str: String = job_row
|
||||
.try_get::<String, _>("status")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let job_status: ImportJobStatus =
|
||||
deserialize_enum_text(&job_status_str, "status").map_err(fail)?;
|
||||
if job_status != ImportJobStatus::Pending {
|
||||
return Err(fail(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
let job_expires = job_row
|
||||
.try_get::<OffsetDateTime, _>("expires_at")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if job_expires <= now {
|
||||
return Err(fail(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
let job_preview_payload = job_row
|
||||
.try_get::<Value, _>("preview_payload")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
|
||||
// Now lock the plan itself and verify it survived with identical
|
||||
// material.
|
||||
let plan_row = sqlx::query(
|
||||
"select job_id, digest, payload, expires_at
|
||||
from import_plans
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.plan_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let Some(plan_row) = plan_row else {
|
||||
return Err(fail(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
};
|
||||
let stored_job_id: String = plan_row
|
||||
.try_get::<String, _>("job_id")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if stored_job_id != job_id {
|
||||
return Err(fail(RegistryError::ImportPlanPayloadCorrupt {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
let stored_digest: String = plan_row
|
||||
.try_get::<String, _>("digest")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let plan_payload = plan_row
|
||||
.try_get::<Value, _>("payload")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
let plan_expires = plan_row
|
||||
.try_get::<OffsetDateTime, _>("expires_at")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if plan_expires <= now {
|
||||
return Err(fail(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Serialize the workspace and re-check the idempotency key: a racing
|
||||
// identical apply committed first, or a racing different digest.
|
||||
let workspace_present = sqlx::query_scalar::<_, bool>(
|
||||
"select exists(select 1 from workspaces where id = $1 for update)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if !workspace_present {
|
||||
return Err(fail(RegistryError::WorkspaceNotFound {
|
||||
workspace_id: request.workspace_id.as_str().to_owned(),
|
||||
}));
|
||||
}
|
||||
let stored_application = sqlx::query(
|
||||
"select plan_digest, report
|
||||
from import_plan_applications
|
||||
where workspace_id = $1 and idempotency_key = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.idempotency_key)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if let Some(stored_application) = stored_application {
|
||||
let stored_digest: String = stored_application
|
||||
.try_get::<String, _>("plan_digest")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?;
|
||||
if stored_digest == request.plan_digest {
|
||||
let report: ImportPlanApplyReport = serde_json::from_value(
|
||||
stored_application
|
||||
.try_get::<Value, _>("report")
|
||||
.map_err(|e| fail(RegistryError::Storage(e)))?,
|
||||
)
|
||||
.map_err(|error| ApplyTxFailure::Registry(RegistryError::Serialization(error)))?;
|
||||
return Ok((true, report));
|
||||
}
|
||||
return Err(fail(RegistryError::ImportPlanKeyDigestConflict {
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Revalidate the immutable material and the service fingerprint.
|
||||
let plan =
|
||||
read_and_validate_plan_material(&plan_payload, request, &stored_digest, &stored_job_id)
|
||||
.map_err(fail)?;
|
||||
verify_job_source_consistency(&job_preview_payload, &plan, &plan_id).map_err(fail)?;
|
||||
|
||||
// Blocked selected candidates reject the whole apply: zero mutation.
|
||||
if plan
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|candidate| candidate.state == "blocked")
|
||||
{
|
||||
let report = build_rejected_report(request, &plan, db_precision_utc(*request.applied_at));
|
||||
return Ok((false, report));
|
||||
}
|
||||
|
||||
// Verify the source and dependency snapshots are still active with the
|
||||
// recorded digests (no network fetch). The job stays pending and the
|
||||
// sources stay attached: other stored plans remain viable until TTL.
|
||||
let mut envelopes: Vec<ImportJobSourceEnvelope> = plan
|
||||
.dependencies
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|dependency| ImportJobSourceEnvelope {
|
||||
source_id: ArtifactSourceId::new(dependency.source_id),
|
||||
digest: ArtifactRef::parse(&dependency.digest).expect("validated above"),
|
||||
})
|
||||
.collect();
|
||||
envelopes.push(ImportJobSourceEnvelope {
|
||||
source_id: ArtifactSourceId::new(plan.source.source_id.clone()),
|
||||
digest: ArtifactRef::parse(&plan.source.digest).expect("validated above"),
|
||||
});
|
||||
envelopes.sort_by(|a, b| a.source_id.as_str().cmp(b.source_id.as_str()));
|
||||
envelopes.dedup_by(|a, b| a.source_id == b.source_id && a.digest == b.digest);
|
||||
for envelope in &envelopes {
|
||||
lock_and_verify_envelope(tx, request.workspace_id, envelope)
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
}
|
||||
|
||||
// Revalidate every referenced auth profile and secret under locks.
|
||||
lock_and_verify_auth(tx, request.workspace_id, &plan.candidates)
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
|
||||
// Apply the selected candidates in deterministic order.
|
||||
let mut candidates: Vec<&StoredPlanCandidate> = plan.candidates.iter().collect();
|
||||
candidates.sort_by(|a, b| a.key.cmp(&b.key));
|
||||
let mut outcomes = Vec::with_capacity(candidates.len());
|
||||
for candidate in candidates {
|
||||
let outcome = apply_candidate_action(tx, request.workspace_id, candidate)
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
|
||||
let applied_at = db_precision_utc(*request.applied_at);
|
||||
let report = build_applied_report(request, &plan, outcomes, applied_at);
|
||||
persist_application_row(tx, request, &stored_digest, &report, applied_at).await?;
|
||||
Ok((false, report))
|
||||
}
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Atomically applies a stored, immutable import plan.
|
||||
///
|
||||
/// * Repays of a committed `(workspace, idempotency_key, plan_digest)`
|
||||
/// triple return the stored immutable report — byte-for-byte, even
|
||||
/// after the plan and its job have been cleaned up — with
|
||||
/// `result.replayed == true`. A different digest under an already-used
|
||||
/// key is a typed conflict.
|
||||
/// * A fresh apply revalidates the plan digest/schema/selection
|
||||
/// closure, the anchor job, the verified source/dependency snapshots
|
||||
/// and every referenced auth profile + secret, then materializes the
|
||||
/// create/rename/skip/new_version mutations — all inside one
|
||||
/// transaction with the application report insert. The successful
|
||||
/// apply leaves the job pending and the sources attached so other
|
||||
/// stored plans remain viable until the TTL expires.
|
||||
pub async fn apply_import_plan(
|
||||
&self,
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
) -> Result<ApplyImportPlanResult, RegistryError> {
|
||||
validate_apply_request(request)?;
|
||||
|
||||
// Replay fast path: committed report evidence is self-contained and
|
||||
// outlives the plan and its job, so a matching key+digest returns it
|
||||
// before the plan/job lookups would see the cleaned-up rows.
|
||||
if let Some(application) = self
|
||||
.get_import_plan_application(request.workspace_id, request.idempotency_key)
|
||||
.await?
|
||||
{
|
||||
if application.plan_digest == request.plan_digest {
|
||||
return Ok(application.result);
|
||||
}
|
||||
return Err(RegistryError::ImportPlanKeyDigestConflict {
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
let outcome = apply_import_plan_transaction(&mut transaction, request).await;
|
||||
match outcome {
|
||||
Ok((replayed, report)) => {
|
||||
transaction.commit().await?;
|
||||
Ok(ApplyImportPlanResult { replayed, report })
|
||||
}
|
||||
Err(ApplyTxFailure::KeyConflict) => {
|
||||
// The application row appeared while we were committing: a
|
||||
// concurrent identical apply committed first. Roll back our
|
||||
// mutations and converge on the stored report (or, if the
|
||||
// digest differs, the typed conflict).
|
||||
transaction.rollback().await?;
|
||||
let Some(application) = self
|
||||
.get_import_plan_application(request.workspace_id, request.idempotency_key)
|
||||
.await?
|
||||
else {
|
||||
return Err(RegistryError::ImportPlanKeyDigestConflict {
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
});
|
||||
};
|
||||
if application.plan_digest == request.plan_digest {
|
||||
return Ok(application.result);
|
||||
}
|
||||
Err(RegistryError::ImportPlanKeyDigestConflict {
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
})
|
||||
}
|
||||
Err(ApplyTxFailure::Registry(error)) => {
|
||||
transaction.rollback().await?;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the stored application evidence for a scoped idempotency key
|
||||
/// (read-only, workspace-scoped): the committed plan digest plus the
|
||||
/// immutable report wrapped as a replayed result. Returns `None` when
|
||||
/// the key was never committed in this workspace. This is the
|
||||
/// replay-first entry point for Admin: a matching digest returns the
|
||||
/// stored report even after the plan and its job have been cleaned
|
||||
/// up; a different digest must be surfaced as a changed plan conflict
|
||||
/// (`ImportPlanKeyDigestConflict`).
|
||||
pub async fn get_import_plan_application(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
idempotency_key: &str,
|
||||
) -> Result<Option<ImportPlanApplication>, RegistryError> {
|
||||
if !(1..=MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES).contains(&idempotency_key.len()) {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "idempotency_key",
|
||||
});
|
||||
}
|
||||
let row = sqlx::query(
|
||||
"select plan_digest, report
|
||||
from import_plan_applications
|
||||
where workspace_id = $1 and idempotency_key = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(idempotency_key)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
match row {
|
||||
Some(row) => {
|
||||
let report: ImportPlanApplyReport =
|
||||
serde_json::from_value(row.try_get::<Value, _>("report")?)?;
|
||||
Ok(Some(ImportPlanApplication {
|
||||
plan_digest: row.try_get("plan_digest")?,
|
||||
result: ApplyImportPlanResult {
|
||||
replayed: true,
|
||||
report,
|
||||
},
|
||||
}))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
use super::*;
|
||||
// ---------------------------------------------------------------------------
|
||||
// Typed parse of the immutable plan material (import-plan-v1). The registry
|
||||
// never trusts the caller: the stored payload is re-derived into a typed
|
||||
// shape and every relationship it claims for itself is re-checked.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredPlan {
|
||||
pub(crate) schema_version: String,
|
||||
pub(crate) plan_reference: String,
|
||||
pub(crate) job_id: String,
|
||||
pub(crate) source: StoredPlanSource,
|
||||
#[serde(default)]
|
||||
pub(crate) dependencies: Vec<StoredPlanSource>,
|
||||
pub(crate) selection: StoredPlanSelection,
|
||||
pub(crate) counts: StoredPlanCounts,
|
||||
pub(crate) candidates: Vec<StoredPlanCandidate>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(super) struct StoredPlanSource {
|
||||
pub(crate) source_id: String,
|
||||
pub(crate) digest: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredPlanSelection {
|
||||
pub(crate) mode: String,
|
||||
pub(crate) all: Vec<String>,
|
||||
pub(crate) selected: Vec<String>,
|
||||
pub(crate) excluded: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub(super) struct StoredPlanCounts {
|
||||
pub(crate) selected: u32,
|
||||
pub(crate) excluded: u32,
|
||||
pub(crate) actionable: u32,
|
||||
pub(crate) blocked: u32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredPlanCandidate {
|
||||
pub(crate) key: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) state: String,
|
||||
pub(crate) decision: StoredPlanDecision,
|
||||
#[serde(default)]
|
||||
pub(crate) reason: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) target: Option<StoredPlanTarget>,
|
||||
#[serde(default)]
|
||||
pub(crate) operation: Option<RegistryOperation>,
|
||||
/// Plan-time auth profile evidence. Required exactly when an actionable
|
||||
/// candidate's operation carries an `auth_profile_ref`: it lets apply
|
||||
/// reject a profile that drifted since confirmation (config change,
|
||||
/// secret rotation/revocation) instead of silently using the new one.
|
||||
/// Never carries credential bytes — only profile metadata and secret
|
||||
/// ids/status/versions.
|
||||
#[serde(default)]
|
||||
pub(crate) auth_snapshot: Option<StoredAuthSnapshot>,
|
||||
}
|
||||
|
||||
/// Plan-time snapshot of one auth profile's redacted metadata.
|
||||
///
|
||||
/// Field names are fixed by the Admin/registry contract: `profile_id`,
|
||||
/// `name`, `kind`, `config` (the stored `config_json` object), `updated_at`
|
||||
/// (RFC3339) and the sorted-by-id `secrets` list.
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
pub(super) struct StoredAuthSnapshot {
|
||||
pub(crate) profile_id: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) kind: String,
|
||||
pub(crate) config: Value,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub(crate) updated_at: OffsetDateTime,
|
||||
pub(crate) secrets: Vec<StoredAuthSecretSnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
pub(super) struct StoredAuthSecretSnapshot {
|
||||
pub(crate) id: String,
|
||||
pub(crate) status: String,
|
||||
pub(crate) current_version: i32,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub(crate) updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredPlanDecision {
|
||||
pub(crate) action: String,
|
||||
#[serde(default)]
|
||||
pub(crate) target_operation_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) confirmed_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) auth_profile_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(super) struct StoredPlanTarget {
|
||||
pub(crate) operation_id: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) expected_state: StoredPlanExpectedState,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(super) struct StoredPlanExpectedState {
|
||||
pub(crate) status: OperationStatus,
|
||||
pub(crate) current_draft_version: u32,
|
||||
pub(crate) latest_published_version: Option<u32>,
|
||||
}
|
||||
|
||||
fn digest_is_hex64(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
}
|
||||
|
||||
pub(super) fn validate_apply_request(
|
||||
request: &ApplyImportPlanRequest,
|
||||
) -> Result<(), RegistryError> {
|
||||
validate_plan_id(request.plan_id)?;
|
||||
if !digest_is_hex64(request.plan_digest) {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "plan_digest",
|
||||
});
|
||||
}
|
||||
if !(1..=MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES).contains(&request.idempotency_key.len()) {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "idempotency_key",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn read_and_validate_plan_material(
|
||||
payload: &Value,
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
stored_digest: &str,
|
||||
stored_job_id: &str,
|
||||
) -> Result<StoredPlan, RegistryError> {
|
||||
let plan_id = request.plan_id.as_str().to_owned();
|
||||
let corrupt = || RegistryError::ImportPlanPayloadCorrupt {
|
||||
plan_id: plan_id.clone(),
|
||||
};
|
||||
let stale = || RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.clone(),
|
||||
};
|
||||
|
||||
if request.plan_digest != stored_digest
|
||||
|| super::super::plan_digest_from_payload(payload).map_err(|_| corrupt())? != stored_digest
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if let Some(server_url) = payload.get("server_url").and_then(Value::as_str)
|
||||
&& (server_url.is_empty() || server_url.len() > MAX_IMPORT_PLAN_SERVER_URL_BYTES)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if payload
|
||||
.pointer("/selection/selected")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
|| payload
|
||||
.pointer("/selection/all")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS * 2)
|
||||
|| payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let source_digest = payload
|
||||
.pointer("/source/digest")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(corrupt)?;
|
||||
if ArtifactRef::parse(source_digest).is_err() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
for item in payload
|
||||
.pointer("/dependencies")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let source_id = item
|
||||
.get("source_id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(corrupt)?;
|
||||
if !(1..=132).contains(&source_id.len()) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let digest = item
|
||||
.get("digest")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(corrupt)?;
|
||||
if ArtifactRef::parse(digest).is_err() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
|
||||
let plan: StoredPlan = serde_json::from_value(payload.clone()).map_err(|_| corrupt())?;
|
||||
|
||||
// The typed material must agree with the request it is being applied for.
|
||||
if plan.schema_version.as_str() != PLAN_PAYLOAD_SCHEMA_VERSION
|
||||
|| plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
|| plan.job_id != stored_job_id
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
|
||||
// Selection closure.
|
||||
if !matches!(plan.selection.mode.as_str(), "full" | "partial") {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let no_duplicates = |items: &[String]| {
|
||||
items.iter().all(|item| !item.is_empty()) && {
|
||||
let mut unique = BTreeSet::new();
|
||||
items.iter().all(|item| unique.insert(item))
|
||||
}
|
||||
};
|
||||
if !no_duplicates(&plan.selection.all)
|
||||
|| !no_duplicates(&plan.selection.selected)
|
||||
|| !no_duplicates(&plan.selection.excluded)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.selection.selected.is_empty() || plan.candidates.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let selected: BTreeSet<&String> = plan.selection.selected.iter().collect();
|
||||
let excluded: BTreeSet<&String> = plan.selection.excluded.iter().collect();
|
||||
let all: BTreeSet<&String> = plan.selection.all.iter().collect();
|
||||
let mut union = selected.clone();
|
||||
union.extend(excluded.iter());
|
||||
if union != all || selected.iter().any(|key| excluded.contains(key)) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.selection.mode == "full" && (!excluded.is_empty() || selected != all) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let candidate_keys: BTreeSet<&String> = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.map(|candidate| &candidate.key)
|
||||
.collect();
|
||||
if candidate_keys != selected {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let actionable = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.filter(|c| c.state == "actionable")
|
||||
.count();
|
||||
let blocked = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.filter(|c| c.state == "blocked")
|
||||
.count();
|
||||
if plan.counts.selected as usize != plan.selection.selected.len()
|
||||
|| plan.counts.excluded as usize != plan.selection.excluded.len()
|
||||
|| plan.counts.actionable != actionable as u32
|
||||
|| plan.counts.blocked != blocked as u32
|
||||
|| plan.counts.actionable + plan.counts.blocked != plan.counts.selected
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
|
||||
// Source bounds (matching the legacy envelope bounds). The digests are
|
||||
// canonical `sha256:` artifact refs exactly as the job envelopes store them.
|
||||
if ArtifactRef::parse(&plan.source.digest).is_err() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let mut dependency_ids = BTreeSet::new();
|
||||
if plan.dependencies.len() > MAX_IMPORT_JOB_DOCUMENTS {
|
||||
return Err(corrupt());
|
||||
}
|
||||
for dependency in &plan.dependencies {
|
||||
if !(1..=132).contains(&dependency.source_id.len())
|
||||
|| ArtifactRef::parse(&dependency.digest).is_err()
|
||||
|| !dependency_ids.insert(dependency.source_id.clone())
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
|
||||
// Per-candidate decision shape.
|
||||
for candidate in &plan.candidates {
|
||||
if !(1..=MAX_IMPORT_PLAN_KEY_BYTES).contains(&candidate.key.len())
|
||||
|| !(1..=MAX_IMPORT_PLAN_NAME_BYTES).contains(&candidate.name.len())
|
||||
|| !matches!(candidate.state.as_str(), "actionable" | "blocked")
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if let Some(reason) = &candidate.reason
|
||||
&& (reason.is_empty() || reason.len() > MAX_IMPORT_PLAN_REASON_BYTES)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let decision = &candidate.decision;
|
||||
if !matches!(
|
||||
decision.action.as_str(),
|
||||
"create" | "skip" | "rename" | "new_version"
|
||||
) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
if decision
|
||||
.target_operation_id
|
||||
.as_deref()
|
||||
.is_some_and(|id| id.is_empty() || id.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
|
||||
|| decision
|
||||
.confirmed_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| name.is_empty() || name.len() > MAX_IMPORT_PLAN_NAME_BYTES)
|
||||
|| decision
|
||||
.auth_profile_id
|
||||
.as_deref()
|
||||
.is_some_and(|id| id.is_empty() || id.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let target = candidate.target.as_ref();
|
||||
if let Some(target) = target
|
||||
&& (!(1..=MAX_IMPORT_PLAN_ID_REF_BYTES).contains(&target.operation_id.len())
|
||||
|| !(1..=MAX_IMPORT_PLAN_NAME_BYTES).contains(&target.name.len()))
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let actionable = candidate.state == "actionable";
|
||||
|
||||
// Auth-snapshot contract: an actionable candidate whose operation
|
||||
// references a profile must carry its plan-time snapshot; nothing
|
||||
// else may (a no-ref candidate carrying one, or a blocked candidate,
|
||||
// is a corrupt plan; a missing one for an auth-bound operation means
|
||||
// the plan predates the snapshot and must be re-previewed).
|
||||
let auth_ref = candidate
|
||||
.operation
|
||||
.as_ref()
|
||||
.and_then(|operation| operation.execution_config.auth_profile_ref.clone());
|
||||
match (&candidate.auth_snapshot, &auth_ref) {
|
||||
(Some(snapshot), Some(id)) if snapshot.profile_id == id.as_str() => {}
|
||||
(Some(snapshot), Some(id)) => {
|
||||
debug_assert!(snapshot.profile_id != id.as_str());
|
||||
return Err(corrupt());
|
||||
}
|
||||
(Some(_), None) => return Err(corrupt()),
|
||||
(None, Some(id)) => {
|
||||
if actionable {
|
||||
return Err(RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id: id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
if let Some(snapshot) = &candidate.auth_snapshot {
|
||||
if snapshot.profile_id.is_empty()
|
||||
|| snapshot.profile_id.len() > MAX_IMPORT_PLAN_ID_REF_BYTES
|
||||
|| snapshot.name.is_empty()
|
||||
|| snapshot.name.len() > MAX_IMPORT_PLAN_NAME_BYTES
|
||||
|| snapshot.kind.is_empty()
|
||||
|| snapshot.kind.len() > 64
|
||||
|| snapshot.secrets.len() > MAX_IMPORT_JOB_DOCUMENTS
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let mut sorted = snapshot
|
||||
.secrets
|
||||
.iter()
|
||||
.map(|secret| secret.id.as_str())
|
||||
.collect::<BTreeSet<_>>();
|
||||
for secret in &snapshot.secrets {
|
||||
if secret.id.is_empty()
|
||||
|| secret.id.len() > MAX_IMPORT_PLAN_ID_REF_BYTES
|
||||
|| secret.status.is_empty()
|
||||
|| secret.status.len() > 16
|
||||
|| secret.current_version < 0
|
||||
|| !sorted.remove(secret.id.as_str())
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
if let Some(decision_auth) = &decision.auth_profile_id
|
||||
&& decision_auth != &snapshot.profile_id
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
match decision.action.as_str() {
|
||||
"create" => {
|
||||
if target.is_some()
|
||||
|| decision.confirmed_name.is_some()
|
||||
|| decision.target_operation_id.is_some()
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
// Blocked candidates are stored without a snapshot; the
|
||||
// snapshot is only required for an actionable apply.
|
||||
if actionable {
|
||||
let operation = candidate.operation.as_ref().ok_or_else(corrupt)?;
|
||||
validate_snapshot_operation(operation)?;
|
||||
if operation.version != 1 {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
}
|
||||
"rename" => {
|
||||
if target.is_some() || decision.target_operation_id.is_some() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let confirmed = decision.confirmed_name.as_deref().ok_or_else(corrupt)?;
|
||||
if actionable {
|
||||
let operation = candidate.operation.as_ref().ok_or_else(corrupt)?;
|
||||
validate_snapshot_operation(operation)?;
|
||||
if operation.version != 1 || operation.name != confirmed {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
}
|
||||
"skip" => {
|
||||
let target = target.ok_or_else(corrupt)?;
|
||||
if decision.target_operation_id.as_deref() != Some(target.operation_id.as_str())
|
||||
|| decision.confirmed_name.is_some()
|
||||
|| candidate.operation.is_some()
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
"new_version" => {
|
||||
let target = target.ok_or_else(corrupt)?;
|
||||
if decision.target_operation_id.as_deref() != Some(target.operation_id.as_str())
|
||||
|| decision.confirmed_name.is_some()
|
||||
|| candidate.name != target.name
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if actionable {
|
||||
let operation = candidate.operation.as_ref().ok_or_else(corrupt)?;
|
||||
validate_snapshot_operation(operation)?;
|
||||
if operation.id.as_str() != target.operation_id {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let expected_next = target
|
||||
.expected_state
|
||||
.current_draft_version
|
||||
.checked_add(1)
|
||||
.ok_or_else(corrupt)?;
|
||||
if operation.version != expected_next {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!("action is validated above"),
|
||||
}
|
||||
}
|
||||
|
||||
// The service recomputes the preview fingerprint from the revalidated
|
||||
// source/dependencies before any mutation; the immutable plan stores the
|
||||
// fingerprint it was created from. A mismatch means the revalidation
|
||||
// drifted from the plan material: re-preview, zero mutation.
|
||||
let Some(plan_fingerprint) = payload.get("fingerprint") else {
|
||||
return Err(stale());
|
||||
};
|
||||
if plan_fingerprint != request.verified_fingerprint {
|
||||
return Err(stale());
|
||||
}
|
||||
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Shared snapshot invariants for planned Draft operations.
|
||||
fn validate_snapshot_operation(operation: &RegistryOperation) -> Result<(), RegistryError> {
|
||||
if operation.status != OperationStatus::Draft || operation.protocol != Protocol::Rest {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "operation" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verifies the plan source/dependencies are exactly the anchor job's
|
||||
/// verified envelopes (the plan material must agree with the job).
|
||||
pub(super) fn verify_job_source_consistency(
|
||||
job_payload: &Value,
|
||||
plan: &StoredPlan,
|
||||
plan_id: &str,
|
||||
) -> Result<(), RegistryError> {
|
||||
let stale = || RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.to_owned(),
|
||||
};
|
||||
let job_source = source_from_payload(job_payload).map_err(|_| stale())?;
|
||||
let Some(job_source) = job_source else {
|
||||
return Err(stale());
|
||||
};
|
||||
if job_source.source_id.as_str() != plan.source.source_id
|
||||
|| job_source.digest.as_str() != plan.source.digest
|
||||
{
|
||||
return Err(stale());
|
||||
}
|
||||
let job_dependencies = dependencies_from_payload(job_payload).map_err(|_| stale())?;
|
||||
let mut job_set: Vec<(String, String)> = job_dependencies
|
||||
.iter()
|
||||
.map(|dependency| {
|
||||
(
|
||||
dependency.source_id.as_str().to_owned(),
|
||||
dependency.digest.as_str().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut plan_set: Vec<(String, String)> = plan
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|dependency| (dependency.source_id.clone(), dependency.digest.clone()))
|
||||
.collect();
|
||||
job_set.sort();
|
||||
plan_set.sort();
|
||||
if job_set != plan_set {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
use super::material::{StoredPlan, StoredPlanCandidate};
|
||||
use super::*;
|
||||
use crate::postgres::operation::matches_operation_name_conflict;
|
||||
// ---------------------------------------------------------------------------
|
||||
// Candidate mutations — exact names only, no runtime auto-rename.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn operation_id_exists(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operation_id: &OperationId,
|
||||
) -> Result<bool, RegistryError> {
|
||||
Ok(sqlx::query_scalar::<_, bool>(
|
||||
"select exists(select 1 from operations where workspace_id = $1 and id = $2)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(operation_id.as_str())
|
||||
.fetch_one(&mut **tx)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(super) async fn apply_candidate_action(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
candidate: &StoredPlanCandidate,
|
||||
) -> Result<ImportPlanCandidateReport, RegistryError> {
|
||||
match candidate.decision.action.as_str() {
|
||||
"create" | "rename" => {
|
||||
let operation = candidate
|
||||
.operation
|
||||
.clone()
|
||||
.ok_or_else(|| RegistryError::InvalidImportPlan { field: "operation" })?;
|
||||
if operation_id_exists(tx, workspace_id, &operation.id).await? {
|
||||
return Err(RegistryError::OperationAlreadyExists {
|
||||
operation_id: operation.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
if operation_name_exists(tx, workspace_id, &operation.name).await? {
|
||||
return Err(RegistryError::ImportPlanNameConflict {
|
||||
name: operation.name.clone(),
|
||||
});
|
||||
}
|
||||
match insert_operation_rows(tx, workspace_id, &operation, None).await {
|
||||
Err(error) if matches_operation_name_conflict(&error) => {
|
||||
return Err(RegistryError::ImportPlanNameConflict {
|
||||
name: operation.name,
|
||||
});
|
||||
}
|
||||
other => other?,
|
||||
}
|
||||
Ok(ImportPlanCandidateReport {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate.name.clone(),
|
||||
outcome: if candidate.decision.action == "create" {
|
||||
ImportPlanCandidateOutcome::Created
|
||||
} else {
|
||||
ImportPlanCandidateOutcome::Renamed
|
||||
},
|
||||
operation_id: Some(operation.id.as_str().to_owned()),
|
||||
version: Some(operation.version),
|
||||
reason: None,
|
||||
})
|
||||
}
|
||||
"skip" => {
|
||||
let target = candidate
|
||||
.target
|
||||
.clone()
|
||||
.ok_or_else(|| RegistryError::InvalidImportPlan { field: "target" })?;
|
||||
let stale = || RegistryError::ImportPlanTargetStale {
|
||||
operation_id: target.operation_id.clone(),
|
||||
};
|
||||
let row = sqlx::query(
|
||||
"select name, status, current_draft_version, latest_published_version
|
||||
from operations
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&target.operation_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(stale)?;
|
||||
let row_name = row.try_get::<String, _>("name")?;
|
||||
let status: OperationStatus = deserialize_enum_text(row.try_get("status")?, "status")?;
|
||||
let current = from_db_version(
|
||||
row.try_get::<i32, _>("current_draft_version")?,
|
||||
"current_draft_version",
|
||||
)?;
|
||||
let latest = row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| from_db_version(value, "latest_published_version"))
|
||||
.transpose()?;
|
||||
if row_name != target.name
|
||||
|| status != target.expected_state.status
|
||||
|| current != target.expected_state.current_draft_version
|
||||
|| latest != target.expected_state.latest_published_version
|
||||
{
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(ImportPlanCandidateReport {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate.name.clone(),
|
||||
outcome: ImportPlanCandidateOutcome::Skipped,
|
||||
operation_id: Some(target.operation_id),
|
||||
version: None,
|
||||
reason: None,
|
||||
})
|
||||
}
|
||||
"new_version" => {
|
||||
let target = candidate
|
||||
.target
|
||||
.clone()
|
||||
.ok_or_else(|| RegistryError::InvalidImportPlan { field: "target" })?;
|
||||
let operation = candidate
|
||||
.operation
|
||||
.clone()
|
||||
.ok_or_else(|| RegistryError::InvalidImportPlan { field: "operation" })?;
|
||||
let stale = || RegistryError::ImportPlanTargetStale {
|
||||
operation_id: target.operation_id.clone(),
|
||||
};
|
||||
let row = sqlx::query(
|
||||
"select name, status, protocol, current_draft_version, latest_published_version
|
||||
from operations
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&target.operation_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(stale)?;
|
||||
let row_name = row.try_get::<String, _>("name")?;
|
||||
let status: OperationStatus = deserialize_enum_text(row.try_get("status")?, "status")?;
|
||||
let protocol: Protocol = deserialize_enum_text(row.try_get("protocol")?, "protocol")?;
|
||||
let current = from_db_version(
|
||||
row.try_get::<i32, _>("current_draft_version")?,
|
||||
"current_draft_version",
|
||||
)?;
|
||||
let latest = row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| from_db_version(value, "latest_published_version"))
|
||||
.transpose()?;
|
||||
if row_name != target.name
|
||||
|| status != target.expected_state.status
|
||||
|| current != target.expected_state.current_draft_version
|
||||
|| latest != target.expected_state.latest_published_version
|
||||
|| status == OperationStatus::Archived
|
||||
|| protocol != Protocol::Rest
|
||||
|| operation.name != target.name
|
||||
|| operation.id.as_str() != target.operation_id
|
||||
|| operation.status != OperationStatus::Draft
|
||||
|| operation.version != current.checked_add(1).ok_or_else(stale)?
|
||||
{
|
||||
return Err(stale());
|
||||
}
|
||||
match insert_version_row(tx, &operation, None, None).await {
|
||||
Err(RegistryError::Storage(sqlx::Error::Database(db_error)))
|
||||
if db_error.code().as_deref() == Some("23505") =>
|
||||
{
|
||||
return Err(stale());
|
||||
}
|
||||
other => other?,
|
||||
}
|
||||
let updated = sqlx::query(
|
||||
"update operations
|
||||
set status = $1, current_draft_version = $2, updated_at = $3::timestamptz
|
||||
where workspace_id = $4 and id = $5",
|
||||
)
|
||||
.bind(serialize_enum_text(&OperationStatus::Draft, "status")?)
|
||||
.bind(to_db_version(operation.version))
|
||||
.bind(operation.updated_at)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&target.operation_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
if updated.rows_affected() != 1 {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(ImportPlanCandidateReport {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate.name.clone(),
|
||||
outcome: ImportPlanCandidateOutcome::Versioned,
|
||||
operation_id: Some(target.operation_id),
|
||||
version: Some(operation.version),
|
||||
reason: None,
|
||||
})
|
||||
}
|
||||
_ => Err(RegistryError::InvalidImportPlan { field: "decision" }),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Report builders and application-record persistence.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn excluded_outcomes(plan: &StoredPlan) -> Vec<ImportPlanCandidateReport> {
|
||||
plan.selection
|
||||
.excluded
|
||||
.iter()
|
||||
.map(|key| ImportPlanCandidateReport {
|
||||
key: key.clone(),
|
||||
name: String::new(),
|
||||
outcome: ImportPlanCandidateOutcome::Excluded,
|
||||
operation_id: None,
|
||||
version: None,
|
||||
reason: Some("not_selected".to_owned()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn build_applied_report(
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
plan: &StoredPlan,
|
||||
outcomes: Vec<ImportPlanCandidateReport>,
|
||||
applied_at: OffsetDateTime,
|
||||
) -> ImportPlanApplyReport {
|
||||
let mut outcomes = outcomes;
|
||||
outcomes.extend(excluded_outcomes(plan));
|
||||
let count_of = |outcome: ImportPlanCandidateOutcome| {
|
||||
outcomes
|
||||
.iter()
|
||||
.filter(|reported| reported.outcome == outcome)
|
||||
.count() as u32
|
||||
};
|
||||
let counts = ImportPlanApplyCounts {
|
||||
created: count_of(ImportPlanCandidateOutcome::Created),
|
||||
versioned: count_of(ImportPlanCandidateOutcome::Versioned),
|
||||
renamed: count_of(ImportPlanCandidateOutcome::Renamed),
|
||||
skipped: count_of(ImportPlanCandidateOutcome::Skipped),
|
||||
excluded: count_of(ImportPlanCandidateOutcome::Excluded),
|
||||
rejected: 0,
|
||||
};
|
||||
ImportPlanApplyReport {
|
||||
schema_version: APPLY_REPORT_SCHEMA_VERSION.to_owned(),
|
||||
status: ImportPlanApplyStatus::Applied,
|
||||
plan_id: request.plan_id.as_str().to_owned(),
|
||||
plan_digest: request.plan_digest.to_owned(),
|
||||
job_id: plan.job_id.clone(),
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
source_id: plan.source.source_id.clone(),
|
||||
source_digest: plan.source.digest.clone(),
|
||||
dependencies: plan
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|dependency| ImportPlanDependencyRef {
|
||||
source_id: dependency.source_id.clone(),
|
||||
digest: dependency.digest.clone(),
|
||||
})
|
||||
.collect(),
|
||||
counts,
|
||||
outcomes,
|
||||
summary: format!(
|
||||
"План применён: создано {}, переименовано {}, новых версий {}, пропущено {}, исключено {}.",
|
||||
counts.created, counts.renamed, counts.versioned, counts.skipped, counts.excluded
|
||||
),
|
||||
recovery: "none".to_owned(),
|
||||
applied_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn build_rejected_report(
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
plan: &StoredPlan,
|
||||
applied_at: OffsetDateTime,
|
||||
) -> ImportPlanApplyReport {
|
||||
let mut outcomes: Vec<ImportPlanCandidateReport> = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.map(|candidate| ImportPlanCandidateReport {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate.name.clone(),
|
||||
outcome: ImportPlanCandidateOutcome::Rejected,
|
||||
operation_id: candidate.decision.target_operation_id.clone(),
|
||||
version: None,
|
||||
reason: if candidate.state == "blocked" {
|
||||
Some(
|
||||
candidate
|
||||
.reason
|
||||
.clone()
|
||||
.unwrap_or_else(|| "import_candidate_blocked".to_owned()),
|
||||
)
|
||||
} else {
|
||||
Some("blocked_by_selection".to_owned())
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
outcomes.extend(excluded_outcomes(plan));
|
||||
let counts = ImportPlanApplyCounts {
|
||||
created: 0,
|
||||
versioned: 0,
|
||||
renamed: 0,
|
||||
skipped: 0,
|
||||
excluded: plan.selection.excluded.len() as u32,
|
||||
rejected: plan.candidates.len() as u32,
|
||||
};
|
||||
ImportPlanApplyReport {
|
||||
schema_version: APPLY_REPORT_SCHEMA_VERSION.to_owned(),
|
||||
status: ImportPlanApplyStatus::Rejected,
|
||||
plan_id: request.plan_id.as_str().to_owned(),
|
||||
plan_digest: request.plan_digest.to_owned(),
|
||||
job_id: plan.job_id.clone(),
|
||||
idempotency_key: request.idempotency_key.to_owned(),
|
||||
source_id: plan.source.source_id.clone(),
|
||||
source_digest: plan.source.digest.clone(),
|
||||
dependencies: plan
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|dependency| ImportPlanDependencyRef {
|
||||
source_id: dependency.source_id.clone(),
|
||||
digest: dependency.digest.clone(),
|
||||
})
|
||||
.collect(),
|
||||
counts,
|
||||
outcomes,
|
||||
summary: format!(
|
||||
"Применение отклонено: {} кандидат(ов) требуют подтверждения, {} кандидат(ов) исключено. Создайте новый preview.",
|
||||
counts.rejected, counts.excluded
|
||||
),
|
||||
recovery: "repreview_required".to_owned(),
|
||||
applied_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn persist_application_row(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
request: &ApplyImportPlanRequest<'_>,
|
||||
stored_digest: &str,
|
||||
report: &ImportPlanApplyReport,
|
||||
applied_at: OffsetDateTime,
|
||||
) -> Result<(), ApplyTxFailure> {
|
||||
let fail = |error: RegistryError| ApplyTxFailure::Registry(error);
|
||||
let report_value = serde_json::to_value(report)
|
||||
.map_err(|error| ApplyTxFailure::Registry(RegistryError::Serialization(error)))?;
|
||||
if serde_json::to_vec(&report_value)
|
||||
.map_err(|error| ApplyTxFailure::Registry(RegistryError::Serialization(error)))?
|
||||
.len()
|
||||
> MAX_IMPORT_PLAN_REPORT_BYTES
|
||||
{
|
||||
return Err(fail(RegistryError::ImportPlanPayloadCorrupt {
|
||||
plan_id: request.plan_id.as_str().to_owned(),
|
||||
}));
|
||||
}
|
||||
let result = sqlx::query(
|
||||
"insert into import_plan_applications (
|
||||
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6::timestamptz)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.idempotency_key)
|
||||
.bind(request.plan_id.as_str())
|
||||
.bind(stored_digest)
|
||||
.bind(report_value)
|
||||
.bind(applied_at)
|
||||
.execute(&mut **tx)
|
||||
.await;
|
||||
match result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(sqlx::Error::Database(db_error))
|
||||
if db_error.code().as_deref() == Some("23505")
|
||||
&& db_error.constraint() == Some("import_plan_applications_pkey") =>
|
||||
{
|
||||
Err(ApplyTxFailure::KeyConflict)
|
||||
}
|
||||
Err(error) => Err(fail(RegistryError::Storage(error))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
use super::*;
|
||||
/// Locks one verified source envelope and requires it to still be active
|
||||
/// with the exact recorded digest. No network fetch is performed.
|
||||
pub(super) async fn lock_and_verify_envelope(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
envelope: &ImportJobSourceEnvelope,
|
||||
) -> Result<(), RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select s.lifecycle, b.artifact_ref
|
||||
from artifact_sources s
|
||||
join artifact_blobs b on b.digest = s.blob_digest
|
||||
where s.workspace_id = $1 and s.source_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(envelope.source_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
let current = row
|
||||
.as_ref()
|
||||
.map(|row| {
|
||||
let lifecycle = row.try_get::<String, _>("lifecycle").ok();
|
||||
let artifact_ref = row.try_get::<String, _>("artifact_ref").ok();
|
||||
lifecycle.as_deref() == Some("active")
|
||||
&& artifact_ref.as_deref() == Some(envelope.digest.as_str())
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !current {
|
||||
return Err(RegistryError::SourceUnavailable);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn auth_profile_from_row(
|
||||
row: &PgRow,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<AuthProfile, RegistryError> {
|
||||
build_auth_profile(
|
||||
row.try_get::<String, _>("id")?,
|
||||
workspace_id.as_str().to_owned(),
|
||||
row.try_get::<String, _>("name")?,
|
||||
row.try_get::<String, _>("kind")?,
|
||||
row.try_get::<Value, _>("config_json")?,
|
||||
row.try_get::<OffsetDateTime, _>("created_at")?,
|
||||
row.try_get::<OffsetDateTime, _>("updated_at")?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Checks every referenced auth profile and secret the same way the
|
||||
/// operation creation path does, but under the apply transaction's locks:
|
||||
///
|
||||
/// 1. read each referenced profile (absent, or name/kind/config/updated_at
|
||||
/// drift from its plan-time snapshot — a stale conflict);
|
||||
/// 2. lock the union of referenced secret rows in sorted order (the same
|
||||
/// order as `save_auth_profile`) and require active + a stored current
|
||||
/// version, plus exact `{id, status, current_version, updated_at}`
|
||||
/// agreement with the sorted plan-time secret list;
|
||||
/// 3. lock the profile rows in sorted order and require the secret set from
|
||||
/// step 1 still equals the live secret set and name/kind/config still
|
||||
/// agree.
|
||||
///
|
||||
/// Only actionable candidates with an operation `auth_profile_ref` take
|
||||
/// part; the plan material was already checked to carry a snapshot for
|
||||
/// exactly those, so a `None` here is unreachable in the checked flow.
|
||||
pub(super) async fn lock_and_verify_auth(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
candidates: &[StoredPlanCandidate],
|
||||
) -> Result<(), RegistryError> {
|
||||
use material::StoredAuthSnapshot;
|
||||
|
||||
let unavailable = |auth_profile_id: &str| RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id: auth_profile_id.to_owned(),
|
||||
};
|
||||
|
||||
// Step 0: the referenced (profile_id, snapshot) pairs in sorted order.
|
||||
// Every candidate binding one profile must carry the same plan-time
|
||||
// snapshot; a disagreement means the profile drifted during CreatePlan
|
||||
// and the whole apply must be re-previewed before any mutation.
|
||||
let mut snapshots: BTreeMap<String, &StoredAuthSnapshot> = BTreeMap::new();
|
||||
{
|
||||
use std::collections::btree_map::Entry;
|
||||
for candidate in candidates {
|
||||
if candidate.state == "blocked" {
|
||||
continue;
|
||||
}
|
||||
let Some(operation) = candidate.operation.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let Some(ref_id) = operation.execution_config.auth_profile_ref.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let snapshot = candidate
|
||||
.auth_snapshot
|
||||
.as_ref()
|
||||
.ok_or_else(|| unavailable(ref_id.as_str()))?;
|
||||
match snapshots.entry(ref_id.as_str().to_owned()) {
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(snapshot);
|
||||
}
|
||||
Entry::Occupied(occupied) => {
|
||||
let id = occupied.key().clone();
|
||||
if *occupied.get() != snapshot {
|
||||
return Err(unavailable(&id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let collected: Vec<(String, &StoredAuthSnapshot)> = snapshots.into_iter().collect();
|
||||
if collected.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Step 1: profile reads with plan-time snapshot comparison.
|
||||
let mut secret_owner: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut read_secret_sets: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
for (profile_id, snapshot) in &collected {
|
||||
let row = sqlx::query(
|
||||
"select id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(profile_id))?;
|
||||
let profile =
|
||||
auth_profile_from_row(&row, workspace_id).map_err(|_| unavailable(profile_id))?;
|
||||
if profile.kind != profile.config.kind() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
// Drift since the plan was confirmed (config, name, kind or
|
||||
// updated_at) means the re-preview contract: typed conflict, no
|
||||
// mutation.
|
||||
if row.try_get::<String, _>("name")? != snapshot.name
|
||||
|| row.try_get::<String, _>("kind")? != snapshot.kind
|
||||
|| row.try_get::<OffsetDateTime, _>("updated_at")? != snapshot.updated_at
|
||||
|| row.try_get::<Value, _>("config_json")? != snapshot.config
|
||||
{
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
let mut secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret_id| secret_id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
secret_ids.sort();
|
||||
secret_ids.dedup();
|
||||
for secret_id in &secret_ids {
|
||||
secret_owner
|
||||
.entry(secret_id.clone())
|
||||
.or_insert_with(|| profile_id.clone());
|
||||
}
|
||||
read_secret_sets.insert(profile_id.clone(), secret_ids);
|
||||
}
|
||||
|
||||
// Step 2: sorted secret locks (same order as `save_auth_profile`),
|
||||
// active-state checks and exact plan-time field agreement.
|
||||
let secret_ids: Vec<String> = secret_owner.keys().cloned().collect();
|
||||
let mut current_secrets: BTreeMap<String, (String, i32, OffsetDateTime)> = BTreeMap::new();
|
||||
for secret_id in &secret_ids {
|
||||
let owner = secret_owner.get(secret_id).cloned().unwrap_or_default();
|
||||
let row = sqlx::query(
|
||||
"select status, current_version, updated_at
|
||||
from secrets
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(&owner))?;
|
||||
let status: String = row.try_get("status")?;
|
||||
if status != "active" {
|
||||
return Err(unavailable(&owner));
|
||||
}
|
||||
let current_version = row.try_get::<i32, _>("current_version")?;
|
||||
let updated_at = row.try_get::<OffsetDateTime, _>("updated_at")?;
|
||||
let version_present = sqlx::query_scalar::<_, bool>(
|
||||
"select exists(select 1 from secret_versions where secret_id = $1 and version = $2)",
|
||||
)
|
||||
.bind(secret_id)
|
||||
.bind(current_version)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if !version_present {
|
||||
return Err(unavailable(&owner));
|
||||
}
|
||||
current_secrets.insert(secret_id.clone(), (status, current_version, updated_at));
|
||||
}
|
||||
// Every profile's ordered live secret list must equal its plan-time
|
||||
// snapshot list exactly (same ids, same order, same fields).
|
||||
for (profile_id, snapshot) in &collected {
|
||||
let live: Vec<(&str, String, i32, OffsetDateTime)> = read_secret_sets[profile_id]
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let (status, version, updated_at) = ¤t_secrets[id];
|
||||
(id.as_str(), status.clone(), *version, *updated_at)
|
||||
})
|
||||
.collect();
|
||||
if live.len() != snapshot.secrets.len() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
for (live_id, live_status, live_version, live_updated_at) in live.iter() {
|
||||
let Some(snapshot_secret) =
|
||||
snapshot.secrets.iter().find(|secret| secret.id == *live_id)
|
||||
else {
|
||||
return Err(unavailable(profile_id));
|
||||
};
|
||||
if snapshot_secret.id != *live_id
|
||||
|| snapshot_secret.status != live_status.as_str()
|
||||
|| snapshot_secret.current_version != *live_version
|
||||
|| snapshot_secret.updated_at != *live_updated_at
|
||||
{
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
}
|
||||
// The sorted-by-id snapshot must contain the live set with no extras
|
||||
// covered above; equal lengths plus every live id present is exact.
|
||||
}
|
||||
|
||||
// Step 3: sorted profile locks + stability re-check under the lock.
|
||||
for (profile_id, snapshot) in &collected {
|
||||
let row = sqlx::query(
|
||||
"select id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(profile_id))?;
|
||||
let profile =
|
||||
auth_profile_from_row(&row, workspace_id).map_err(|_| unavailable(profile_id))?;
|
||||
if profile.kind != profile.config.kind() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
if row.try_get::<String, _>("name")? != snapshot.name
|
||||
|| row.try_get::<String, _>("kind")? != snapshot.kind
|
||||
|| row.try_get::<OffsetDateTime, _>("updated_at")? != snapshot.updated_at
|
||||
|| row.try_get::<Value, _>("config_json")? != snapshot.config
|
||||
{
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
let mut current_secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret_id| secret_id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
current_secret_ids.sort();
|
||||
current_secret_ids.dedup();
|
||||
if read_secret_sets.get(profile_id) != Some(¤t_secret_ids) {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -989,7 +989,7 @@ fn verify_expected_state(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn matches_operation_name_conflict(error: &RegistryError) -> bool {
|
||||
pub(super) fn matches_operation_name_conflict(error: &RegistryError) -> bool {
|
||||
let RegistryError::Storage(sqlx::Error::Database(error)) = error else {
|
||||
return false;
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user