feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -136,8 +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("import auth profile binding is unavailable")]
|
||||
ImportAuthBindingUnavailable,
|
||||
#[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}")]
|
||||
@@ -150,6 +182,14 @@ pub enum RegistryError {
|
||||
OnboardingStaleRevision,
|
||||
#[error("onboarding domain steps are not complete")]
|
||||
OnboardingIncomplete,
|
||||
#[error(
|
||||
"onboarding import Draft is not an actionable Draft produced by a committed import apply"
|
||||
)]
|
||||
OnboardingImportDraftUnavailable,
|
||||
#[error("no committed import apply report matches the requested application identity")]
|
||||
OnboardingImportApplicationUnavailable,
|
||||
#[error("the workspace has no durable import context matching the requested application")]
|
||||
OnboardingImportContextUnavailable,
|
||||
#[error("artifact source {source_id} was not found")]
|
||||
SourceNotFound { source_id: String },
|
||||
#[error("artifact source {source_id} conflicts with immutable metadata or lifecycle")]
|
||||
|
||||
@@ -21,41 +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, ImportAuthRequirement, ImportConflictMode,
|
||||
ImportJobSourceEnvelope, ImportOperationDraft, ListApprovalRequestsQuery,
|
||||
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||
MasterKeyIdentityCandidate, PublishAgentRequest, PublishRequest,
|
||||
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,
|
||||
RecoverAdminPasswordRequest, RegisterOnboardingImportContextRequest, RotateSecretRequest,
|
||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
||||
UpdateAgentSummaryRequest, UpdateWorkspaceRequest, UsageQuery,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,36 +74,41 @@ 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, ImportAuthRequirement,
|
||||
ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft,
|
||||
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode,
|
||||
ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
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,
|
||||
SaveWorkspaceUpstreamRequest, SecretRecord, SecretVersionRecord, SessionRecord,
|
||||
MasterKeyRotationStatus, MembershipRecord, OnboardingEventSnapshot, OnboardingImportChoice,
|
||||
OnboardingImportContext, OnboardingImportDrift, OnboardingMilestoneResult,
|
||||
OnboardingPresentationMilestone, OnboardingSnapshot, OperationAgentRef,
|
||||
OperationSampleMetadata, OperationStateExpectation, OperationSummary, OperationUsageSummary,
|
||||
OperationVersionRecord, Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest,
|
||||
PublishRequest, PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest,
|
||||
RegisterOnboardingImportContextRequest, RegistryOperation, RotateSecretRequest, SampleKind,
|
||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
||||
SecretRecord, SecretVersionRecord, SelectOnboardingImportDraftRequest, SessionRecord,
|
||||
SkippedImportOperation, UpdateAgentSummaryRequest, UpdateWorkspaceRequest, UsageAgentBreakdown,
|
||||
UsageBucket, UsageOperationBreakdown, UsageOutcomeBreakdown, UsageOutcomeGroup, UsageQuery,
|
||||
UsageRollupRecord, UsageSummary, UsageTimelinePoint, VerifiedArtifactSource,
|
||||
|
||||
@@ -6,7 +6,9 @@ mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod execution_outcome_v5;
|
||||
mod import_plan_v14;
|
||||
mod master_key_identity_v7;
|
||||
mod onboarding_import_selection_v15;
|
||||
mod onboarding_product_events_v11;
|
||||
mod owned_relations;
|
||||
mod platform_key_name_reuse_v6;
|
||||
@@ -16,6 +18,8 @@ mod schema_guard_v10;
|
||||
mod schema_guard_v11;
|
||||
mod schema_guard_v12;
|
||||
mod schema_guard_v13;
|
||||
mod schema_guard_v14;
|
||||
mod schema_guard_v15;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -4,7 +4,9 @@ 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_import_selection_v15;
|
||||
use super::onboarding_product_events_v11;
|
||||
use super::owned_relations;
|
||||
use super::platform_key_name_reuse_v6;
|
||||
@@ -25,8 +27,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 = 15;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
|
||||
@@ -264,6 +266,13 @@ impl MigrationAuthority {
|
||||
artifact_cleanup_indexes_v13::SOURCE_SHA256,
|
||||
12,
|
||||
),
|
||||
expand_descriptor(14, "import-plan-v14", import_plan_v14::SOURCE_SHA256, 13),
|
||||
expand_descriptor(
|
||||
15,
|
||||
"onboarding-import-selection-v15",
|
||||
onboarding_import_selection_v15::SOURCE_SHA256,
|
||||
14,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -392,6 +401,12 @@ 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?;
|
||||
}
|
||||
if from < 15 {
|
||||
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
@@ -558,6 +573,14 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ONBOARDING_IMPORT_SELECTION,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
@@ -580,6 +603,7 @@ async fn is_ledgerless_legacy_baseline(
|
||||
"product_events",
|
||||
"product_event_daily_rollups",
|
||||
"onboarding_selections",
|
||||
"onboarding_import_selections",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
] {
|
||||
|
||||
@@ -130,6 +130,9 @@ 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
|
||||
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
|
||||
!= onboarding_import_selection_v15::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, 15]
|
||||
);
|
||||
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();
|
||||
@@ -0,0 +1,44 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const SOURCE: &str = include_str!("onboarding_import_selection_v15.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"0dbe85c649ca227f15ac141e7bf004948d3240c3495489b30e2197980ecd0c5e";
|
||||
|
||||
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.onboarding_import_selection",
|
||||
Some(15),
|
||||
"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(15),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
-- Guided onboarding OpenAPI import context.
|
||||
--
|
||||
-- A workspace has at most one durable import context. It stores only the
|
||||
-- identity of an already committed immutable apply report
|
||||
-- (`application_idempotency_key`, `plan_digest`) plus the explicitly selected
|
||||
-- operation/version and timestamps. The immutable report itself is never
|
||||
-- copied or mutated here; recovery re-reads it from
|
||||
-- `import_plan_applications` by (workspace_id, idempotency_key) and verifies
|
||||
-- the exact plan digest. This keeps the context alive after the import job and
|
||||
-- plan are garbage collected.
|
||||
--
|
||||
-- Pending context has null selected operation/version and suppresses generic
|
||||
-- automatic Operation selection until the administrator explicitly picks one
|
||||
-- actionable Draft. Reset deletes the context without touching the terminal
|
||||
-- `onboarding_selections` evidence boundary.
|
||||
|
||||
alter table operations
|
||||
add constraint operations_workspace_id_unique unique (workspace_id, id);
|
||||
|
||||
create table onboarding_import_selections (
|
||||
workspace_id text primary key references workspaces(id) on delete cascade,
|
||||
application_idempotency_key text not null,
|
||||
plan_digest text not null,
|
||||
selected_operation_id text null,
|
||||
selected_operation_version integer null,
|
||||
registered_at timestamptz not null,
|
||||
selected_at timestamptz null,
|
||||
constraint onboarding_import_selections_application_key_check
|
||||
check (octet_length(application_idempotency_key) between 1 and 256),
|
||||
constraint onboarding_import_selections_plan_digest_check
|
||||
check (plan_digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint onboarding_import_selections_version_check
|
||||
check (selected_operation_version is null or selected_operation_version > 0),
|
||||
constraint onboarding_import_selections_selection_shape_check check (
|
||||
(
|
||||
selected_operation_id is null
|
||||
and selected_operation_version is null
|
||||
and selected_at is null
|
||||
) or (
|
||||
selected_operation_id is not null
|
||||
and selected_operation_version is not null
|
||||
and selected_at is not null
|
||||
)
|
||||
),
|
||||
-- The selected Operation is a durable report anchor. Hard-deleting it must
|
||||
-- fail until the administrator explicitly resets/clears the import context;
|
||||
-- normal archive keeps the row and surfaces drift. `no action` (checked at
|
||||
-- statement end) still lets a single workspace deletion cascade-clean the
|
||||
-- whole context together with its operations.
|
||||
constraint onboarding_import_selections_operation_fk
|
||||
foreign key (workspace_id, selected_operation_id)
|
||||
references operations(workspace_id, id)
|
||||
on delete no action,
|
||||
constraint onboarding_import_selections_application_fk
|
||||
foreign key (workspace_id, application_idempotency_key)
|
||||
references import_plan_applications(workspace_id, idempotency_key)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create index onboarding_import_selections_operation_idx
|
||||
on onboarding_import_selections(workspace_id, selected_operation_id);
|
||||
|
||||
alter table product_events
|
||||
drop constraint product_events_name_check;
|
||||
|
||||
alter table product_events
|
||||
add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed', 'onboarding_dismissed',
|
||||
'onboarding_abandoned', 'onboarding_completed',
|
||||
'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated'
|
||||
));
|
||||
|
||||
alter table product_event_daily_rollups
|
||||
drop constraint product_event_daily_rollups_name_check;
|
||||
|
||||
alter table product_event_daily_rollups
|
||||
add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed', 'onboarding_dismissed',
|
||||
'onboarding_abandoned', 'onboarding_completed',
|
||||
'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated'
|
||||
));
|
||||
@@ -31,8 +31,12 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
|
||||
"onboarding_selections",
|
||||
];
|
||||
|
||||
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
|
||||
|
||||
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,9 @@ pub(super) const OWNED_RELATIONS: &[&str] = &[
|
||||
"usage_rollups",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
"import_plans",
|
||||
"import_plan_applications",
|
||||
"onboarding_import_selections",
|
||||
];
|
||||
|
||||
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
|
||||
@@ -645,6 +648,20 @@ 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?;
|
||||
}
|
||||
if current_version < 15 {
|
||||
if !super::schema_guard_v15::validate_v15_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v15::validate_v15_onboarding_import_selection(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"))
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{
|
||||
constraint_expression, normalize_definition, relation_exists, schema_error,
|
||||
};
|
||||
|
||||
const IMPORT_EVENT_NAMES: &[&str] = &[
|
||||
"onboarding_import_eligible",
|
||||
"onboarding_import_published",
|
||||
"onboarding_agent_activated",
|
||||
];
|
||||
|
||||
const CONTEXT_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("application_idempotency_key", "text", false),
|
||||
("plan_digest", "text", false),
|
||||
("selected_operation_id", "text", true),
|
||||
("selected_operation_version", "integer", true),
|
||||
("registered_at", "timestamp with time zone", false),
|
||||
("selected_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
pub(super) async fn validate_v15_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, "onboarding_import_selections").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if !relation_exists(connection, "product_events").await? {
|
||||
return Ok(true);
|
||||
}
|
||||
let name_check =
|
||||
constraint_expression(connection, "product_events", "product_events_name_check").await?;
|
||||
Ok(!normalize_definition(&name_check).contains("onboarding_import_eligible"))
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v15_onboarding_import_selection(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
validate_context_columns(connection).await?;
|
||||
validate_context_constraints(connection).await?;
|
||||
validate_context_index(connection).await?;
|
||||
if !named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? {
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
for (table, constraint) in [
|
||||
("product_events", "product_events_name_check"),
|
||||
(
|
||||
"product_event_daily_rollups",
|
||||
"product_event_daily_rollups_name_check",
|
||||
),
|
||||
] {
|
||||
let definition =
|
||||
normalize_definition(&constraint_expression(connection, table, constraint).await?);
|
||||
for event_name in IMPORT_EVENT_NAMES {
|
||||
if !definition.contains(event_name) {
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_context_columns(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
for (name, data_type, nullable) in CONTEXT_COLUMNS {
|
||||
let row = query(
|
||||
"select data_type, is_nullable, column_default, datetime_precision, collation_name
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema()
|
||||
and table_name = 'onboarding_import_selections'
|
||||
and column_name = $1",
|
||||
)
|
||||
.bind(name)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let Some(row) = row else {
|
||||
return Err(schema_error(15));
|
||||
};
|
||||
let actual_type = row
|
||||
.try_get::<String, _>("data_type")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let actual_nullable = row
|
||||
.try_get::<String, _>("is_nullable")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let default = row
|
||||
.try_get::<Option<String>, _>("column_default")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let 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 actual_type != *data_type
|
||||
|| actual_nullable != if *nullable { "YES" } else { "NO" }
|
||||
|| default.is_some()
|
||||
|| (*data_type == "timestamp with time zone" && precision != Some(6))
|
||||
|| collation.is_some()
|
||||
{
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_context_constraints(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
for (name, kind, required) in [
|
||||
(
|
||||
"onboarding_import_selections_pkey",
|
||||
"p",
|
||||
&["primarykeyworkspace_id"][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_workspace_id_fkey",
|
||||
"f",
|
||||
&[
|
||||
"foreignkeyworkspace_id",
|
||||
"referencesworkspacesid",
|
||||
"ondeletecascade",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_operation_fk",
|
||||
"f",
|
||||
&[
|
||||
"foreignkeyworkspace_id,selected_operation_id",
|
||||
"referencesoperationsworkspace_id,id",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_application_fk",
|
||||
"f",
|
||||
&[
|
||||
"foreignkeyworkspace_id,application_idempotency_key",
|
||||
"referencesimport_plan_applicationsworkspace_id,idempotency_key",
|
||||
"ondeletecascade",
|
||||
][..],
|
||||
),
|
||||
] {
|
||||
let definition = constraint_definition(connection, name).await?;
|
||||
if !constraint_is_type(connection, name, kind).await? {
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
for snippet in required {
|
||||
if !definition.contains(snippet) {
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
}
|
||||
}
|
||||
// `ON DELETE NO ACTION` is the FK default and Postgres omits it from
|
||||
// `pg_get_constraintdef`; assert the raw delete action instead so a
|
||||
// selected Operation hard-delete cannot silently cascade the report.
|
||||
if constraint_delete_action(connection, "onboarding_import_selections_operation_fk")
|
||||
.await?
|
||||
.as_deref()
|
||||
!= Some("a")
|
||||
{
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
for (name, required) in [
|
||||
(
|
||||
"onboarding_import_selections_application_key_check",
|
||||
&[
|
||||
"octet_lengthapplication_idempotency_key>=1",
|
||||
"octet_lengthapplication_idempotency_key<=256",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_plan_digest_check",
|
||||
&["plan_digest~'^[0-9a-f]{64}$'"][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_version_check",
|
||||
&[
|
||||
"selected_operation_versionisnull",
|
||||
"selected_operation_version>0",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"onboarding_import_selections_selection_shape_check",
|
||||
&["selected_operation_idisnull", "selected_atisnull"][..],
|
||||
),
|
||||
] {
|
||||
let definition = normalize_definition(
|
||||
&constraint_expression(connection, "onboarding_import_selections", name).await?,
|
||||
);
|
||||
if required
|
||||
.iter()
|
||||
.any(|snippet| !definition.contains(&normalize_definition(snippet)))
|
||||
{
|
||||
return Err(schema_error(15));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_context_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method,
|
||||
i.indisvalid, i.indisready, i.indisunique, i.indnkeyatts,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
|
||||
pg_get_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 = 'onboarding_import_selections_operation_idx'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref()
|
||||
== Some("onboarding_import_selections")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref()
|
||||
== Some("selected_operation_id")
|
||||
&& row
|
||||
.try_get::<Option<String>, _>("predicate")
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_none()
|
||||
});
|
||||
if valid { Ok(()) } else { Err(schema_error(15)) }
|
||||
}
|
||||
|
||||
async fn constraint_definition(
|
||||
connection: &mut PgConnection,
|
||||
constraint: &str,
|
||||
) -> Result<String, MigrationError> {
|
||||
query(
|
||||
"select 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 = 'onboarding_import_selections'
|
||||
and c.conname = $1",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.ok_or_else(|| schema_error(15))?
|
||||
.try_get::<String, _>("definition")
|
||||
.map(|definition| normalize_definition(&definition))
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn constraint_delete_action(
|
||||
connection: &mut PgConnection,
|
||||
constraint: &str,
|
||||
) -> Result<Option<String>, MigrationError> {
|
||||
query(
|
||||
"select c.confdeltype::text as action
|
||||
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 = 'onboarding_import_selections'
|
||||
and c.conname = $1",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.map(|row| {
|
||||
row.try_get::<String, _>("action")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn constraint_is_type(
|
||||
connection: &mut PgConnection,
|
||||
constraint: &str,
|
||||
kind: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
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 = 'onboarding_import_selections'
|
||||
and c.conname = $1
|
||||
and c.contype = $2
|
||||
) as present",
|
||||
)
|
||||
.bind(constraint)
|
||||
.bind(kind)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn named_constraint_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
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 = $1
|
||||
and c.conname = $2
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthKind, AuthProfile, DescriptorId,
|
||||
ExecutionErrorCode, ExportMode, InvitationToken, InvocationLevel, InvocationLog,
|
||||
InvocationLogId, InvocationSource, InvocationStatus, MembershipRole, OnboardingProjection,
|
||||
Operation, OperationId, OperationSecurityLevel, OperationStatus, PlatformApiKey,
|
||||
PlatformApiKeyId, ProductEvent, ProductEventId, ProductEventKind, Protocol, SampleId, Secret,
|
||||
SecretId, SecretVersion, ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId,
|
||||
UserSessionId, Workspace, WorkspaceId,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, DescriptorId, ExecutionErrorCode,
|
||||
ExportMode, InvitationToken, InvocationLevel, InvocationLog, InvocationLogId, InvocationSource,
|
||||
InvocationStatus, MembershipRole, OnboardingProjection, Operation, OperationId,
|
||||
OperationSecurityLevel, OperationStatus, PlatformApiKey, PlatformApiKeyId, ProductEvent,
|
||||
ProductEventId, ProductEventKind, Protocol, SampleId, Secret, SecretId, SecretVersion,
|
||||
ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId, UserSessionId, Workspace,
|
||||
WorkspaceId,
|
||||
};
|
||||
use crank_mapping::MappingSet;
|
||||
use crank_schema::Schema;
|
||||
@@ -48,8 +48,17 @@ mod artifact_source;
|
||||
|
||||
pub use artifact_source::*;
|
||||
|
||||
mod import_plan;
|
||||
|
||||
pub use import_plan::*;
|
||||
|
||||
mod onboarding_import;
|
||||
|
||||
pub use onboarding_import::*;
|
||||
|
||||
define_registry_id!(YamlImportJobId);
|
||||
define_registry_id!(ImportJobId);
|
||||
define_registry_id!(ImportPlanId);
|
||||
define_registry_id!(WorkspaceUpstreamId);
|
||||
|
||||
pub type RegistryOperation = Operation<Schema, MappingSet>;
|
||||
@@ -648,29 +657,6 @@ pub enum ImportConflictMode {
|
||||
pub struct ImportOperationDraft {
|
||||
pub operation_key: String,
|
||||
pub operation: RegistryOperation,
|
||||
/// The effective single-scheme requirement selected for this operation.
|
||||
/// The registry checks it against the referenced profile inside Apply.
|
||||
pub auth_requirement: Option<ImportAuthRequirement>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum ImportAuthRequirement {
|
||||
Bearer,
|
||||
Basic,
|
||||
ApiKeyHeader { parameter_name: String },
|
||||
ApiKeyQuery { parameter_name: String },
|
||||
}
|
||||
|
||||
impl ImportAuthRequirement {
|
||||
pub const fn kind(&self) -> AuthKind {
|
||||
match self {
|
||||
Self::Bearer => AuthKind::Bearer,
|
||||
Self::Basic => AuthKind::Basic,
|
||||
Self::ApiKeyHeader { .. } => AuthKind::ApiKeyHeader,
|
||||
Self::ApiKeyQuery { .. } => AuthKind::ApiKeyQuery,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegisterOnboardingImportContextRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub application_idempotency_key: &'a str,
|
||||
pub plan_digest: &'a str,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SelectOnboardingImportDraftRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub application_idempotency_key: &'a str,
|
||||
pub plan_digest: &'a str,
|
||||
pub operation_id: &'a OperationId,
|
||||
pub operation_version: u32,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// A projection and its durable import context read from one authoritative
|
||||
/// registry transaction/snapshot. Pairing them avoids returning a projection
|
||||
/// revision that belongs to an older context state.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OnboardingSnapshot {
|
||||
pub projection: OnboardingProjection,
|
||||
pub import_context: Option<OnboardingImportContext>,
|
||||
}
|
||||
|
||||
/// Result of recording a presentation/completion milestone together with the
|
||||
/// import context read from the same transaction. Returning both avoids a
|
||||
/// second post-projection pool read that could pair a revision with a newer
|
||||
/// context.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OnboardingEventSnapshot {
|
||||
pub accepted: bool,
|
||||
pub snapshot: OnboardingSnapshot,
|
||||
}
|
||||
|
||||
/// Durable workspace import context resolved from an immutable committed
|
||||
/// apply report. The report and choices are read-only evidence; only the
|
||||
/// selected operation/version and its timestamps live in mutable state.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OnboardingImportContext {
|
||||
pub application_idempotency_key: String,
|
||||
pub plan_digest: String,
|
||||
pub report: Value,
|
||||
pub choices: Vec<OnboardingImportChoice>,
|
||||
pub selected_operation_id: Option<OperationId>,
|
||||
pub selected_operation_version: Option<u32>,
|
||||
pub drift: Option<OnboardingImportDrift>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OnboardingImportChoice {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub outcome: String,
|
||||
pub operation_id: Option<String>,
|
||||
pub version: Option<u32>,
|
||||
pub reason: Option<String>,
|
||||
pub selectable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OnboardingImportDrift {
|
||||
pub reason: String,
|
||||
pub current_operation_version: Option<u32>,
|
||||
}
|
||||
@@ -1,12 +1,26 @@
|
||||
mod catalog;
|
||||
mod cleanup;
|
||||
mod legacy_auth;
|
||||
mod plan_apply;
|
||||
mod semantic;
|
||||
use cleanup::{cleanup_source_ids, detach_source_if_unreferenced_in_transaction};
|
||||
use semantic::plan_digest_from_payload;
|
||||
|
||||
use super::*;
|
||||
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
||||
use crate::{
|
||||
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope,
|
||||
ImportOperationDraft, ImportPlan, ImportPlanId,
|
||||
};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{AuthConfig, AuthProfile, AuthProfileId, SecretId};
|
||||
use std::collections::BTreeMap;
|
||||
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 = 16 * 1024 * 1024;
|
||||
const MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const DANGLING_OPENAPI_SOURCE_GRACE: time::Duration = time::Duration::minutes(5);
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -81,6 +95,224 @@ 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 v2 = request
|
||||
.payload
|
||||
.get("schema_version")
|
||||
.and_then(Value::as_str)
|
||||
== Some("import-plan-v2");
|
||||
if v2 {
|
||||
semantic::validate_v2_metadata(request.payload)?;
|
||||
plan_apply::validate_v2_creation(&request, &digest)?;
|
||||
if request
|
||||
.payload
|
||||
.get("plan_reference")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(request.id.as_str())
|
||||
|| request.payload.get("job_id").and_then(Value::as_str)
|
||||
!= Some(request.job_id.as_str())
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "identity" });
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
});
|
||||
}
|
||||
if v2 {
|
||||
semantic::validate_v2_sources(request.payload, &preview_payload)?;
|
||||
}
|
||||
|
||||
sqlx::query("select id from workspaces where id = $1 for update")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
if v2
|
||||
&& request
|
||||
.payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(
|
||||
catalog::catalog_revision(&mut *transaction, request.workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: request.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
// 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<'_>,
|
||||
@@ -135,11 +367,12 @@ impl PostgresRegistry {
|
||||
// bounded source identities and must not roll back the terminal
|
||||
// state because some other payload field was corrupted.
|
||||
for source_id in cleanup_source_ids(&payload) {
|
||||
let _ = detach_source_in_transaction(
|
||||
let _ = detach_source_if_unreferenced_in_transaction(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
&source_id,
|
||||
*request.finished_at,
|
||||
&[request.id.as_str().to_owned()],
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
@@ -205,18 +438,26 @@ impl PostgresRegistry {
|
||||
.bind(limit)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await?;
|
||||
let mut expired_ids = Vec::with_capacity(expired.len());
|
||||
let expired_ids = expired
|
||||
.iter()
|
||||
.map(|row| row.try_get::<String, _>("id"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut detached_sources = 0;
|
||||
for row in &expired {
|
||||
expired_ids.push(row.try_get::<String, _>("id")?);
|
||||
let workspace_id = WorkspaceId::new(row.try_get::<String, _>("workspace_id")?);
|
||||
let payload = row.try_get::<Value, _>("preview_payload")?;
|
||||
// The job itself is expired regardless of whether a legacy or
|
||||
// corrupt payload can be decoded. Do not let one bad row roll
|
||||
// back cleanup for every workspace.
|
||||
for source_id in cleanup_source_ids(&payload) {
|
||||
if detach_source_in_transaction(&mut transaction, &workspace_id, &source_id, now)
|
||||
.await?
|
||||
if detach_source_if_unreferenced_in_transaction(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
&source_id,
|
||||
now,
|
||||
&expired_ids,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
detached_sources += 1;
|
||||
}
|
||||
@@ -251,7 +492,13 @@ impl PostgresRegistry {
|
||||
j.preview_payload -> 'source' ->> 'source_id' = s.source_id
|
||||
or exists (
|
||||
select 1
|
||||
from jsonb_array_elements(coalesce(j.preview_payload -> 'dependencies', '[]'::jsonb)) d
|
||||
from jsonb_array_elements(
|
||||
case
|
||||
when jsonb_typeof(j.preview_payload -> 'dependencies') = 'array'
|
||||
then j.preview_payload -> 'dependencies'
|
||||
else '[]'::jsonb
|
||||
end
|
||||
) d
|
||||
where d ->> 'source_id' = s.source_id
|
||||
)
|
||||
)
|
||||
@@ -390,9 +637,7 @@ async fn apply_import_job_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the complete binding set before the first Operation insert.
|
||||
// This transaction-level check closes the gap between preview and Apply.
|
||||
validate_import_auth_bindings(tx, request.workspace_id, request.operations).await?;
|
||||
legacy_auth::verify_legacy_import_auth(tx, request.workspace_id, request.operations).await?;
|
||||
|
||||
let mut result = ImportJobApplyResult {
|
||||
application_key: request.application_key.to_owned(),
|
||||
@@ -491,190 +736,6 @@ async fn apply_import_job_transaction(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn validate_import_auth_bindings(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operations: &[crate::ImportOperationDraft],
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut requirements_by_profile = BTreeMap::<String, Vec<&crate::ImportAuthRequirement>>::new();
|
||||
for draft in operations {
|
||||
match (
|
||||
draft.auth_requirement.as_ref(),
|
||||
draft.operation.execution_config.auth_profile_ref.as_ref(),
|
||||
) {
|
||||
(None, None) => {}
|
||||
(Some(requirement), Some(profile_id)) => requirements_by_profile
|
||||
.entry(profile_id.as_str().to_owned())
|
||||
.or_default()
|
||||
.push(requirement),
|
||||
_ => return Err(RegistryError::ImportAuthBindingUnavailable),
|
||||
}
|
||||
}
|
||||
if requirements_by_profile.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Read the current workspace's profile config first to discover Secret
|
||||
// references. Secret rows are locked in stable order before profile rows,
|
||||
// matching save_auth_profile's secret-then-profile write order.
|
||||
let mut observed_profiles = BTreeMap::<String, AuthProfile>::new();
|
||||
let mut secret_ids = BTreeMap::<String, SecretId>::new();
|
||||
for profile_id in requirements_by_profile.keys() {
|
||||
let profile = read_import_auth_profile(tx, workspace_id, profile_id, false)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
let requirements = &requirements_by_profile[profile_id];
|
||||
if !requirements
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, &profile, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
for secret_id in profile.config.secret_ids() {
|
||||
secret_ids
|
||||
.entry(secret_id.as_str().to_owned())
|
||||
.or_insert_with(|| secret_id.clone());
|
||||
}
|
||||
observed_profiles.insert(profile_id.clone(), profile);
|
||||
}
|
||||
|
||||
for secret_id in secret_ids.values() {
|
||||
let row = sqlx::query(
|
||||
"select s.status,
|
||||
exists (
|
||||
select 1 from secret_versions sv
|
||||
where sv.secret_id = s.id and sv.version = s.current_version
|
||||
) as has_current_version
|
||||
from secrets s
|
||||
where s.workspace_id = $1 and s.id = $2
|
||||
for update of s",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
};
|
||||
if row.try_get::<String, _>("status")? != "active"
|
||||
|| !row.try_get::<bool, _>("has_current_version")?
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
// The profile may have changed while its former Secret rows were being
|
||||
// locked. Lock profile rows only after Secrets (the order used by profile
|
||||
// updates), then compare the binding config and revalidate compatibility.
|
||||
for (profile_id, observed) in &observed_profiles {
|
||||
let current = read_import_auth_profile(tx, workspace_id, profile_id, true)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
if current.id != observed.id
|
||||
|| current.workspace_id != observed.workspace_id
|
||||
|| current.kind != observed.kind
|
||||
|| current.config != observed.config
|
||||
|| !requirements_by_profile[profile_id]
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, ¤t, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_import_auth_profile(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile_id: &str,
|
||||
lock: bool,
|
||||
) -> Result<Option<AuthProfile>, RegistryError> {
|
||||
let query = if lock {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2
|
||||
for update"
|
||||
} else {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2"
|
||||
};
|
||||
let row = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
super::build_auth_profile(
|
||||
row.try_get("id")?,
|
||||
row.try_get("workspace_id")?,
|
||||
row.try_get("name")?,
|
||||
row.try_get("kind")?,
|
||||
row.try_get("config_json")?,
|
||||
row.try_get("created_at")?,
|
||||
row.try_get("updated_at")?,
|
||||
)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn auth_profile_matches(
|
||||
expected_profile_id: &str,
|
||||
profile: &AuthProfile,
|
||||
requirement: &crate::ImportAuthRequirement,
|
||||
) -> bool {
|
||||
if profile.id != AuthProfileId::new(expected_profile_id)
|
||||
|| profile.kind != profile.config.kind()
|
||||
|| profile.kind != requirement.kind()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match (requirement, &profile.config) {
|
||||
(crate::ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||
| (crate::ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => {
|
||||
is_valid_auth_header_name(&config.header_name)
|
||||
&& is_valid_auth_header_name(parameter_name)
|
||||
&& config.header_name.eq_ignore_ascii_case(parameter_name)
|
||||
}
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => config.param_name == *parameter_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_auth_header_name(value: &str) -> bool {
|
||||
value.len() <= 128
|
||||
&& !value.is_empty()
|
||||
&& value.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric()
|
||||
|| matches!(
|
||||
byte,
|
||||
b'!' | b'#'
|
||||
| b'$'
|
||||
| b'%'
|
||||
| b'&'
|
||||
| b'\''
|
||||
| b'*'
|
||||
| b'+'
|
||||
| b'-'
|
||||
| b'.'
|
||||
| b'^'
|
||||
| b'_'
|
||||
| b'`'
|
||||
| b'|'
|
||||
| b'~'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_source_envelope(
|
||||
source: &ImportJobSourceEnvelope,
|
||||
preview_payload: &Value,
|
||||
@@ -778,29 +839,6 @@ fn dependencies_from_payload(
|
||||
Ok(dependencies)
|
||||
}
|
||||
|
||||
fn cleanup_source_ids(payload: &Value) -> Vec<ArtifactSourceId> {
|
||||
let mut identities = std::collections::BTreeSet::new();
|
||||
if let Some(source_id) = payload
|
||||
.pointer("/source/source_id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| value.len() <= 132)
|
||||
{
|
||||
identities.insert(source_id.to_owned());
|
||||
}
|
||||
if let Some(dependencies) = payload.get("dependencies").and_then(Value::as_array) {
|
||||
for source_id in dependencies
|
||||
.iter()
|
||||
.take(MAX_IMPORT_JOB_DOCUMENTS)
|
||||
.filter_map(|item| item.get("source_id"))
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|value| value.len() <= 132)
|
||||
{
|
||||
identities.insert(source_id.to_owned());
|
||||
}
|
||||
}
|
||||
identities.into_iter().map(ArtifactSourceId::new).collect()
|
||||
}
|
||||
|
||||
async fn detach_source_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
@@ -863,3 +901,81 @@ 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")?,
|
||||
})
|
||||
}
|
||||
|
||||
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.payload == *request.payload
|
||||
&& 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,68 @@
|
||||
use super::*;
|
||||
|
||||
// A bounded metadata read, independent of the size of stored schemas/Drafts.
|
||||
const MAX_IMPORT_CATALOG_ENTRIES: i64 = 10_000;
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn list_import_catalog_names(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Vec<String>, RegistryError> {
|
||||
let names = sqlx::query_scalar::<_, String>(
|
||||
"select name from operations where workspace_id = $1 order by name limit $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
if names.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
/// Deterministic workspace catalog identity for naming and version targets.
|
||||
/// Referenced authentication state is separately bound in plan snapshots.
|
||||
pub async fn import_catalog_revision(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<String, RegistryError> {
|
||||
catalog_revision(&self.pool, workspace_id, false).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn catalog_revision<'c, E>(
|
||||
executor: E,
|
||||
workspace_id: &WorkspaceId,
|
||||
lock: bool,
|
||||
) -> Result<String, RegistryError>
|
||||
where
|
||||
E: Executor<'c, Database = Postgres>,
|
||||
{
|
||||
let query = if lock {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2 for share"
|
||||
} else {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2"
|
||||
};
|
||||
let rows = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(executor)
|
||||
.await?;
|
||||
if rows.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
let metadata = rows
|
||||
.iter()
|
||||
.map(|row| row.try_get::<Value, _>("metadata"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(serde_json::to_vec(&metadata)?)
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use super::*;
|
||||
|
||||
const OPENAPI_SOURCE_ID_PREFIX: &str = "src_openapi_";
|
||||
|
||||
pub(super) fn cleanup_source_ids(payload: &Value) -> Vec<ArtifactSourceId> {
|
||||
let mut identities = std::collections::BTreeSet::new();
|
||||
if let Some(source_id) = payload
|
||||
.pointer("/source/source_id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| value.len() <= 132 && value.starts_with(OPENAPI_SOURCE_ID_PREFIX))
|
||||
{
|
||||
identities.insert(source_id.to_owned());
|
||||
}
|
||||
if let Some(dependencies) = payload.get("dependencies").and_then(Value::as_array) {
|
||||
for source_id in dependencies
|
||||
.iter()
|
||||
.take(MAX_IMPORT_JOB_DOCUMENTS)
|
||||
.filter_map(|item| item.get("source_id"))
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|value| value.len() <= 132 && value.starts_with(OPENAPI_SOURCE_ID_PREFIX))
|
||||
{
|
||||
identities.insert(source_id.to_owned());
|
||||
}
|
||||
}
|
||||
identities.into_iter().map(ArtifactSourceId::new).collect()
|
||||
}
|
||||
|
||||
pub(super) async fn detach_source_if_unreferenced_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
source_id: &ArtifactSourceId,
|
||||
detached_at: OffsetDateTime,
|
||||
excluded_job_ids: &[String],
|
||||
) -> Result<bool, RegistryError> {
|
||||
let detached = sqlx::query(
|
||||
"update artifact_sources
|
||||
set lifecycle = 'detached', updated_at = $1, detached_at = $1
|
||||
where workspace_id = $2 and source_id = $3
|
||||
and lifecycle = 'active'
|
||||
and not exists (
|
||||
select 1
|
||||
from import_jobs j
|
||||
where j.workspace_id = $2
|
||||
and not (j.id = any($4::text[]))
|
||||
and (
|
||||
j.preview_payload -> 'source' ->> 'source_id' = $3
|
||||
or exists (
|
||||
select 1
|
||||
from jsonb_array_elements(
|
||||
case
|
||||
when jsonb_typeof(j.preview_payload -> 'dependencies') = 'array'
|
||||
then j.preview_payload -> 'dependencies'
|
||||
else '[]'::jsonb
|
||||
end
|
||||
) d
|
||||
where d ->> 'source_id' = $3
|
||||
)
|
||||
)
|
||||
)",
|
||||
)
|
||||
.bind(detached_at)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(source_id.as_str())
|
||||
.bind(excluded_job_ids)
|
||||
.execute(&mut **transaction)
|
||||
.await?
|
||||
.rows_affected();
|
||||
Ok(detached == 1)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
use super::*;
|
||||
|
||||
/// Legacy Apply has no plan-time auth snapshot, but it still must not create
|
||||
/// operations from a stale or cross-workspace profile reference. Lock and
|
||||
/// validate every referenced profile and its secret rows before inserting
|
||||
/// any operation; ImportPlan Apply performs the stricter snapshot comparison.
|
||||
pub(super) async fn verify_legacy_import_auth(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operations: &[ImportOperationDraft],
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut profiles = std::collections::BTreeMap::<String, Vec<String>>::new();
|
||||
let mut profile_snapshots = std::collections::BTreeMap::<String, (String, Value)>::new();
|
||||
for draft in operations {
|
||||
if let Some(profile_id) = draft.operation.execution_config.auth_profile_ref.as_ref() {
|
||||
profiles.entry(profile_id.as_str().to_owned()).or_default();
|
||||
}
|
||||
}
|
||||
if profiles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let unavailable = |id: &str| RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id: id.to_owned(),
|
||||
};
|
||||
let profile_ids: Vec<String> = profiles.keys().cloned().collect();
|
||||
for profile_id in &profile_ids {
|
||||
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_id_value = row.try_get::<String, _>("id")?;
|
||||
let profile_kind = row.try_get::<String, _>("kind")?;
|
||||
let config_json = row.try_get::<Value, _>("config_json")?;
|
||||
let profile = build_auth_profile(
|
||||
profile_id_value,
|
||||
workspace_id.as_str().to_owned(),
|
||||
row.try_get::<String, _>("name")?,
|
||||
profile_kind.clone(),
|
||||
config_json.clone(),
|
||||
row.try_get::<OffsetDateTime, _>("created_at")?,
|
||||
row.try_get::<OffsetDateTime, _>("updated_at")?,
|
||||
)
|
||||
.map_err(|_| unavailable(profile_id))?;
|
||||
if profile.kind != profile.config.kind() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
let mut secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret| secret.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
secret_ids.sort();
|
||||
secret_ids.dedup();
|
||||
profiles.insert(profile_id.clone(), secret_ids);
|
||||
profile_snapshots.insert(row.try_get::<String, _>("id")?, (profile_kind, config_json));
|
||||
}
|
||||
|
||||
let secret_ids: std::collections::BTreeSet<String> =
|
||||
profiles.values().flatten().cloned().collect();
|
||||
for secret_id in secret_ids {
|
||||
let owner = profiles
|
||||
.iter()
|
||||
.find_map(|(profile_id, ids)| ids.contains(&secret_id).then_some(profile_id.as_str()))
|
||||
.unwrap_or_default();
|
||||
let row = sqlx::query(
|
||||
"select status, current_version
|
||||
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")?;
|
||||
let version: i32 = row.try_get("current_version")?;
|
||||
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(version)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if status != "active" || !version_present {
|
||||
return Err(unavailable(owner));
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the established secret-then-profile lock order. The profile may
|
||||
// have changed while secret rows were locked; compare its live config and
|
||||
// secret set with the initial read before Apply mutates any operation.
|
||||
for profile_id in profile_ids {
|
||||
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 kind: String = row.try_get("kind")?;
|
||||
let config: Value = row.try_get("config_json")?;
|
||||
let Some((expected_kind, expected_config)) = profile_snapshots.get(&profile_id) else {
|
||||
return Err(unavailable(&profile_id));
|
||||
};
|
||||
if &kind != expected_kind || &config != expected_config {
|
||||
return Err(unavailable(&profile_id));
|
||||
}
|
||||
let profile = build_auth_profile(
|
||||
row.try_get::<String, _>("id")?,
|
||||
workspace_id.as_str().to_owned(),
|
||||
row.try_get::<String, _>("name")?,
|
||||
kind,
|
||||
config,
|
||||
row.try_get::<OffsetDateTime, _>("created_at")?,
|
||||
row.try_get::<OffsetDateTime, _>("updated_at")?,
|
||||
)
|
||||
.map_err(|_| unavailable(&profile_id))?;
|
||||
let mut live_secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret| secret.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
live_secret_ids.sort();
|
||||
live_secret_ids.dedup();
|
||||
if profiles.get(&profile_id) != Some(&live_secret_ids) {
|
||||
return Err(unavailable(&profile_id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
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 revalidate;
|
||||
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 = 2_000;
|
||||
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` (16 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;
|
||||
|
||||
pub(super) fn validate_v2_creation(
|
||||
request: &CreateImportPlanRequest<'_>,
|
||||
digest: &str,
|
||||
) -> Result<(), RegistryError> {
|
||||
let fingerprint =
|
||||
request
|
||||
.payload
|
||||
.get("fingerprint")
|
||||
.ok_or(RegistryError::InvalidImportPlan {
|
||||
field: "fingerprint",
|
||||
})?;
|
||||
let validation = ApplyImportPlanRequest {
|
||||
workspace_id: request.workspace_id,
|
||||
plan_id: request.id,
|
||||
plan_digest: digest,
|
||||
idempotency_key: "creation-validation",
|
||||
verified_fingerprint: fingerprint,
|
||||
applied_at: request.created_at,
|
||||
};
|
||||
read_and_validate_plan_material(
|
||||
request.payload,
|
||||
&validation,
|
||||
digest,
|
||||
request.job_id.as_str(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::catalog::catalog_revision(&mut **tx, request.workspace_id, true)
|
||||
.await
|
||||
.map_err(fail)?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(fail(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
// 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,654 @@
|
||||
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>,
|
||||
#[serde(default)]
|
||||
pub(crate) catalog_revision: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) excluded_reasons: Vec<StoredExcludedReason>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredExcludedReason {
|
||||
pub(crate) key: String,
|
||||
#[serde(default)]
|
||||
pub(crate) name: String,
|
||||
pub(crate) reason: String,
|
||||
}
|
||||
|
||||
impl StoredExcludedReason {
|
||||
pub(crate) fn name_or_key(&self) -> &str {
|
||||
if self.name.is_empty() {
|
||||
&self.key
|
||||
} else {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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>,
|
||||
/// Source-derived selected scheme requirement. Apply checks the live
|
||||
/// profile against this independently of the captured profile snapshot,
|
||||
/// closing a profile-change race between compatibility lookup and capture.
|
||||
#[serde(default)]
|
||||
pub(crate) auth_requirement: Option<StoredAuthRequirement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct StoredAuthRequirement {
|
||||
pub(crate) kind: String,
|
||||
#[serde(default)]
|
||||
pub(crate) parameter_name: Option<String>,
|
||||
}
|
||||
|
||||
/// 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());
|
||||
}
|
||||
let v2 = payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2");
|
||||
let selected_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 512 };
|
||||
let all_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 1_024 };
|
||||
if payload
|
||||
.pointer("/selection/selected")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
|| payload
|
||||
.pointer("/selection/all")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > all_limit)
|
||||
|| payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
{
|
||||
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 !matches!(
|
||||
plan.schema_version.as_str(),
|
||||
PLAN_PAYLOAD_SCHEMA_VERSION | "import-plan-v2"
|
||||
) || plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
|| plan.job_id != stored_job_id
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
super::super::semantic::validate_v2_metadata(payload).map_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();
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let findings = payload
|
||||
.pointer("/findings/candidates")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(corrupt)?;
|
||||
let keys = findings
|
||||
.iter()
|
||||
.map(|item| {
|
||||
if !item.get("findings").is_some_and(Value::is_array) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
item.get("key").and_then(Value::as_str).ok_or_else(corrupt)
|
||||
})
|
||||
.collect::<Result<BTreeSet<_>, _>>()?;
|
||||
let expected = plan
|
||||
.selection
|
||||
.all
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if keys != expected || keys.len() != findings.len() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let reasons = plan
|
||||
.excluded_reasons
|
||||
.iter()
|
||||
.map(|item| &item.key)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if reasons != excluded
|
||||
|| reasons.len() != plan.excluded_reasons.len()
|
||||
|| plan.excluded_reasons.iter().any(|item| {
|
||||
item.reason.is_empty() || item.reason.len() > MAX_IMPORT_PLAN_REASON_BYTES
|
||||
})
|
||||
|| !plan
|
||||
.excluded_reasons
|
||||
.windows(2)
|
||||
.all(|items| items[0].key < items[1].key)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.selection.mode == "partial"
|
||||
&& plan
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|candidate| candidate.state != "actionable")
|
||||
{
|
||||
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 (&candidate.auth_requirement, &auth_ref, actionable) {
|
||||
(Some(requirement), Some(_), true)
|
||||
if requirement.kind == "unconstrained"
|
||||
&& requirement.parameter_name.is_none()
|
||||
&& decision.action == "new_version" => {}
|
||||
(Some(requirement), Some(_), true)
|
||||
if matches!(requirement.kind.as_str(), "bearer" | "basic")
|
||||
&& requirement.parameter_name.is_none()
|
||||
|| matches!(
|
||||
requirement.kind.as_str(),
|
||||
"api_key_header" | "api_key_query"
|
||||
) && requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| !name.is_empty() && name.len() <= 256) => {}
|
||||
(None, None, _) | (None, Some(_), false) => {}
|
||||
_ => 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(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::StoredExcludedReason;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn historic_excluded_reason_without_display_name_deserializes_and_uses_key() {
|
||||
let reason: StoredExcludedReason = serde_json::from_value(json!({
|
||||
"key": "GET /legacy",
|
||||
"reason": "not_selected"
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(reason.name, "");
|
||||
assert_eq!(reason.name_or_key(), "GET /legacy");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
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: plan
|
||||
.excluded_reasons
|
||||
.iter()
|
||||
.find(|item| item.key == *key)
|
||||
.map(|item| item.name_or_key())
|
||||
.unwrap_or(key)
|
||||
.to_owned(),
|
||||
outcome: ImportPlanCandidateOutcome::Excluded,
|
||||
operation_id: None,
|
||||
version: None,
|
||||
reason: Some(
|
||||
plan.excluded_reasons
|
||||
.iter()
|
||||
.find(|item| item.key == *key)
|
||||
.map(|item| item.reason.clone())
|
||||
.unwrap_or_else(|| "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,114 @@
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Reopens immutable plan evidence without applying it or writing a report.
|
||||
/// The result is current validation evidence, never a promise about a later
|
||||
/// Apply; Apply independently repeats its checks inside its transaction.
|
||||
pub async fn revalidate_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
verified_fingerprint: &Value,
|
||||
) -> Result<(), RegistryError> {
|
||||
let plan = self
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanNotFound {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
})?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id,
|
||||
plan_id,
|
||||
plan_digest: &plan.digest,
|
||||
idempotency_key: "read-only-revalidation",
|
||||
verified_fingerprint,
|
||||
applied_at: &now,
|
||||
};
|
||||
let material = read_and_validate_plan_material(
|
||||
&plan.payload,
|
||||
&request,
|
||||
&plan.digest,
|
||||
plan.job_id.as_str(),
|
||||
)?;
|
||||
let job = self
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: plan.job_id.as_str().to_owned(),
|
||||
})?;
|
||||
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanJobTerminal {
|
||||
job_id: job.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
verify_job_source_consistency(&job.preview_payload, &material, plan_id.as_str())?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let mut envelopes = material
|
||||
.dependencies
|
||||
.iter()
|
||||
.chain(std::iter::once(&material.source))
|
||||
.map(|source| ImportJobSourceEnvelope {
|
||||
source_id: ArtifactSourceId::new(source.source_id.clone()),
|
||||
digest: ArtifactRef::parse(&source.digest).expect("material was validated"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
envelopes.sort_by(|a, b| a.source_id.as_str().cmp(b.source_id.as_str()));
|
||||
for envelope in &envelopes {
|
||||
lock_and_verify_envelope(&mut tx, workspace_id, envelope).await?;
|
||||
}
|
||||
lock_and_verify_auth(&mut tx, workspace_id, &material.candidates).await?;
|
||||
if material.schema_version == "import-plan-v2"
|
||||
&& material.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::super::catalog::catalog_revision(&mut *tx, workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
for candidate in &material.candidates {
|
||||
if let Some(target) = &candidate.target {
|
||||
let row = sqlx::query("select name, status, current_draft_version, latest_published_version from operations where workspace_id = $1 and id = $2 for share")
|
||||
.bind(workspace_id.as_str()).bind(&target.operation_id).fetch_optional(&mut *tx).await?;
|
||||
let matching = match row {
|
||||
Some(row) => {
|
||||
row.try_get::<String, _>("name")? == target.name
|
||||
&& deserialize_enum_text::<OperationStatus>(
|
||||
row.try_get("status")?,
|
||||
"status",
|
||||
)? == target.expected_state.status
|
||||
&& row.try_get::<i32, _>("current_draft_version")? as u32
|
||||
== target.expected_state.current_draft_version
|
||||
&& row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| value as u32)
|
||||
== target.expected_state.latest_published_version
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !matching {
|
||||
return Err(RegistryError::ImportPlanTargetStale {
|
||||
operation_id: target.operation_id.clone(),
|
||||
});
|
||||
}
|
||||
} else if candidate.state == "actionable"
|
||||
&& operation_name_exists(&mut tx, workspace_id, &candidate.name).await?
|
||||
{
|
||||
return Err(RegistryError::ImportPlanNameConflict {
|
||||
name: candidate.name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
tx.rollback().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
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::{StoredAuthRequirement, 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();
|
||||
let mut requirements: BTreeMap<String, Vec<&StoredAuthRequirement>> = 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()))?;
|
||||
let requirement = candidate
|
||||
.auth_requirement
|
||||
.as_ref()
|
||||
.ok_or_else(|| unavailable(ref_id.as_str()))?;
|
||||
requirements
|
||||
.entry(ref_id.as_str().to_owned())
|
||||
.or_default()
|
||||
.push(requirement);
|
||||
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));
|
||||
}
|
||||
if requirements.get(profile_id).is_none_or(|expected| {
|
||||
expected
|
||||
.iter()
|
||||
.any(|requirement| !auth_config_satisfies_requirement(&profile.config, requirement))
|
||||
}) {
|
||||
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(())
|
||||
}
|
||||
|
||||
fn auth_config_satisfies_requirement(
|
||||
config: &crank_core::AuthConfig,
|
||||
requirement: &material::StoredAuthRequirement,
|
||||
) -> bool {
|
||||
use crank_core::AuthConfig;
|
||||
match (config, requirement.kind.as_str()) {
|
||||
(_, "unconstrained") => requirement.parameter_name.is_none(),
|
||||
(AuthConfig::Bearer(_), "bearer") | (AuthConfig::Basic(_), "basic") => {
|
||||
requirement.parameter_name.is_none()
|
||||
}
|
||||
(AuthConfig::ApiKeyHeader(config), "api_key_header") => requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| config.header_name.eq_ignore_ascii_case(name)),
|
||||
(AuthConfig::ApiKeyQuery(config), "api_key_query") => requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| config.param_name == name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::auth_config_satisfies_requirement;
|
||||
use crate::postgres::import_job::plan_apply::material::StoredAuthRequirement;
|
||||
use crank_core::{ApiKeyHeaderAuthConfig, AuthConfig, SecretId};
|
||||
|
||||
#[test]
|
||||
fn source_selected_header_name_is_rechecked_against_live_profile_config() {
|
||||
let source_requirement = StoredAuthRequirement {
|
||||
kind: "api_key_header".to_owned(),
|
||||
parameter_name: Some("X-A".to_owned()),
|
||||
};
|
||||
let compatible = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "x-a".to_owned(),
|
||||
secret_id: SecretId::new("secret_a"),
|
||||
});
|
||||
let changed_after_resolution = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-B".to_owned(),
|
||||
secret_id: SecretId::new("secret_a"),
|
||||
});
|
||||
|
||||
assert!(auth_config_satisfies_requirement(
|
||||
&compatible,
|
||||
&source_requirement
|
||||
));
|
||||
assert!(!auth_config_satisfies_requirement(
|
||||
&changed_after_resolution,
|
||||
&source_requirement
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use super::*;
|
||||
|
||||
/// 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.
|
||||
pub(super) fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let limit = if payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2") {
|
||||
MAX_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
} else {
|
||||
MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
};
|
||||
if serde_json::to_vec(payload)?.len() > limit {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(&canonical_material(payload))?;
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_sources(payload: &Value, preview: &Value) -> Result<(), RegistryError> {
|
||||
let dependency_set =
|
||||
|value: &Value| -> Result<std::collections::BTreeSet<(String, String)>, RegistryError> {
|
||||
Ok(dependencies_from_payload(value)?
|
||||
.iter()
|
||||
.map(|source| {
|
||||
(
|
||||
source.source_id.as_str().to_owned(),
|
||||
source.digest.as_str().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
};
|
||||
if source_from_payload(payload)? != source_from_payload(preview)?
|
||||
|| dependency_set(payload)? != dependency_set(preview)?
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "source" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes only server-generated envelope fields from v2 semantic material.
|
||||
/// Paths are explicit: equally named fields in a user schema remain semantic.
|
||||
pub(super) fn canonical_material(payload: &Value) -> Value {
|
||||
let mut material = payload.clone();
|
||||
if payload.get("schema_version").and_then(Value::as_str) != Some("import-plan-v2") {
|
||||
return material;
|
||||
}
|
||||
let object = material.as_object_mut().expect("validated object");
|
||||
object.remove("plan_reference");
|
||||
object.remove("job_id");
|
||||
if let Some(source) = object.get_mut("source").and_then(Value::as_object_mut) {
|
||||
source.remove("source_id");
|
||||
}
|
||||
if let Some(dependencies) = object.get_mut("dependencies").and_then(Value::as_array_mut) {
|
||||
for dependency in dependencies.iter_mut() {
|
||||
if let Some(source) = dependency.as_object_mut() {
|
||||
source.remove("source_id");
|
||||
}
|
||||
}
|
||||
dependencies.sort_by_key(Value::to_string);
|
||||
}
|
||||
if let Some(candidates) = object.get_mut("candidates").and_then(Value::as_array_mut) {
|
||||
for candidate in candidates {
|
||||
let generated = matches!(
|
||||
candidate
|
||||
.pointer("/decision/action")
|
||||
.and_then(Value::as_str),
|
||||
Some("create" | "rename")
|
||||
);
|
||||
if let Some(operation) = candidate
|
||||
.get_mut("operation")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
if generated {
|
||||
operation.remove("id");
|
||||
}
|
||||
operation.remove("created_at");
|
||||
operation.remove("updated_at");
|
||||
operation.remove("published_at");
|
||||
}
|
||||
if let Some(snapshot) = candidate
|
||||
.get_mut("auth_snapshot")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
snapshot.remove("updated_at");
|
||||
if let Some(secrets) = snapshot.get_mut("secrets").and_then(Value::as_array_mut) {
|
||||
for secret in secrets {
|
||||
if let Some(secret) = secret.as_object_mut() {
|
||||
secret.remove("updated_at");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
material
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_metadata(payload: &Value) -> Result<(), RegistryError> {
|
||||
let invalid = || RegistryError::InvalidImportPlan { field: "metadata" };
|
||||
let revision = payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if revision.len() != 64
|
||||
|| !revision
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let matrix = payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if matrix.is_empty() || matrix.len() > 64 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let findings = payload
|
||||
.get("findings")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(invalid)?;
|
||||
if !findings.get("document").is_some_and(Value::is_array)
|
||||
|| !findings.get("candidates").is_some_and(Value::is_array)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::plan_digest_from_payload;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn payload() -> Value {
|
||||
json!({
|
||||
"schema_version": "import-plan-v2", "plan_reference": "plan_a", "job_id": "job_a",
|
||||
"catalog_revision": "a".repeat(64), "support_matrix_version": "1.0.2",
|
||||
"source": {"source_id": "src_a", "digest": format!("sha256:{}", "b".repeat(64))},
|
||||
"dependencies": [{"source_id": "dep_a", "digest": format!("sha256:{}", "c".repeat(64))}],
|
||||
"findings": {"document": [], "candidates": []},
|
||||
"selection": {"mode": "full", "selected": ["GET /a"], "excluded": [], "all": ["GET /a"]},
|
||||
"candidates": [{
|
||||
"key": "GET /a", "decision": {"action": "create"},
|
||||
"operation": {"id": "op_a", "created_at": "time_a", "updated_at": "time_a",
|
||||
"input_schema": {"properties": {"id": {"default": "semantic_id"}, "created_at": {"default": "semantic_time"}}}},
|
||||
"auth_snapshot": {"profile_id": "auth_a", "updated_at": "time_a", "secrets": [
|
||||
{"id": "secret_a", "current_version": 1, "status": "active", "updated_at": "time_a"}
|
||||
]}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_v2_material_ignores_only_identity_envelope_and_runtime_instants() {
|
||||
let first = payload();
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("plan_b");
|
||||
second["job_id"] = json!("job_b");
|
||||
second["source"]["source_id"] = json!("src_b");
|
||||
second["dependencies"][0]["source_id"] = json!("dep_b");
|
||||
second["candidates"][0]["operation"]["id"] = json!("op_b");
|
||||
second["candidates"][0]["operation"]["created_at"] = json!("time_b");
|
||||
second["candidates"][0]["operation"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["secrets"][0]["updated_at"] = json!("time_b");
|
||||
assert_eq!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_semantic_changes_and_schema_fields_named_like_runtime_fields_change_digest() {
|
||||
let first = payload();
|
||||
for pointer in [
|
||||
"/catalog_revision",
|
||||
"/support_matrix_version",
|
||||
"/source/digest",
|
||||
"/candidates/0/decision/action",
|
||||
"/candidates/0/auth_snapshot/secrets/0/current_version",
|
||||
"/candidates/0/operation/input_schema/properties/id/default",
|
||||
"/candidates/0/operation/input_schema/properties/created_at/default",
|
||||
] {
|
||||
let mut changed = first.clone();
|
||||
*changed.pointer_mut(pointer).unwrap() = json!("changed");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&changed).unwrap(),
|
||||
"{pointer}"
|
||||
);
|
||||
}
|
||||
let mut target = first.clone();
|
||||
target["candidates"][0]["decision"]["action"] = json!("new_version");
|
||||
let mut changed_target = target.clone();
|
||||
changed_target["candidates"][0]["operation"]["id"] = json!("different_existing_target");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&target).unwrap(),
|
||||
plan_digest_from_payload(&changed_target).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_payload_digest_still_covers_runtime_and_identity_fields() {
|
||||
let mut first = payload();
|
||||
first["schema_version"] = json!("import-plan-v1");
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("other");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_payload_budget_grows_without_changing_the_legacy_budget() {
|
||||
let mut large =
|
||||
json!({"schema_version": "import-plan-v1", "evidence": "x".repeat(5 * 1024 * 1024)});
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
large["schema_version"] = json!("import-plan-v2");
|
||||
assert!(plan_digest_from_payload(&large).is_ok());
|
||||
large["evidence"] = json!("x".repeat(16 * 1024 * 1024));
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod import_job;
|
||||
mod master_key;
|
||||
mod observability;
|
||||
mod onboarding;
|
||||
mod onboarding_import;
|
||||
mod operation;
|
||||
mod operation_artifact;
|
||||
mod operation_published;
|
||||
@@ -51,14 +52,16 @@ use crate::{
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus,
|
||||
MembershipRecord, OnboardingMilestoneResult, OnboardingPresentationMilestone,
|
||||
OperationAgentRef, OperationSampleMetadata, OperationStateExpectation, OperationSummary,
|
||||
OperationUsageSummary, OperationVersionRecord, PlatformApiKeyRecord, ProductEventRecord,
|
||||
PublishAgentRequest, PublishRequest, PublishedAgentCatalog, PublishedAgentTool,
|
||||
RecordOnboardingCompletionRequest, RecordOnboardingMilestoneRequest, RegistryOperation,
|
||||
RotateSecretRequest, SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest,
|
||||
SaveAuthProfileRequest, SaveDescriptorMetadataRequest, SaveSampleMetadataRequest,
|
||||
SaveWorkspaceUpstreamRequest, SecretRecord, SecretVersionRecord, SessionRecord,
|
||||
MembershipRecord, OnboardingEventSnapshot, OnboardingImportChoice, OnboardingImportContext,
|
||||
OnboardingImportDrift, OnboardingMilestoneResult, OnboardingPresentationMilestone,
|
||||
OnboardingSnapshot, OperationAgentRef, OperationSampleMetadata, OperationStateExpectation,
|
||||
OperationSummary, OperationUsageSummary, OperationVersionRecord, PlatformApiKeyRecord,
|
||||
ProductEventRecord, PublishAgentRequest, PublishRequest, PublishedAgentCatalog,
|
||||
PublishedAgentTool, RecordOnboardingCompletionRequest, RecordOnboardingMilestoneRequest,
|
||||
RegisterOnboardingImportContextRequest, RegistryOperation, RotateSecretRequest,
|
||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
||||
SecretRecord, SecretVersionRecord, SelectOnboardingImportDraftRequest, SessionRecord,
|
||||
SkippedImportOperation, UpdateWorkspaceRequest, UsageAgentBreakdown,
|
||||
UsageOperationBreakdown, UsageOutcomeBreakdown, UsageQuery, UsageRollupRecord,
|
||||
UsageSummary, UsageTimelinePoint, WorkspaceMembershipRecord, WorkspaceRecord,
|
||||
|
||||
@@ -186,7 +186,7 @@ impl PostgresRegistry {
|
||||
field: "operation_version",
|
||||
value: i64::MAX,
|
||||
})?;
|
||||
let should_anchor_onboarding = request.log.source
|
||||
let mut should_anchor_onboarding = request.log.source
|
||||
== crank_core::InvocationSource::AgentToolCall
|
||||
&& request.log.status == crank_core::InvocationStatus::Ok
|
||||
&& request.log.execution_stage == Some(crank_core::ExecutionStage::Runtime)
|
||||
@@ -200,6 +200,21 @@ impl PostgresRegistry {
|
||||
.bind(request.log.workspace_id.as_str())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
// A durable import context governs terminal anchoring: a pending
|
||||
// context suppresses the generic anchor entirely, and an explicit
|
||||
// selection only anchors the exact selected Operation/version.
|
||||
// Without an import context the existing generic anchoring stays.
|
||||
if let Some((selected_operation_id, selected_operation_version)) =
|
||||
super::onboarding_import::onboarding_import_selection_in_transaction(
|
||||
&mut transaction,
|
||||
&request.log.workspace_id,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
should_anchor_onboarding = selected_operation_id.as_deref()
|
||||
== Some(request.log.operation_id.as_str())
|
||||
&& selected_operation_version == Some(operation_version);
|
||||
}
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into invocation_logs (
|
||||
@@ -404,6 +419,14 @@ impl PostgresRegistry {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
// Record import funnel publication/activation at the authoritative
|
||||
// call boundary (idempotent; no-op without a selected import).
|
||||
super::onboarding_import::record_import_funnel_milestones_in_transaction(
|
||||
&mut transaction,
|
||||
&request.log.workspace_id,
|
||||
request.log.created_at,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
@@ -7,20 +7,58 @@ use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Bounded whole-transaction retries for transient PostgreSQL serialization
|
||||
/// failures. A `REPEATABLE READ` transaction that reads a row later updated by
|
||||
/// a concurrent transaction aborts with SQLSTATE `40001`; retrying from the
|
||||
/// start re-reads a consistent snapshot instead of continuing a partial,
|
||||
/// aborted transaction.
|
||||
const MAX_ONBOARDING_SERIALIZATION_ATTEMPTS: usize = 4;
|
||||
|
||||
/// Whether a registry error is a transient PostgreSQL serialization/deadlock
|
||||
/// failure that must abort and retry the whole transaction.
|
||||
pub(super) fn is_onboarding_serialization_failure(error: &RegistryError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
RegistryError::Storage(sqlx::Error::Database(database))
|
||||
if matches!(database.code().as_deref(), Some("40001") | Some("40P01"))
|
||||
)
|
||||
}
|
||||
|
||||
/// Begins an onboarding transaction with a true, consistent snapshot.
|
||||
///
|
||||
/// The onboarding projection aggregates many relations and is paired with a
|
||||
/// separately-read durable import context; the default `READ COMMITTED` would
|
||||
/// let each statement see a different snapshot and pair a revision with newer
|
||||
/// choices. `REPEATABLE READ` fixes one snapshot for the whole transaction.
|
||||
pub(super) async fn begin_onboarding_transaction<'a>(
|
||||
pool: &'a sqlx::PgPool,
|
||||
) -> Result<Transaction<'a, Postgres>, RegistryError> {
|
||||
let mut transaction = pool.begin().await?;
|
||||
sqlx::query("set transaction isolation level repeatable read")
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
const ONBOARDING_PROJECTION_SQL: &str = r#"
|
||||
with selection_state as (
|
||||
select operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
from onboarding_selections
|
||||
where workspace_id = $1
|
||||
), import_selection as (
|
||||
select application_idempotency_key, plan_digest, selected_operation_id,
|
||||
selected_operation_version, registered_at, selected_at
|
||||
from onboarding_import_selections
|
||||
where workspace_id = $1
|
||||
), operation_candidates as (
|
||||
select o.id, o.current_draft_version, o.latest_published_version, o.updated_at,
|
||||
coalesce(ss.operation_version, o.latest_published_version, o.current_draft_version) as target_version,
|
||||
coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version) as target_version,
|
||||
(o.status <> 'archived') as operation_active,
|
||||
exists (
|
||||
select 1 from invocation_logs l
|
||||
where l.workspace_id = $1 and l.operation_id = o.id
|
||||
and l.operation_version = coalesce(ss.operation_version, o.latest_published_version, o.current_draft_version)
|
||||
and l.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version)
|
||||
and (ss.test_log_id is null or l.id = ss.test_log_id)
|
||||
and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz)
|
||||
and l.source = 'admin_test_run' and l.status = 'ok'
|
||||
@@ -30,14 +68,14 @@ with selection_state as (
|
||||
exists (
|
||||
select 1 from published_operations po
|
||||
where po.operation_id = o.id
|
||||
and po.version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and po.version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
) as published,
|
||||
exists (
|
||||
select 1 from agent_operation_bindings b
|
||||
join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version
|
||||
join agents a on a.id = pa.agent_id
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and b.enabled and a.workspace_id = $1 and a.status = 'published'
|
||||
@@ -49,7 +87,7 @@ with selection_state as (
|
||||
join agents a on a.id = pa.agent_id
|
||||
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -67,7 +105,7 @@ with selection_state as (
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = o.id and l.operation_version = b.operation_version
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -91,7 +129,7 @@ with selection_state as (
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = o.id and l.operation_version = b.operation_version
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -106,7 +144,14 @@ with selection_state as (
|
||||
) as historical_first_call
|
||||
from operations o
|
||||
left join selection_state ss on true
|
||||
where o.workspace_id = $1 and (ss.operation_id is null or o.id = ss.operation_id)
|
||||
left join import_selection imp on true
|
||||
where o.workspace_id = $1
|
||||
and (ss.operation_id is null or o.id = ss.operation_id)
|
||||
and (
|
||||
ss.operation_id is not null
|
||||
or (imp.selected_operation_id is not null and o.id = imp.selected_operation_id)
|
||||
or (imp.selected_operation_id is null and not exists (select 1 from import_selection))
|
||||
)
|
||||
), selected_operation as (
|
||||
select o.id, o.current_draft_version, o.latest_published_version, o.updated_at, o.target_version,
|
||||
o.operation_active
|
||||
@@ -248,9 +293,39 @@ select os.id as operation_id, os.operation_active, os.tested, os.published, os.p
|
||||
coalesce(sk.expires_at::text, ''), coalesce(sk.key_active::text, ''),
|
||||
coalesce(fc.id, ''), coalesce(es.event_count::text, ''),
|
||||
coalesce(es.last_event_at::text, ''), coalesce(es.last_event_id, ''),
|
||||
coalesce((select evidence_after::text from selection_state), ''),
|
||||
coalesce((select selected_at::text from selection_state), '')
|
||||
), 0) & 9223372036854775807) as revision
|
||||
coalesce((select evidence_after::text from selection_state), ''),
|
||||
coalesce((select selected_at::text from selection_state), ''),
|
||||
coalesce((select application_idempotency_key from import_selection), ''),
|
||||
coalesce((select plan_digest from import_selection), ''),
|
||||
coalesce((select selected_operation_id from import_selection), ''),
|
||||
coalesce((select selected_operation_version::text from import_selection), ''),
|
||||
coalesce((select registered_at::text from import_selection), ''),
|
||||
coalesce((select selected_at::text from import_selection), ''),
|
||||
coalesce((select o.current_draft_version::text from operations o
|
||||
where o.workspace_id = $1
|
||||
and o.id = (select selected_operation_id from import_selection)), ''),
|
||||
coalesce((
|
||||
select string_agg(
|
||||
candidate.operation_id || ':' || coalesce(o.status, 'missing') || ':' ||
|
||||
coalesce(o.current_draft_version::text, 'null'),
|
||||
',' order by candidate.operation_id
|
||||
)
|
||||
from (
|
||||
select distinct outcome ->> 'operation_id' as operation_id
|
||||
from import_plan_applications a
|
||||
cross join lateral jsonb_array_elements(a.report -> 'outcomes') as outcome
|
||||
where a.workspace_id = $1
|
||||
and a.idempotency_key = (
|
||||
select application_idempotency_key from import_selection
|
||||
)
|
||||
and a.plan_digest = (select plan_digest from import_selection)
|
||||
and outcome ->> 'outcome' in ('created', 'versioned', 'renamed')
|
||||
and outcome ->> 'operation_id' is not null
|
||||
) candidate
|
||||
left join operations o
|
||||
on o.workspace_id = $1 and o.id = candidate.operation_id
|
||||
), '')
|
||||
), 0) & 9007199254740991) as revision
|
||||
from event_state es
|
||||
left join operation_state os on true
|
||||
left join selected_agent sa on true
|
||||
@@ -259,41 +334,120 @@ select os.id as operation_id, os.operation_active, os.tested, os.published, os.p
|
||||
"#;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Retries a whole onboarding transaction on transient serialization
|
||||
/// failures. Each attempt starts from scratch, so an aborted transaction is
|
||||
/// never continued partially. Exhausted retries surface as a truthful
|
||||
/// revision conflict so the client reloads and revalidates.
|
||||
pub(super) async fn with_onboarding_retry<T, F, Fut>(
|
||||
&self,
|
||||
mut operation: F,
|
||||
) -> Result<T, RegistryError>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T, RegistryError>>,
|
||||
{
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match operation().await {
|
||||
Err(error) if is_onboarding_serialization_failure(&error) => {
|
||||
attempt += 1;
|
||||
if attempt >= MAX_ONBOARDING_SERIALIZATION_ATTEMPTS {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures the workspace enters the server-owned onboarding cohort exactly once.
|
||||
pub async fn ensure_onboarding_eligibility(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let eligible = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
"onboarding:eligible:v1",
|
||||
)
|
||||
.await?;
|
||||
let eligible_since = if let Some(record) = eligible {
|
||||
record.event.eligible_since.unwrap_or(occurred_at)
|
||||
} else {
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingEligible,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(occurred_at),
|
||||
idempotency_key: "onboarding:eligible:v1".to_owned(),
|
||||
Ok(self
|
||||
.ensure_onboarding_eligibility_snapshot(workspace_id, occurred_at)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Ensures eligibility and returns the authoritative projection together
|
||||
/// with the durable import context from the same locked transaction.
|
||||
pub async fn ensure_onboarding_eligibility_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let eligible_since = ensure_onboarding_eligible_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
)
|
||||
.await?;
|
||||
super::onboarding_import::record_import_funnel_milestones_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
occurred_at,
|
||||
)
|
||||
.await?;
|
||||
let mut projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if projection.completed && !projection.was_completed {
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingCompleted,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection.first_call_at.unwrap_or(occurred_at),
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id)
|
||||
.await?;
|
||||
}
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
occurred_at
|
||||
};
|
||||
let mut projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if projection.completed && !projection.was_completed {
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Records the server-owned completion once the authoritative projection is terminal.
|
||||
pub async fn ensure_onboarding_completion(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
_occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if !projection.completed {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
}
|
||||
let Some(eligible_since) = projection.eligible_since else {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
};
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
@@ -303,55 +457,20 @@ impl PostgresRegistry {
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection.first_call_at.unwrap_or(occurred_at),
|
||||
occurred_at: projection.first_call_at.ok_or(
|
||||
RegistryError::InvalidExecutionRecord {
|
||||
field: "onboarding.first_call_at",
|
||||
},
|
||||
)?,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
projection =
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
}
|
||||
|
||||
/// Records the server-owned completion once the authoritative projection is terminal.
|
||||
pub async fn ensure_onboarding_completion(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
_occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if !projection.completed {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
}
|
||||
let Some(eligible_since) = projection.eligible_since else {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
};
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingCompleted,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection
|
||||
.first_call_at
|
||||
.ok_or(RegistryError::InvalidExecutionRecord {
|
||||
field: "onboarding.first_call_at",
|
||||
})?,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
Ok(projection)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_onboarding_projection(
|
||||
@@ -365,44 +484,107 @@ impl PostgresRegistry {
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
/// Reads the authoritative projection and the durable import context from
|
||||
/// one workspace-locked transaction so revision and context cannot diverge.
|
||||
pub async fn get_onboarding_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let snapshot =
|
||||
get_onboarding_snapshot_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(snapshot)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn reset_onboarding_selection(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if current.revision != expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into onboarding_selections (
|
||||
workspace_id, operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
) values ($1, null, null, null, null, null, null, null, $2, null)
|
||||
on conflict (workspace_id) do update
|
||||
set operation_id = null, operation_version = null, agent_id = null,
|
||||
catalog_revision = null, platform_api_key_id = null,
|
||||
invocation_log_id = null, test_log_id = null,
|
||||
evidence_after = excluded.evidence_after, selected_at = null",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
Ok(self
|
||||
.reset_onboarding_selection_snapshot(workspace_id, expected_revision, occurred_at)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Resets the terminal/import selection and returns the resulting
|
||||
/// projection with its (now absent) import context from one snapshot.
|
||||
pub async fn reset_onboarding_selection_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if current.revision != expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into onboarding_selections (
|
||||
workspace_id, operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
) values ($1, null, null, null, null, null, null, null, $2, null)
|
||||
on conflict (workspace_id) do update
|
||||
set operation_id = null, operation_version = null, agent_id = null,
|
||||
catalog_revision = null, platform_api_key_id = null,
|
||||
invocation_log_id = null, test_log_id = null,
|
||||
evidence_after = excluded.evidence_after, selected_at = null",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
// Reset clears the durable import context as well, but keeps the
|
||||
// existing evidence boundary (evidence_after) intact.
|
||||
sqlx::query("delete from onboarding_import_selections where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn record_onboarding_milestone(
|
||||
&self,
|
||||
request: RecordOnboardingMilestoneRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
let snapshot = self.record_onboarding_milestone_snapshot(request).await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: snapshot.accepted,
|
||||
projection: snapshot.snapshot.projection,
|
||||
})
|
||||
}
|
||||
|
||||
/// Records a presentation milestone and returns the projection and import
|
||||
/// context read from the same transaction, avoiding a post-mutation pool
|
||||
/// read that could pair the revision with a newer context.
|
||||
pub async fn record_onboarding_milestone_snapshot(
|
||||
&self,
|
||||
request: RecordOnboardingMilestoneRequest<'_>,
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
let kind = match request.milestone {
|
||||
OnboardingPresentationMilestone::Eligible => ProductEventKind::OnboardingEligible,
|
||||
OnboardingPresentationMilestone::Started => ProductEventKind::OnboardingStarted,
|
||||
@@ -410,7 +592,7 @@ impl PostgresRegistry {
|
||||
OnboardingPresentationMilestone::Dismissed => ProductEventKind::OnboardingDismissed,
|
||||
OnboardingPresentationMilestone::Abandoned => ProductEventKind::OnboardingAbandoned,
|
||||
};
|
||||
self.record_onboarding_event(
|
||||
self.record_onboarding_event_snapshot(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
kind,
|
||||
@@ -426,7 +608,20 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: RecordOnboardingCompletionRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
self.record_onboarding_event(
|
||||
let snapshot = self.record_onboarding_completion_snapshot(request).await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: snapshot.accepted,
|
||||
projection: snapshot.snapshot.projection,
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the authoritative completion and returns the projection and
|
||||
/// import context from the same transaction.
|
||||
pub async fn record_onboarding_completion_snapshot(
|
||||
&self,
|
||||
request: RecordOnboardingCompletionRequest<'_>,
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
self.record_onboarding_event_snapshot(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
ProductEventKind::OnboardingCompleted,
|
||||
@@ -439,7 +634,7 @@ impl PostgresRegistry {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn record_onboarding_event(
|
||||
async fn record_onboarding_event_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
event_id: &ProductEventId,
|
||||
@@ -448,60 +643,114 @@ impl PostgresRegistry {
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
eligible_since: Option<OffsetDateTime>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
if idempotency_key.starts_with(PRODUCT_EVENT_SERVER_IDEMPOTENCY_PREFIX) {
|
||||
return Err(RegistryError::InvalidExecutionRecord {
|
||||
field: "product_event.reserved_idempotency_key",
|
||||
});
|
||||
}
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if kind == ProductEventKind::OnboardingCompleted && !current.completed {
|
||||
return Err(RegistryError::OnboardingIncomplete);
|
||||
}
|
||||
let event = ProductEvent {
|
||||
id: event_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: eligible_since.is_some(),
|
||||
eligible_since,
|
||||
idempotency_key: idempotency_key.to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
if current.revision != expected_revision {
|
||||
let replay = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
idempotency_key,
|
||||
)
|
||||
.await?;
|
||||
if replay.is_some_and(|record| event.is_semantic_replay_of(&record.event)) {
|
||||
transaction.commit().await?;
|
||||
return Ok(OnboardingMilestoneResult {
|
||||
accepted: false,
|
||||
projection: current,
|
||||
});
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if kind == ProductEventKind::OnboardingCompleted && !current.completed {
|
||||
return Err(RegistryError::OnboardingIncomplete);
|
||||
}
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let outcome =
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
let event = ProductEvent {
|
||||
id: event_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: eligible_since.is_some(),
|
||||
eligible_since,
|
||||
idempotency_key: idempotency_key.to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
if current.revision != expected_revision {
|
||||
let replay =
|
||||
super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
idempotency_key,
|
||||
)
|
||||
.await?;
|
||||
if replay.is_some_and(|record| event.is_semantic_replay_of(&record.event)) {
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
return Ok(OnboardingEventSnapshot {
|
||||
accepted: false,
|
||||
snapshot: OnboardingSnapshot {
|
||||
projection: current,
|
||||
import_context,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let outcome =
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: outcome == AppendProductEventOutcome::Recorded,
|
||||
projection,
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingEventSnapshot {
|
||||
accepted: outcome == AppendProductEventOutcome::Recorded,
|
||||
snapshot: OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
},
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn lock_onboarding_workspace(
|
||||
/// Ensures the workspace is in the server-owned onboarding eligible cohort and
|
||||
/// returns its authoritative `eligible_since` timestamp. Idempotent: the
|
||||
/// cohort event is created at most once per workspace.
|
||||
pub(super) async fn ensure_onboarding_eligible_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OffsetDateTime, RegistryError> {
|
||||
let eligible = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
transaction,
|
||||
workspace_id,
|
||||
"onboarding:eligible:v1",
|
||||
)
|
||||
.await?;
|
||||
if let Some(record) = eligible {
|
||||
return Ok(record.event.eligible_since.unwrap_or(occurred_at));
|
||||
}
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingEligible,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(occurred_at),
|
||||
idempotency_key: "onboarding:eligible:v1".to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(transaction, &event).await?;
|
||||
Ok(occurred_at)
|
||||
}
|
||||
|
||||
pub(super) async fn lock_onboarding_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -529,6 +778,22 @@ pub(super) async fn get_onboarding_projection_in_transaction(
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
pub(super) async fn get_onboarding_snapshot_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
let projection = get_onboarding_projection_in_transaction(transaction, workspace_id).await?;
|
||||
let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
}
|
||||
|
||||
fn map_projection(
|
||||
workspace_id: &WorkspaceId,
|
||||
row: &sqlx::postgres::PgRow,
|
||||
|
||||
@@ -0,0 +1,749 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crank_core::{
|
||||
OnboardingProjection, OnboardingStepId, OperationId, PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
ProductEvent, ProductEventId, ProductEventKind, WorkspaceId,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::onboarding::{
|
||||
begin_onboarding_transaction, ensure_onboarding_eligible_in_transaction,
|
||||
get_onboarding_projection_in_transaction, lock_onboarding_workspace,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
const MAX_APPLICATION_KEY_BYTES: usize = 128;
|
||||
|
||||
struct ImportContextRow {
|
||||
application_idempotency_key: String,
|
||||
plan_digest: String,
|
||||
selected_operation_id: Option<String>,
|
||||
selected_operation_version: Option<i32>,
|
||||
}
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Registers the durable workspace import context for an already committed
|
||||
/// immutable apply report.
|
||||
///
|
||||
/// Only the application identity (`application_idempotency_key`,
|
||||
/// `plan_digest`) is persisted; the report itself is never copied. The
|
||||
/// context starts pending (no selected operation) and suppresses generic
|
||||
/// automatic Operation selection until the administrator explicitly picks
|
||||
/// one actionable Draft. Exact re-registration is idempotent and keeps any
|
||||
/// existing selection.
|
||||
pub async fn register_onboarding_import_context(
|
||||
&self,
|
||||
request: RegisterOnboardingImportContextRequest<'_>,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
Ok(self
|
||||
.register_onboarding_import_context_snapshot(request)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Registers the durable context and returns the authoritative projection
|
||||
/// together with the context read from the same transaction/snapshot.
|
||||
pub async fn register_onboarding_import_context_snapshot(
|
||||
&self,
|
||||
request: RegisterOnboardingImportContextRequest<'_>,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
validate_application_key(request.application_idempotency_key)?;
|
||||
validate_plan_digest(request.plan_digest)?;
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, request.workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, request.workspace_id)
|
||||
.await?;
|
||||
if current.revision != request.expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let Some(application) = load_application(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
request.application_idempotency_key,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
};
|
||||
if application.0 != request.plan_digest || !report_is_applied(&application.1) {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
}
|
||||
let actionable = report_has_actionable_outcome(&application.1);
|
||||
let existing = load_context(&mut transaction, request.workspace_id).await?;
|
||||
let same_identity = existing.as_ref().is_some_and(|context| {
|
||||
context.application_idempotency_key == request.application_idempotency_key
|
||||
&& context.plan_digest == request.plan_digest
|
||||
});
|
||||
if !same_identity {
|
||||
sqlx::query(
|
||||
"insert into onboarding_import_selections (
|
||||
workspace_id, application_idempotency_key, plan_digest,
|
||||
selected_operation_id, selected_operation_version,
|
||||
registered_at, selected_at
|
||||
) values ($1, $2, $3, null, null, $4, null)
|
||||
on conflict (workspace_id) do update
|
||||
set application_idempotency_key = excluded.application_idempotency_key,
|
||||
plan_digest = excluded.plan_digest,
|
||||
selected_operation_id = null,
|
||||
selected_operation_version = null,
|
||||
registered_at = excluded.registered_at,
|
||||
selected_at = null",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.application_idempotency_key)
|
||||
.bind(request.plan_digest)
|
||||
.bind(request.occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
if actionable {
|
||||
record_import_eligible_in_transaction(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
request.application_idempotency_key,
|
||||
request.occurred_at,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, request.workspace_id)
|
||||
.await?;
|
||||
let import_context = get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Explicitly anchors one actionable Draft produced by the registered
|
||||
/// immutable apply report as the OpenAPI onboarding target.
|
||||
///
|
||||
/// The selection must carry the exact registered application identity and
|
||||
/// plan digest, and the Draft must be the operation's live current Draft
|
||||
/// with the exact strict version. Forged, cross-workspace, published,
|
||||
/// archived or drifted choices fail without mutation.
|
||||
pub async fn select_onboarding_import_draft(
|
||||
&self,
|
||||
request: SelectOnboardingImportDraftRequest<'_>,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
Ok(self
|
||||
.select_onboarding_import_draft_snapshot(request)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Selects one actionable imported Draft and returns the authoritative
|
||||
/// projection together with the context from the same snapshot.
|
||||
pub async fn select_onboarding_import_draft_snapshot(
|
||||
&self,
|
||||
request: SelectOnboardingImportDraftRequest<'_>,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
validate_application_key(request.application_idempotency_key)?;
|
||||
validate_plan_digest(request.plan_digest)?;
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, request.workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, request.workspace_id)
|
||||
.await?;
|
||||
if current.revision != request.expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let Some(context) = load_context(&mut transaction, request.workspace_id).await? else {
|
||||
return Err(RegistryError::OnboardingImportContextUnavailable);
|
||||
};
|
||||
if context.application_idempotency_key != request.application_idempotency_key
|
||||
|| context.plan_digest != request.plan_digest
|
||||
{
|
||||
return Err(RegistryError::OnboardingImportContextUnavailable);
|
||||
}
|
||||
let Some(application) = load_application(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
request.application_idempotency_key,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
};
|
||||
if application.0 != request.plan_digest || !report_is_applied(&application.1) {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
}
|
||||
if successful_outcome_version(&application.1, request.operation_id.as_str())
|
||||
!= Some(request.operation_version)
|
||||
{
|
||||
return Err(RegistryError::OnboardingImportDraftUnavailable);
|
||||
}
|
||||
// Lock the exact selected Draft row and validate exact
|
||||
// workspace/status/version under that lock so a concurrent archive
|
||||
// or edit cannot slip between validation and selection.
|
||||
match current_draft_version(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
request.operation_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some((status, version))
|
||||
if status == "draft" && version == request.operation_version => {}
|
||||
_ => return Err(RegistryError::OnboardingImportDraftUnavailable),
|
||||
}
|
||||
sqlx::query(
|
||||
"update onboarding_import_selections
|
||||
set selected_operation_id = $2,
|
||||
selected_operation_version = $3,
|
||||
selected_at = $4
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.operation_id.as_str())
|
||||
.bind(i32::try_from(request.operation_version).map_err(|_| {
|
||||
RegistryError::InvalidNumericValue {
|
||||
field: "onboarding.import.operation_version",
|
||||
value: i64::from(request.operation_version),
|
||||
}
|
||||
})?)
|
||||
.bind(request.occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
record_import_funnel_milestones_in_transaction(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
request.occurred_at,
|
||||
)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, request.workspace_id)
|
||||
.await?;
|
||||
let import_context = get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
request.workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Resolves the complete authoritative import context for a workspace,
|
||||
/// re-reading the immutable report from `import_plan_applications` by the
|
||||
/// durable identity and verifying the exact plan digest. Pending context
|
||||
/// has `selected_operation_id`/`selected_operation_version` as `None`.
|
||||
pub async fn get_onboarding_import_context(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Option<OnboardingImportContext>, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
let context =
|
||||
get_onboarding_import_context_in_transaction(&mut transaction, workspace_id)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(context)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the durable import context and re-reads the immutable report from
|
||||
/// `import_plan_applications` on the same transaction/snapshot as the caller's
|
||||
/// projection, so report/choices/drift can never pair with a stale revision.
|
||||
pub(super) async fn get_onboarding_import_context_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Option<OnboardingImportContext>, RegistryError> {
|
||||
let Some(context) = sqlx::query(
|
||||
"select application_idempotency_key, plan_digest, selected_operation_id,
|
||||
selected_operation_version
|
||||
from onboarding_import_selections
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let application_idempotency_key: String = context.try_get("application_idempotency_key")?;
|
||||
let plan_digest: String = context.try_get("plan_digest")?;
|
||||
let selected_operation_id: Option<String> = context.try_get("selected_operation_id")?;
|
||||
let selected_operation_version: Option<i32> = context.try_get("selected_operation_version")?;
|
||||
let Some(application) = sqlx::query(
|
||||
"select plan_digest, report
|
||||
from import_plan_applications
|
||||
where workspace_id = $1 and idempotency_key = $2
|
||||
for key share",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&application_idempotency_key)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?
|
||||
else {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
};
|
||||
let stored_digest: String = application.try_get("plan_digest")?;
|
||||
if stored_digest != plan_digest {
|
||||
return Err(RegistryError::OnboardingImportApplicationUnavailable);
|
||||
}
|
||||
let report: Value = application.try_get("report")?;
|
||||
let live = live_operations(transaction, workspace_id).await?;
|
||||
let choices = report_choices(&report, &live);
|
||||
let selected_operation_id = selected_operation_id.map(OperationId::new);
|
||||
let selected_operation_version = selected_operation_version
|
||||
.map(|value| {
|
||||
u32::try_from(value).map_err(|_| RegistryError::InvalidNumericValue {
|
||||
field: "onboarding.import.operation_version",
|
||||
value: i64::from(value),
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let drift = compute_drift(
|
||||
&live,
|
||||
selected_operation_id.as_ref(),
|
||||
selected_operation_version,
|
||||
);
|
||||
Ok(Some(OnboardingImportContext {
|
||||
application_idempotency_key,
|
||||
plan_digest,
|
||||
report,
|
||||
choices,
|
||||
selected_operation_id,
|
||||
selected_operation_version,
|
||||
drift,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Records the import funnel conversion milestones exactly once per durable
|
||||
/// application identity. `import-to-publish` requires publication of the
|
||||
/// explicitly selected operation/version and `agent activation` requires the
|
||||
/// authoritative successful public first call on that exact operation/version
|
||||
/// (a published Agent alone never counts). Properties stay redacted and there
|
||||
/// is no outbound egress: these are local append-only rows feeding local daily
|
||||
/// rollups.
|
||||
pub(super) async fn record_import_funnel_milestones_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<(), RegistryError> {
|
||||
let Some(context) = load_context(transaction, workspace_id).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let (Some(operation_id), Some(operation_version)) = (
|
||||
context.selected_operation_id,
|
||||
context.selected_operation_version,
|
||||
) else {
|
||||
return Ok(());
|
||||
};
|
||||
// Published/activated milestones inherit the authoritative server-owned
|
||||
// cohort so their funnel properties always carry `eligible=true` and the
|
||||
// same `eligible_since` as the eligibility denominator.
|
||||
let eligible_since =
|
||||
ensure_onboarding_eligible_in_transaction(transaction, workspace_id, occurred_at).await?;
|
||||
let projection = get_onboarding_projection_in_transaction(transaction, workspace_id).await?;
|
||||
// An existing terminal tuple takes precedence over later import contexts.
|
||||
// Its evidence must never be attributed to a different imported target.
|
||||
if projection.operation_id.as_ref().map(OperationId::as_str) != Some(operation_id.as_str())
|
||||
|| projection.operation_version != u32::try_from(operation_version).ok()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let published = projection
|
||||
.step(OnboardingStepId::PublishOperation)
|
||||
.is_some_and(|step| step.completed);
|
||||
let activated = projection
|
||||
.step(OnboardingStepId::FirstCall)
|
||||
.is_some_and(|step| step.completed);
|
||||
if published {
|
||||
// The conversion is anchored to the exact published version's own
|
||||
// `published_at`, not the observation time.
|
||||
let Some(published_at) = selected_version_published_at(
|
||||
transaction,
|
||||
workspace_id,
|
||||
operation_id.as_str(),
|
||||
operation_version,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
append_funnel_event_with_cohort(
|
||||
transaction,
|
||||
workspace_id,
|
||||
ProductEventKind::OnboardingImportPublished,
|
||||
format!(
|
||||
"onboarding:import-published:v1:{}:{}:{}",
|
||||
context.application_idempotency_key, operation_id, operation_version
|
||||
),
|
||||
published_at,
|
||||
Some(eligible_since),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if activated {
|
||||
// Activation is anchored to the authoritative successful public first
|
||||
// call timestamp from the same projection, not the observation time.
|
||||
let Some(first_call_at) = projection.first_call_at else {
|
||||
return Ok(());
|
||||
};
|
||||
append_funnel_event_with_cohort(
|
||||
transaction,
|
||||
workspace_id,
|
||||
ProductEventKind::OnboardingAgentActivated,
|
||||
format!(
|
||||
"onboarding:agent-activated:v1:{}:{}:{}",
|
||||
context.application_idempotency_key, operation_id, operation_version
|
||||
),
|
||||
first_call_at,
|
||||
Some(eligible_since),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn selected_version_published_at(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operation_id: &str,
|
||||
version: i32,
|
||||
) -> Result<Option<OffsetDateTime>, RegistryError> {
|
||||
sqlx::query_scalar(
|
||||
"select po.published_at
|
||||
from published_operations po
|
||||
join operations o on o.id = po.operation_id and o.workspace_id = $1
|
||||
where po.operation_id = $2 and po.version = $3",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(operation_id)
|
||||
.bind(version)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(RegistryError::from)
|
||||
}
|
||||
|
||||
async fn record_import_eligible_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
application_idempotency_key: &str,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<(), RegistryError> {
|
||||
let eligible_since =
|
||||
ensure_onboarding_eligible_in_transaction(transaction, workspace_id, occurred_at).await?;
|
||||
let idempotency_key = format!(
|
||||
"onboarding:import-eligible:v1:{}",
|
||||
application_idempotency_key
|
||||
);
|
||||
append_funnel_event_with_cohort(
|
||||
transaction,
|
||||
workspace_id,
|
||||
ProductEventKind::OnboardingImportEligible,
|
||||
idempotency_key,
|
||||
occurred_at,
|
||||
Some(eligible_since),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_funnel_event_with_cohort(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
kind: ProductEventKind,
|
||||
idempotency_key: String,
|
||||
occurred_at: OffsetDateTime,
|
||||
eligible_since: Option<OffsetDateTime>,
|
||||
) -> Result<(), RegistryError> {
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: eligible_since.is_some(),
|
||||
eligible_since,
|
||||
idempotency_key,
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(transaction, &event).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the durable import context's explicit selection, if any, for
|
||||
/// terminal-anchor gating. `Some((None, None))` means a pending context that
|
||||
/// suppresses generic anchoring.
|
||||
pub(super) async fn onboarding_import_selection_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Option<(Option<String>, Option<i32>)>, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select selected_operation_id, selected_operation_version
|
||||
from onboarding_import_selections
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
Ok((
|
||||
row.try_get::<Option<String>, _>("selected_operation_id")?,
|
||||
row.try_get::<Option<i32>, _>("selected_operation_version")?,
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn load_context(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Option<ImportContextRow>, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select application_idempotency_key, plan_digest, selected_operation_id,
|
||||
selected_operation_version
|
||||
from onboarding_import_selections
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
Ok(ImportContextRow {
|
||||
application_idempotency_key: row.try_get("application_idempotency_key")?,
|
||||
plan_digest: row.try_get("plan_digest")?,
|
||||
selected_operation_id: row.try_get("selected_operation_id")?,
|
||||
selected_operation_version: row.try_get("selected_operation_version")?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn load_application(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
idempotency_key: &str,
|
||||
) -> Result<Option<(String, Value)>, RegistryError> {
|
||||
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(&mut **transaction)
|
||||
.await?;
|
||||
row.map(|row| Ok((row.try_get("plan_digest")?, row.try_get("report")?)))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn current_draft_version(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operation_id: &str,
|
||||
) -> Result<Option<(String, u32)>, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select status, current_draft_version
|
||||
from operations
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(operation_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let status: String = row.try_get("status")?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let version = u32::try_from(version).map_err(|_| RegistryError::InvalidNumericValue {
|
||||
field: "onboarding.import.operation_version",
|
||||
value: i64::from(version),
|
||||
})?;
|
||||
Ok(Some((status, version)))
|
||||
}
|
||||
|
||||
async fn live_operations(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<HashMap<String, (String, u32)>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select id, status, current_draft_version
|
||||
from operations
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_all(&mut **transaction)
|
||||
.await?;
|
||||
let mut live = HashMap::new();
|
||||
for row in rows {
|
||||
let id: String = row.try_get("id")?;
|
||||
let status: String = row.try_get("status")?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let version = u32::try_from(version).map_err(|_| RegistryError::InvalidNumericValue {
|
||||
field: "onboarding.import.operation_version",
|
||||
value: i64::from(version),
|
||||
})?;
|
||||
live.insert(id, (status, version));
|
||||
}
|
||||
Ok(live)
|
||||
}
|
||||
|
||||
fn report_is_applied(report: &Value) -> bool {
|
||||
report.get("status").and_then(Value::as_str) == Some("applied")
|
||||
}
|
||||
|
||||
fn report_outcomes(report: &Value) -> Vec<&Value> {
|
||||
report
|
||||
.get("outcomes")
|
||||
.and_then(Value::as_array)
|
||||
.map(|outcomes| outcomes.iter().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn outcome_kind(outcome: &Value) -> Option<&str> {
|
||||
outcome.get("outcome").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn is_successful_outcome(outcome: &str) -> bool {
|
||||
matches!(outcome, "created" | "versioned" | "renamed")
|
||||
}
|
||||
|
||||
fn report_has_actionable_outcome(report: &Value) -> bool {
|
||||
report_outcomes(report).into_iter().any(|outcome| {
|
||||
outcome_kind(outcome).is_some_and(is_successful_outcome)
|
||||
&& outcome
|
||||
.get("operation_id")
|
||||
.and_then(Value::as_str)
|
||||
.is_some()
|
||||
&& outcome.get("version").and_then(Value::as_u64).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
fn successful_outcome_version(report: &Value, operation_id: &str) -> Option<u32> {
|
||||
report_outcomes(report).into_iter().find_map(|outcome| {
|
||||
let matches_operation =
|
||||
outcome.get("operation_id").and_then(Value::as_str) == Some(operation_id);
|
||||
let successful = outcome_kind(outcome).is_some_and(is_successful_outcome);
|
||||
if matches_operation && successful {
|
||||
outcome
|
||||
.get("version")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn report_choices(
|
||||
report: &Value,
|
||||
live: &HashMap<String, (String, u32)>,
|
||||
) -> Vec<OnboardingImportChoice> {
|
||||
let mut choices = Vec::new();
|
||||
for outcome in report_outcomes(report) {
|
||||
let Some(outcome_kind) = outcome_kind(outcome) else {
|
||||
continue;
|
||||
};
|
||||
let operation_id = outcome
|
||||
.get("operation_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
let version = match outcome.get("version") {
|
||||
Some(value) if !value.is_null() => value.as_u64().and_then(|v| u32::try_from(v).ok()),
|
||||
_ => None,
|
||||
};
|
||||
let selectable = is_successful_outcome(outcome_kind)
|
||||
&& operation_id
|
||||
.as_deref()
|
||||
.zip(version)
|
||||
.is_some_and(|(operation_id, version)| {
|
||||
live.get(operation_id)
|
||||
.is_some_and(|(status, current)| status == "draft" && *current == version)
|
||||
});
|
||||
choices.push(OnboardingImportChoice {
|
||||
key: outcome
|
||||
.get("key")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
name: outcome
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
outcome: outcome_kind.to_owned(),
|
||||
operation_id,
|
||||
version,
|
||||
reason: outcome
|
||||
.get("reason")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned),
|
||||
selectable,
|
||||
});
|
||||
}
|
||||
choices
|
||||
}
|
||||
|
||||
fn compute_drift(
|
||||
live: &HashMap<String, (String, u32)>,
|
||||
selected_operation_id: Option<&OperationId>,
|
||||
selected_operation_version: Option<u32>,
|
||||
) -> Option<OnboardingImportDrift> {
|
||||
let operation_id = selected_operation_id?;
|
||||
let selected_version = selected_operation_version?;
|
||||
match live.get(operation_id.as_str()) {
|
||||
None => Some(OnboardingImportDrift {
|
||||
reason: "selected_operation_unavailable".to_owned(),
|
||||
current_operation_version: None,
|
||||
}),
|
||||
// A newer Draft/version of the selected operation is drift.
|
||||
Some((_, current)) if *current != selected_version => Some(OnboardingImportDrift {
|
||||
reason: "selected_operation_version_drift".to_owned(),
|
||||
current_operation_version: Some(*current),
|
||||
}),
|
||||
// An exact-version publication (or test) is the expected onboarding
|
||||
// continuation, not blocking drift; only archive remains a visible
|
||||
// non-version drift. The chooser already stops offering it as a Draft
|
||||
// because `report_choices` requires live status `draft`.
|
||||
Some((status, _)) if status == "archived" => Some(OnboardingImportDrift {
|
||||
reason: "selected_operation_not_draft".to_owned(),
|
||||
current_operation_version: Some(selected_version),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_application_key(value: &str) -> Result<(), RegistryError> {
|
||||
if !(1..=MAX_APPLICATION_KEY_BYTES).contains(&value.len()) {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "idempotency_key",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_plan_digest(value: &str) -> Result<(), RegistryError> {
|
||||
let valid = value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
|
||||
if !valid {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "plan_digest",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -812,6 +812,13 @@ impl PostgresRegistry {
|
||||
expected_state: Option<&OperationStateExpectation>,
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
// Onboarding selection locks workspace state before an Operation row.
|
||||
// Keep that lock order here while remaining compatible with the
|
||||
// workspace KEY SHARE lock used by Operation foreign keys.
|
||||
sqlx::query("select id from workspaces where id = $1 for no key update")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let row = sqlx::query(
|
||||
"select status, current_draft_version, latest_published_version
|
||||
from operations
|
||||
@@ -844,6 +851,12 @@ impl PostgresRegistry {
|
||||
.map(|value| from_db_version(value, "latest_published_version"))
|
||||
.transpose()?;
|
||||
if latest == Some(request.version) && current == request.version {
|
||||
super::onboarding_import::record_import_funnel_milestones_in_transaction(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
*request.published_at,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -953,6 +966,13 @@ impl PostgresRegistry {
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
super::onboarding_import::record_import_funnel_milestones_in_transaction(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
*request.published_at,
|
||||
)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -989,7 +1009,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