//! Apply tests for the registry-only transactional `apply_import_plan`. //! //! Conventions follow the existing CreatePlan tests in `create.rs`: one //! unique schema per test, registry API for domain objects and the raw pool //! for storage-level fixtures (artifact sources). #![allow(dead_code)] use super::super::common::{TestDatabase, test_operation}; use super::{create_pending_openapi_job, create_workspace}; pub use time::Duration; pub use crank_core::{OperationId, OperationStatus, WorkspaceId}; pub use serde_json::{Value, json}; pub use sqlx::PgPool; pub use time::OffsetDateTime; pub use crank_registry::{ ApplyImportPlanRequest, CreateImportPlanRequest, ImportJobId, ImportJobStatus, ImportPlanApplyStatus, ImportPlanCandidateOutcome, ImportPlanId, RegistryError, RegistryOperation, }; mod auth; mod blocked; mod concurrency; mod new_version; mod partial; mod replay_stale; mod skip_rename; /// Shared fixture source id — must match `create_pending_openapi_job`. pub(crate) const SOURCE_ID: &str = "src_openapi_test"; fn source_hex() -> String { "ab".repeat(32) } fn source_ref() -> String { format!("sha256:{}", source_hex()) } /// Activates the source row the apply path revalidates under lock: the job /// envelope must still be `active` with exactly the recorded artifact ref. async fn activate_source(raw: &PgPool, workspace_id: &WorkspaceId, now: OffsetDateTime) { let hex = source_hex(); sqlx::query( "insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at) values ($1, 'sha256:' || $1, 16, $2, $2)", ) .bind(&hex) .bind(now) .execute(raw) .await .unwrap(); sqlx::query( "insert into artifact_sources ( workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle, created_at, updated_at ) values ($1, $2, $3, 'application/yaml', 'public', 'active', $4, $4)", ) .bind(workspace_id.as_str()) .bind(SOURCE_ID) .bind(&hex) .bind(now) .execute(raw) .await .unwrap(); } /// A planned Draft operation without auth references: apply must not /// require profile/secret rows for the basic create path. fn plan_operation(id: &str) -> RegistryOperation { let mut operation = test_operation(id, 1, OperationStatus::Draft); operation.execution_config.auth_profile_ref = None; operation } /// Builds a valid `import-plan-v1` payload applying a single `create` /// candidate over the shared verifiable source. fn single_create_payload(plan_id: &str, job_id: &str, fingerprint: &Value) -> Value { let operation = plan_operation("op_apply_basic"); json!({ "schema_version": "import-plan-v1", "plan_reference": plan_id, "job_id": job_id, "fingerprint": fingerprint, "source": { "source_id": SOURCE_ID, "digest": source_ref() }, "dependencies": [], "selection": { "mode": "full", "all": ["basic"], "selected": ["basic"], "excluded": [] }, "counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 }, "candidates": [{ "key": "basic", "name": operation.name, "state": "actionable", "decision": { "action": "create" }, "operation": operation }] }) } async fn stored_plan( registry: &crank_registry::PostgresRegistry, workspace_id: &WorkspaceId, job: &ImportJobId, plan_id: &str, fingerprint: &Value, ) -> (ImportPlanId, String) { let payload = single_create_payload(plan_id, job.as_str(), fingerprint); store_plan(registry, workspace_id, job, plan_id, fingerprint, payload).await } /// Persists any well-formed `import-plan-v1` payload bound to the shared /// verifiable source; returns the plan id and the registry-computed digest. async fn store_plan( registry: &crank_registry::PostgresRegistry, workspace_id: &WorkspaceId, job: &ImportJobId, plan_id: &str, _fingerprint: &Value, payload: Value, ) -> (ImportPlanId, String) { let plan = ImportPlanId::new(plan_id); let now = OffsetDateTime::now_utc(); let created = registry .create_import_plan(CreateImportPlanRequest { id: &plan, workspace_id, job_id: job, payload: &payload, created_at: &now, expires_at: &(now + Duration::minutes(30)), }) .await .unwrap(); (plan, created.digest) } /// Basename of the workspace slug for slug-scoped registry reads. #[allow(dead_code)] fn workspace_slug(workspace_id: &WorkspaceId) -> String { workspace_id.as_str().replace('_', "-") } fn fingerprint() -> Value { json!({"importer": "test", "digest": "fp-1"}) } #[tokio::test] async fn apply_creates_draft_operation_and_replays_committed_report() { let database = TestDatabase::new().await; let registry = database.registry().await; let raw = database.raw_pool().await; let now = OffsetDateTime::now_utc(); let ws = create_workspace(®istry, "ws_apply_1").await; let job = create_pending_openapi_job(®istry, &ws, "job_apply_1", now, now + Duration::hours(1)) .await; activate_source(&raw, &ws, now).await; let fp = fingerprint(); let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_apply_1", &fp).await; let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap(); let request = ApplyImportPlanRequest { workspace_id: &ws, plan_id: &plan, plan_digest: &digest, idempotency_key: "idem_apply_1", verified_fingerprint: &fp, applied_at: &applied_at, }; let result = registry.apply_import_plan(&request).await.unwrap(); // Fresh apply: the report is produced by this call, not a replay. assert!( !result.replayed, "a first apply must never be marked replayed" ); let report = &result.report; assert_eq!(report.status, ImportPlanApplyStatus::Applied); assert_eq!(report.plan_id, plan.as_str()); assert_eq!(report.job_id, job.as_str()); assert_eq!(report.plan_digest, digest); assert_eq!(report.idempotency_key, "idem_apply_1"); assert_eq!(report.counts.created, 1); assert_eq!(report.counts.versioned, 0); assert_eq!(report.counts.renamed, 0); assert_eq!(report.counts.skipped, 0); assert_eq!(report.counts.excluded, 0); assert_eq!(report.counts.rejected, 0); assert_eq!(report.outcomes.len(), 1); assert_eq!(report.outcomes[0].key, "basic"); assert_eq!( report.outcomes[0].outcome, ImportPlanCandidateOutcome::Created ); assert_eq!( report.outcomes[0].operation_id, Some(OperationId::new("op_apply_basic").as_str().to_owned()) ); assert_eq!(report.outcomes[0].version, Some(1)); assert_eq!(report.outcomes[0].reason, None); assert_eq!(report.source_id, SOURCE_ID); assert_eq!(report.source_digest, source_ref()); assert_eq!( report.recovery, "none", "a clean apply must not ask for recovery" ); // The planned contract landed as a new Draft operation at version 1. let summary = registry .get_operation_summary(&ws, &OperationId::new("op_apply_basic")) .await .unwrap() .unwrap(); assert_eq!(summary.status, OperationStatus::Draft); assert_eq!(summary.current_draft_version, 1); assert_eq!(summary.latest_published_version, None); // The anchor job is untouched: legacy replay and other plans stay viable. let job_after = registry.get_import_job(&ws, &job).await.unwrap().unwrap(); assert_eq!(job_after.status, ImportJobStatus::Pending); // Replay with the same scoped key and digest: identical immutable report. let replay = registry.apply_import_plan(&request).await.unwrap(); assert!(replay.replayed, "a second identical apply must be a replay"); assert_eq!( replay.report, *report, "the stored report must be returned byte-for-byte" ); // A changed digest under the same key is a typed conflict. let changed_digest = "cd".repeat(32); let changed = ApplyImportPlanRequest { plan_digest: &changed_digest, ..request }; assert!( matches!( registry.apply_import_plan(&changed).await, Err(RegistryError::ImportPlanKeyDigestConflict { .. }) ), "a changed digest under a used key must be a typed conflict" ); database.cleanup().await; }