diff --git a/crates/piqueld-store/src/auth/access.rs b/crates/piqueld-store/src/auth/access/mod.rs similarity index 63% rename from crates/piqueld-store/src/auth/access.rs rename to crates/piqueld-store/src/auth/access/mod.rs index fcdbea80c..d844c358e 100644 --- a/crates/piqueld-store/src/auth/access.rs +++ b/crates/piqueld-store/src/auth/access/mod.rs @@ -587,293 +587,4 @@ impl Store { } #[cfg(test)] -mod tests { - use super::*; - use crate::testing::{credential, template, user}; - use crate::{Actor, Mutation, MutationResponse}; - use crate::{CredentialKind, NewCredential}; - use piqueld_core::access::{AppPermission, Preset}; - - /// The actor `alice`'s session (see `Store::seed_caller`) records as. - fn alice() -> piqueld_core::EventActor { - piqueld_core::EventActor::Account { - user_id: "alice".into(), - credential_id: Some("alice".into()), - } - } - - /// Saves an empty application named `name`, returning its ID. - async fn application(store: &Store, name: &str) -> ApplicationId { - let saved = store.save_template(template(name, "[spec]"), false).await; - ApplicationId::parse(saved.application_id).unwrap() - } - - /// Creating an application gives its creator's account matching grants - /// there, unless it was created through a scoped credential. - #[tokio::test] - async fn only_unscoped_creators_receive_creator_grants() { - let (_temp, store) = Store::temporary().await; - let blog = application(&store, "blog").await; - let mut grants = Preset::Developer.grants(&Scope::one(blog.clone())); - grants - .grant( - Permission::Global(piqueld_core::access::GlobalPermission::AppsCreate), - &Scope::All, - ) - .unwrap(); - store.seed_auth_user(&user("alice"), &grants).await; - for (id, scoped) in [("token", Some(&grants)), ("session", None)] { - let credential = NewCredential { - grants: scoped, - ..credential(id, CredentialKind::Cli) - }; - store.insert_credential("alice", &credential).await.unwrap(); - } - let create = |credential_id, name: &str| { - let manifest = template(name, "[spec]"); - let actor = Actor::Account(Caller { - credential_id, - user_id: "alice", - }); - let store = &store; - async move { - let mutation = Mutation::save(manifest, None, false); - let (MutationResponse::Saved(saved), _) = store - .accept(actor, mutation, Some(0), false, None) - .await - .unwrap() - else { - panic!("saved application"); - }; - ApplicationId::parse(saved.application_id).unwrap() - } - }; - let readable = |store: &Store| { - let store = store.clone(); - async move { - let mut db = store.pool.acquire().await.unwrap(); - Holder::User("alice") - .grants(&mut db) - .await - .unwrap() - .app_scope(AppPermission::Write) - } - }; - let by_token = create("token", "from-token").await; - assert!(!readable(&store).await.contains(&by_token)); - let by_session = create("session", "from-session").await; - assert!(readable(&store).await.contains(&by_session)); - } - - /// Mutations record their caller on the operation and its events, - /// including events written later about that operation and daemon actions - /// it requests. A runtime action keeps the actor it started under even if - /// the operation is restarted. - #[tokio::test] - async fn operations_and_their_events_record_the_caller() { - use crate::Visibility; - use piqueld_core::observability::EventFilter; - let (_temp, store) = Store::temporary().await; - let blog = application(&store, "blog").await; - let actor = store.seed_caller("alice", &Grants::admin()).await; - let deploy = Mutation::deploy(store.production(&blog).await); - let (MutationResponse::Operation(operation), _) = - store.accept(actor, deploy, None, true, None).await.unwrap() - else { - panic!("deployment"); - }; - let filter = EventFilter { - operation_id: Some(operation.operation_id.clone()), - ..EventFilter::default() - }; - let accepted = store - .filtered_events(&filter, &Visibility::ALL, None, 100) - .await - .unwrap() - .items - .len(); - store.mark_running(&operation.operation_id).await; - let id = &operation.operation_id; - let action = store - .begin_action(Some(id), piqueld_core::Phase::EnsureService, None) - .await; - let action = action.unwrap(); - // Shared gateway work a deployment needs stays daemon-scoped. - let shared = store - .begin_daemon_action(Some(id), piqueld_core::Phase::IngressConfigureRoutes, None) - .await; - let shared = shared.unwrap(); - store.finish_action(&shared, None).await.unwrap(); - let only_shared = EventFilter { - action_id: Some(shared.id.clone()), - ..EventFilter::default() - }; - let shared = store - .filtered_events(&only_shared, &Visibility::ALL, None, 100) - .await - .unwrap() - .items; - assert_eq!(shared.len(), 2, "started and succeeded"); - assert!( - shared - .iter() - .all(|event| event.application_id.is_none() && event.actor == Some(alice())) - ); - let restart = "UPDATE operations SET actor_user_id='bob' WHERE id=?1"; - sqlx::query(restart) - .bind(id) - .execute(&store.pool) - .await - .unwrap(); - store.finish_action(&action, None).await.unwrap(); - let events = store - .filtered_events(&filter, &Visibility::ALL, None, 100) - .await - .unwrap() - .items; - // The transition wrote at least one event after acceptance. - assert!(events.len() > accepted, "{events:?}"); - for event in events { - assert_eq!(event.actor, Some(alice()), "{}", event.kind); - } - } - - /// Environment changes record their caller too, including every - /// operation one mutation requests, like deleting each environment of an - /// application. - #[tokio::test] - async fn environment_mutations_record_the_caller() { - use crate::Visibility; - use piqueld_core::{EnvironmentName, observability::EventFilter}; - let (_temp, store) = Store::temporary().await; - let blog = application(&store, "blog").await; - let actor = store.seed_caller("alice", &Grants::admin()).await; - let filter = EventFilter { - application_id: Some(blog.to_string()), - ..EventFilter::default() - }; - let history = |store: &Store| { - let (store, filter) = (store.clone(), filter.clone()); - async move { - let page = store.filtered_events(&filter, &Visibility::ALL, None, 100); - page.await.unwrap().items - } - }; - let before = history(&store).await.len(); - let names = ["production", "staging"].map(|name| EnvironmentName::parse(name).unwrap()); - let create = Mutation::CreateEnvironment { - application: blog.clone(), - name: names[1].clone(), - source: None, - }; - store.accept(actor, create, None, true, None).await.unwrap(); - let delete = Mutation::DeleteApplication { - id: blog.clone(), - environments: names.to_vec(), - }; - let (MutationResponse::Deleted(deleted), _) = - store.accept(actor, delete, None, true, None).await.unwrap() - else { - panic!("deletion"); - }; - assert_eq!(deleted.operations.len(), 2); - for operation in &deleted.operations { - let actor: Option = - sqlx::query_scalar("SELECT actor_user_id FROM operations WHERE id=?1") - .bind(&operation.operation_id) - .fetch_one(&store.pool) - .await - .unwrap(); - assert_eq!(actor.as_deref(), Some("alice")); - } - let events = history(&store).await.split_off(before); - assert!( - events - .iter() - .any(|event| event.environment_id.is_some() && event.operation_id.is_none()) - ); - for event in events { - assert_eq!(event.actor, Some(alice()), "{}", event.kind); - } - } - - /// Superseding someone else's operation records the new request's caller - /// on its own operation only; the superseded one keeps its requester. - #[tokio::test] - async fn superseded_operations_keep_their_caller() { - let (_temp, store) = Store::temporary().await; - let blog = application(&store, "blog").await; - let mut operations = Vec::new(); - for name in ["alice", "bob"] { - let actor = store.seed_caller(name, &Grants::admin()).await; - let deploy = Mutation::deploy(store.production(&blog).await); - let (MutationResponse::Operation(operation), _) = - store.accept(actor, deploy, None, true, None).await.unwrap() - else { - panic!("deployment"); - }; - operations.push(operation.operation_id); - } - for (operation, name) in operations.iter().zip(["alice", "bob"]) { - let actor: Option = - sqlx::query_scalar("SELECT actor_user_id FROM operations WHERE id=?1") - .bind(operation) - .fetch_one(&store.pool) - .await - .unwrap(); - assert_eq!(actor.as_deref(), Some(name)); - } - } - - /// Deleting an application removes grants on it, and expires scoped - /// credentials that held grants only there a minute later instead of - /// leaving them with no access. - #[tokio::test] - async fn deleting_an_application_expires_tokens_left_without_grants() { - let (_temp, store) = Store::temporary().await; - let blog = application(&store, "blog").await; - let shop = application(&store, "shop").await; - store.seed_auth_user(&user("alice"), &Grants::admin()).await; - let deploy_blog = Preset::Deploy.grants(&Scope::one(blog.clone())); - let mut both = deploy_blog.clone(); - both.extend(&Preset::ReadOnly.grants(&Scope::one(shop.clone()))); - for (id, grants) in [ - ("blog-only", Some(&deploy_blog)), - ("both", Some(&both)), - ("session", None), - ] { - let credential = NewCredential { - grants, - ..credential(id, CredentialKind::Token) - }; - store.insert_credential("alice", &credential).await.unwrap(); - } - let delete = Mutation::DeleteApplication { - id: blog.clone(), - environments: Vec::new(), - }; - let (MutationResponse::Deleted(deleted), _) = store - .accept(Actor::Daemon, delete, None, true, None) - .await - .unwrap() - else { - panic!("deletion"); - }; - let operation = &deleted.operations[0]; - store.mark_running(&operation.operation_id).await; - let operation = store.operation(&operation.operation_id).await.unwrap(); - store.finish_delete_operation(&operation).await.unwrap(); - let left = store.credential_owner("blog-only").await.unwrap().unwrap(); - assert!(left.grants.is_empty()); - let expires_at = - sqlx::query_scalar!("SELECT expires_at FROM auth_credentials WHERE id='blog-only'") - .fetch_one(&store.pool) - .await - .unwrap(); - assert!(expires_at.is_some_and(|at| at <= now_secs() + 60)); - assert!(store.credential_owner("session").await.unwrap().is_some()); - let both = store.credential_owner("both").await.unwrap().unwrap(); - assert_eq!(both.grants.app_scope(AppPermission::Read), Scope::one(shop)); - assert!(both.grants.app_scope(AppPermission::Deploy).is_empty()); - } -} +mod tests; diff --git a/crates/piqueld-store/src/auth/access/tests.rs b/crates/piqueld-store/src/auth/access/tests.rs new file mode 100644 index 000000000..2be2185b6 --- /dev/null +++ b/crates/piqueld-store/src/auth/access/tests.rs @@ -0,0 +1,288 @@ +use super::*; +use crate::testing::{credential, template, user}; +use crate::{Actor, Mutation, MutationResponse}; +use crate::{CredentialKind, NewCredential}; +use piqueld_core::access::{AppPermission, Preset}; + +/// The actor `alice`'s session (see `Store::seed_caller`) records as. +fn alice() -> piqueld_core::EventActor { + piqueld_core::EventActor::Account { + user_id: "alice".into(), + credential_id: Some("alice".into()), + } +} + +/// Saves an empty application named `name`, returning its ID. +async fn application(store: &Store, name: &str) -> ApplicationId { + let saved = store.save_template(template(name, "[spec]"), false).await; + ApplicationId::parse(saved.application_id).unwrap() +} + +/// Creating an application gives its creator's account matching grants +/// there, unless it was created through a scoped credential. +#[tokio::test] +async fn only_unscoped_creators_receive_creator_grants() { + let (_temp, store) = Store::temporary().await; + let blog = application(&store, "blog").await; + let mut grants = Preset::Developer.grants(&Scope::one(blog.clone())); + grants + .grant( + Permission::Global(piqueld_core::access::GlobalPermission::AppsCreate), + &Scope::All, + ) + .unwrap(); + store.seed_auth_user(&user("alice"), &grants).await; + for (id, scoped) in [("token", Some(&grants)), ("session", None)] { + let credential = NewCredential { + grants: scoped, + ..credential(id, CredentialKind::Cli) + }; + store.insert_credential("alice", &credential).await.unwrap(); + } + let create = |credential_id, name: &str| { + let manifest = template(name, "[spec]"); + let actor = Actor::Account(Caller { + credential_id, + user_id: "alice", + }); + let store = &store; + async move { + let mutation = Mutation::save(manifest, None, false); + let (MutationResponse::Saved(saved), _) = store + .accept(actor, mutation, Some(0), false, None) + .await + .unwrap() + else { + panic!("saved application"); + }; + ApplicationId::parse(saved.application_id).unwrap() + } + }; + let readable = |store: &Store| { + let store = store.clone(); + async move { + let mut db = store.pool.acquire().await.unwrap(); + Holder::User("alice") + .grants(&mut db) + .await + .unwrap() + .app_scope(AppPermission::Write) + } + }; + let by_token = create("token", "from-token").await; + assert!(!readable(&store).await.contains(&by_token)); + let by_session = create("session", "from-session").await; + assert!(readable(&store).await.contains(&by_session)); +} + +/// Mutations record their caller on the operation and its events, +/// including events written later about that operation and daemon actions +/// it requests. A runtime action keeps the actor it started under even if +/// the operation is restarted. +#[tokio::test] +async fn operations_and_their_events_record_the_caller() { + use crate::Visibility; + use piqueld_core::observability::EventFilter; + let (_temp, store) = Store::temporary().await; + let blog = application(&store, "blog").await; + let actor = store.seed_caller("alice", &Grants::admin()).await; + let deploy = Mutation::deploy(store.production(&blog).await); + let (MutationResponse::Operation(operation), _) = + store.accept(actor, deploy, None, true, None).await.unwrap() + else { + panic!("deployment"); + }; + let filter = EventFilter { + operation_id: Some(operation.operation_id.clone()), + ..EventFilter::default() + }; + let accepted = store + .filtered_events(&filter, &Visibility::ALL, None, 100) + .await + .unwrap() + .items + .len(); + store.mark_running(&operation.operation_id).await; + let id = &operation.operation_id; + let action = store + .begin_action(Some(id), piqueld_core::Phase::EnsureService, None) + .await; + let action = action.unwrap(); + // Shared gateway work a deployment needs stays daemon-scoped. + let shared = store + .begin_daemon_action(Some(id), piqueld_core::Phase::IngressConfigureRoutes, None) + .await; + let shared = shared.unwrap(); + store.finish_action(&shared, None).await.unwrap(); + let only_shared = EventFilter { + action_id: Some(shared.id.clone()), + ..EventFilter::default() + }; + let shared = store + .filtered_events(&only_shared, &Visibility::ALL, None, 100) + .await + .unwrap() + .items; + assert_eq!(shared.len(), 2, "started and succeeded"); + assert!( + shared + .iter() + .all(|event| event.application_id.is_none() && event.actor == Some(alice())) + ); + let restart = "UPDATE operations SET actor_user_id='bob' WHERE id=?1"; + sqlx::query(restart) + .bind(id) + .execute(&store.pool) + .await + .unwrap(); + store.finish_action(&action, None).await.unwrap(); + let events = store + .filtered_events(&filter, &Visibility::ALL, None, 100) + .await + .unwrap() + .items; + // The transition wrote at least one event after acceptance. + assert!(events.len() > accepted, "{events:?}"); + for event in events { + assert_eq!(event.actor, Some(alice()), "{}", event.kind); + } +} + +/// Environment changes record their caller too, including every +/// operation one mutation requests, like deleting each environment of an +/// application. +#[tokio::test] +async fn environment_mutations_record_the_caller() { + use crate::Visibility; + use piqueld_core::{EnvironmentName, observability::EventFilter}; + let (_temp, store) = Store::temporary().await; + let blog = application(&store, "blog").await; + let actor = store.seed_caller("alice", &Grants::admin()).await; + let filter = EventFilter { + application_id: Some(blog.to_string()), + ..EventFilter::default() + }; + let history = |store: &Store| { + let (store, filter) = (store.clone(), filter.clone()); + async move { + let page = store.filtered_events(&filter, &Visibility::ALL, None, 100); + page.await.unwrap().items + } + }; + let before = history(&store).await.len(); + let names = ["production", "staging"].map(|name| EnvironmentName::parse(name).unwrap()); + let create = Mutation::CreateEnvironment { + application: blog.clone(), + name: names[1].clone(), + source: None, + }; + store.accept(actor, create, None, true, None).await.unwrap(); + let delete = Mutation::DeleteApplication { + id: blog.clone(), + environments: names.to_vec(), + }; + let (MutationResponse::Deleted(deleted), _) = + store.accept(actor, delete, None, true, None).await.unwrap() + else { + panic!("deletion"); + }; + assert_eq!(deleted.operations.len(), 2); + for operation in &deleted.operations { + let actor: Option = + sqlx::query_scalar("SELECT actor_user_id FROM operations WHERE id=?1") + .bind(&operation.operation_id) + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(actor.as_deref(), Some("alice")); + } + let events = history(&store).await.split_off(before); + assert!( + events + .iter() + .any(|event| event.environment_id.is_some() && event.operation_id.is_none()) + ); + for event in events { + assert_eq!(event.actor, Some(alice()), "{}", event.kind); + } +} + +/// Superseding someone else's operation records the new request's caller +/// on its own operation only; the superseded one keeps its requester. +#[tokio::test] +async fn superseded_operations_keep_their_caller() { + let (_temp, store) = Store::temporary().await; + let blog = application(&store, "blog").await; + let mut operations = Vec::new(); + for name in ["alice", "bob"] { + let actor = store.seed_caller(name, &Grants::admin()).await; + let deploy = Mutation::deploy(store.production(&blog).await); + let (MutationResponse::Operation(operation), _) = + store.accept(actor, deploy, None, true, None).await.unwrap() + else { + panic!("deployment"); + }; + operations.push(operation.operation_id); + } + for (operation, name) in operations.iter().zip(["alice", "bob"]) { + let actor: Option = + sqlx::query_scalar("SELECT actor_user_id FROM operations WHERE id=?1") + .bind(operation) + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(actor.as_deref(), Some(name)); + } +} + +/// Deleting an application removes grants on it, and expires scoped +/// credentials that held grants only there a minute later instead of +/// leaving them with no access. +#[tokio::test] +async fn deleting_an_application_expires_tokens_left_without_grants() { + let (_temp, store) = Store::temporary().await; + let blog = application(&store, "blog").await; + let shop = application(&store, "shop").await; + store.seed_auth_user(&user("alice"), &Grants::admin()).await; + let deploy_blog = Preset::Deploy.grants(&Scope::one(blog.clone())); + let mut both = deploy_blog.clone(); + both.extend(&Preset::ReadOnly.grants(&Scope::one(shop.clone()))); + for (id, grants) in [ + ("blog-only", Some(&deploy_blog)), + ("both", Some(&both)), + ("session", None), + ] { + let credential = NewCredential { + grants, + ..credential(id, CredentialKind::Token) + }; + store.insert_credential("alice", &credential).await.unwrap(); + } + let delete = Mutation::DeleteApplication { + id: blog.clone(), + environments: Vec::new(), + }; + let (MutationResponse::Deleted(deleted), _) = store + .accept(Actor::Daemon, delete, None, true, None) + .await + .unwrap() + else { + panic!("deletion"); + }; + let operation = &deleted.operations[0]; + store.mark_running(&operation.operation_id).await; + let operation = store.operation(&operation.operation_id).await.unwrap(); + store.finish_delete_operation(&operation).await.unwrap(); + let left = store.credential_owner("blog-only").await.unwrap().unwrap(); + assert!(left.grants.is_empty()); + let expires_at = + sqlx::query_scalar!("SELECT expires_at FROM auth_credentials WHERE id='blog-only'") + .fetch_one(&store.pool) + .await + .unwrap(); + assert!(expires_at.is_some_and(|at| at <= now_secs() + 60)); + assert!(store.credential_owner("session").await.unwrap().is_some()); + let both = store.credential_owner("both").await.unwrap().unwrap(); + assert_eq!(both.grants.app_scope(AppPermission::Read), Scope::one(shop)); + assert!(both.grants.app_scope(AppPermission::Deploy).is_empty()); +} diff --git a/crates/piqueld-store/src/deployment.rs b/crates/piqueld-store/src/deployment/mod.rs similarity index 64% rename from crates/piqueld-store/src/deployment.rs rename to crates/piqueld-store/src/deployment/mod.rs index c3ab108cb..e2ba88a0a 100644 --- a/crates/piqueld-store/src/deployment.rs +++ b/crates/piqueld-store/src/deployment/mod.rs @@ -547,332 +547,4 @@ impl Store { } #[cfg(test)] -mod tests { - use super::*; - use crate::Actor::Daemon; - use crate::{Mutation, MutationResponse}; - use piqueld_core::{ApplicationState, OperationState}; - - fn empty() -> ApplicationTemplate { - crate::testing::template("empty", "[spec]") - .normalize(piqueld_core::ApplicationId::parse("app-empty-test").unwrap()) - } - - async fn save(store: &Store, app: ApplicationTemplate, generation: u64) -> SavedApplication { - let (MutationResponse::Saved(saved), wake) = store - .accept( - Daemon, - Mutation::Save { - application: Box::new(app), - expected_application_id: None, - deploy: false, - }, - Some(generation), - false, - None, - ) - .await - .unwrap() - else { - panic!("saved response") - }; - assert!(!wake); - saved - } - - /// Requests a deployment of `id`, returning it and whether the controller should wake. - async fn deploy( - store: &Store, - id: &EnvironmentId, - generation: u64, - key: Option<&str>, - ) -> (piqueld_core::api::AcceptedOperation, bool) { - let (MutationResponse::Operation(operation), wake) = store - .accept( - Daemon, - Mutation::deploy(id.clone()), - Some(generation), - false, - key, - ) - .await - .unwrap() - else { - panic!("operation response") - }; - (operation, wake) - } - - #[tokio::test] - async fn save_and_deploy_accepts_saved_only_configuration_but_cannot_reverse_deletion() { - let (_temp, store) = Store::temporary().await; - let saved = save(&store, empty(), 0).await; - let id = store.saved_production(&saved).await; - let application = store.get(&id).await.unwrap().application.application; - let (MutationResponse::Saved(deployed), wake) = store - .accept( - Daemon, - Mutation::Save { - application: Box::new(application.clone()), - expected_application_id: Some(saved.application_id.clone()), - deploy: true, - }, - Some(saved.generation), - false, - None, - ) - .await - .unwrap() - else { - panic!("saved deployment") - }; - assert!(wake); - let operation_id = deployed.operation_id.unwrap(); - assert_eq!( - store - .deployment_snapshot(&operation_id) - .await - .unwrap() - .template, - application - ); - let (MutationResponse::Deleted(deletion), _) = store - .accept( - Daemon, - Mutation::DeleteApplication { - id: application.id().clone(), - environments: Vec::new(), - }, - Some(deployed.generation), - false, - None, - ) - .await - .unwrap() - else { - panic!("deleted") - }; - for deploy in [false, true] { - assert!(matches!( - store - .accept( - Daemon, - Mutation::Save { - application: Box::new(application.clone()), - expected_application_id: Some(saved.application_id.clone()), - deploy, - }, - Some(deletion.generation), - false, - None, - ) - .await, - Err(StoreError::IllegalTransition) - )); - } - assert!(matches!( - store - .save_application(&application, None, Some(deletion.generation)) - .await, - Err(StoreError::IllegalTransition) - )); - let current = store.get(&id).await.unwrap(); - assert!(current.delete_intent() && current.application.delete_intent); - assert_eq!(current.application.generation, deletion.generation); - assert_eq!( - store - .latest_operation_for_environment(&id) - .await - .unwrap() - .unwrap() - .id, - deletion.operations[0].operation_id - ); - } - - #[tokio::test] - async fn saved_changes_cannot_enter_deployments_or_retries_after_restart() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("db"); - let store = Store::open_unsynced(&path).await.unwrap(); - let saved = save(&store, empty(), 0).await; - let id = store.saved_production(&saved).await; - assert_eq!( - store.status(&id).await.unwrap().state, - ApplicationState::NotDeployed - ); - assert!( - store - .latest_operation_for_environment(&id) - .await - .unwrap() - .is_none() - ); - let (first, wake) = deploy(&store, &id, saved.generation, Some("deploy-once")).await; - assert!(wake); - let original = store - .deployment_snapshot(&first.operation_id) - .await - .unwrap() - .template; - store.mark_running(&first.operation_id).await; - let mut edited = original.to_manifest(); - edited.spec.volumes.push(piqueld_core::manifest::Volume { - name: "later".into(), - }); - let edited = edited - .validate_template() - .unwrap() - .normalize(original.id().clone()); - let changed = save(&store, edited, 1).await; - assert_eq!(changed.generation, 2); - drop(store); - let store = Store::open_unsynced(&path).await.unwrap(); - store.recover_interrupted().await.unwrap(); - let op = store.operation(&first.operation_id).await.unwrap(); - let attempts = store.deployment_attempts(&op.id, None, 100).await.unwrap(); - assert_eq!(attempts.items.len(), 1); - assert_eq!(attempts.items[0].attempt, 1); - assert_eq!(attempts.items[0].state, OperationState::Cancelled); - assert!(attempts.items[0].finished_at_ms.is_some()); - assert_eq!(store.recover_interrupted().await.unwrap(), 0); - assert_eq!(op.generation, 1); - assert_eq!( - store.deployment_snapshot(&op.id).await.unwrap().template, - original - ); - let (replay, wake) = deploy(&store, &id, 1, Some("deploy-once")).await; - assert!(!wake); - assert_eq!(replay.operation_id, op.id); - let (next, _) = deploy(&store, &id, 2, None).await; - assert_ne!(next.operation_id, op.id); - assert!(matches!( - store.retry_operation(&op).await, - Err(StoreError::IllegalTransition) - )); - assert_eq!( - store.deployments(&id, None, 3).await.unwrap().items.len(), - 2 - ); - assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 0); - } - - #[tokio::test] - async fn failure_survives_success_and_empty_target_has_no_resources() { - let (_temp, store) = Store::temporary().await; - let saved = save(&store, empty(), 0).await; - let id = store.saved_production(&saved).await; - let op = store.request_deploy(&id, Some(1)).await.unwrap(); - let target = piqueld_core::compile_application( - &store - .deployment_snapshot(&op.id) - .await - .unwrap() - .rendering - .unwrap() - .application, - &id, - store.instance_id().clone(), - &piqueld_core::ResolutionSet::default(), - ) - .unwrap(); - assert!( - target.services.is_empty() && target.networks.is_empty() && target.volumes.is_empty() - ); - store.mark_running(&op.id).await; - store - .transition_operation( - &op.id, - OperationState::Running, - OperationState::Failed, - Some(("docker_unavailable", "Docker is unavailable")), - ) - .await - .unwrap(); - let op = store.operation(&op.id).await.unwrap(); - store.retry_operation(&op).await.unwrap(); - store.mark_running(&op.id).await; - store.save_prepared(&op, &target).await.unwrap(); - store.publish_prepared(&op).await.unwrap(); - store - .transition_operation( - &op.id, - OperationState::Running, - OperationState::Succeeded, - None, - ) - .await - .unwrap(); - store.prune_events(i64::MAX).await.unwrap(); - let history = store.deployment_attempts(&op.id, None, 100).await.unwrap(); - assert_eq!(history.items.len(), 2); - assert_eq!( - history.items[1].error_code.as_deref(), - Some("docker_unavailable") - ); - let deployments = store.deployments(&id, None, 3).await.unwrap(); - assert!(deployments.items[0].current_target && deployments.items[0].last_successful); - } - - /// Deployment IDs are monotonic only within one process, so after a - /// restart with the clock behind, a newer deployment can sort below an - /// older one: the current and last successful deployments are the - /// newest by creation time, not by ID. - #[tokio::test] - async fn current_deployment_is_the_newest_by_creation_time_not_by_id() { - let (_temp, store) = Store::temporary().await; - let saved = store - .save_template(crate::testing::template("alpha", "[spec]"), true) - .await; - let id = store.saved_production(&saved).await; - let alpha = saved.operation_id.unwrap(); - // Published and succeeded, as a finished rollout leaves it. - sqlx::query("UPDATE operations SET promoted=1,state='succeeded',finished_at_ms=created_at_ms WHERE id=?1") - .bind(&alpha) - .execute(&store.pool) - .await - .unwrap(); - sqlx::query("UPDATE deployments SET succeeded_at_ms=created_at_ms WHERE id=?1") - .bind(&alpha) - .execute(&store.pool) - .await - .unwrap(); - // An already-published deployment from before the restart: its ID - // sorts above alpha's, but it was created a minute earlier. - let older = format!("operation-{}", "f".repeat(32)); - sqlx::query("INSERT INTO operations(id,environment_id,kind,state,generation,promoted,created_at_ms,updated_at_ms,finished_at_ms) SELECT ?1,environment_id,kind,'succeeded',generation,1,created_at_ms-60000,created_at_ms-60000,created_at_ms-60000 FROM operations WHERE id=?2") - .bind(&older) - .bind(&alpha) - .execute(&store.pool) - .await - .unwrap(); - sqlx::query("INSERT INTO deployments(id,environment_id,generation,manifest_json,template_json,variables_json,created_at_ms,succeeded_at_ms) SELECT ?1,environment_id,generation,manifest_json,template_json,variables_json,created_at_ms-60000,created_at_ms-60000 FROM deployments WHERE id=?2") - .bind(&older) - .bind(&alpha) - .execute(&store.pool) - .await - .unwrap(); - let latest = store.latest_operation_for_environment(&id).await.unwrap(); - assert_eq!(latest.unwrap().id, alpha); - assert_eq!( - store.current_deployment(&id).await.unwrap().unwrap().id, - alpha - ); - // Paging stays in ID order, so the older deployment lists first. - let deployments = store.deployments(&id, None, 2).await.unwrap().items; - let flags = deployments - .iter() - .map(|deployment| { - ( - deployment.operation.id.as_str(), - deployment.current_target, - deployment.last_successful, - ) - }) - .collect::>(); - assert_eq!( - flags, - [(older.as_str(), false, false), (alpha.as_str(), true, true)] - ); - } -} +mod tests; diff --git a/crates/piqueld-store/src/deployment/tests.rs b/crates/piqueld-store/src/deployment/tests.rs new file mode 100644 index 000000000..a0c71a012 --- /dev/null +++ b/crates/piqueld-store/src/deployment/tests.rs @@ -0,0 +1,325 @@ +use super::*; +use crate::Actor::Daemon; +use crate::{Mutation, MutationResponse}; +use piqueld_core::{ApplicationState, OperationState}; + +fn empty() -> ApplicationTemplate { + crate::testing::template("empty", "[spec]") + .normalize(piqueld_core::ApplicationId::parse("app-empty-test").unwrap()) +} + +async fn save(store: &Store, app: ApplicationTemplate, generation: u64) -> SavedApplication { + let (MutationResponse::Saved(saved), wake) = store + .accept( + Daemon, + Mutation::Save { + application: Box::new(app), + expected_application_id: None, + deploy: false, + }, + Some(generation), + false, + None, + ) + .await + .unwrap() + else { + panic!("saved response") + }; + assert!(!wake); + saved +} + +/// Requests a deployment of `id`, returning it and whether the controller should wake. +async fn deploy( + store: &Store, + id: &EnvironmentId, + generation: u64, + key: Option<&str>, +) -> (piqueld_core::api::AcceptedOperation, bool) { + let (MutationResponse::Operation(operation), wake) = store + .accept( + Daemon, + Mutation::deploy(id.clone()), + Some(generation), + false, + key, + ) + .await + .unwrap() + else { + panic!("operation response") + }; + (operation, wake) +} + +#[tokio::test] +async fn save_and_deploy_accepts_saved_only_configuration_but_cannot_reverse_deletion() { + let (_temp, store) = Store::temporary().await; + let saved = save(&store, empty(), 0).await; + let id = store.saved_production(&saved).await; + let application = store.get(&id).await.unwrap().application.application; + let (MutationResponse::Saved(deployed), wake) = store + .accept( + Daemon, + Mutation::Save { + application: Box::new(application.clone()), + expected_application_id: Some(saved.application_id.clone()), + deploy: true, + }, + Some(saved.generation), + false, + None, + ) + .await + .unwrap() + else { + panic!("saved deployment") + }; + assert!(wake); + let operation_id = deployed.operation_id.unwrap(); + assert_eq!( + store + .deployment_snapshot(&operation_id) + .await + .unwrap() + .template, + application + ); + let (MutationResponse::Deleted(deletion), _) = store + .accept( + Daemon, + Mutation::DeleteApplication { + id: application.id().clone(), + environments: Vec::new(), + }, + Some(deployed.generation), + false, + None, + ) + .await + .unwrap() + else { + panic!("deleted") + }; + for deploy in [false, true] { + assert!(matches!( + store + .accept( + Daemon, + Mutation::Save { + application: Box::new(application.clone()), + expected_application_id: Some(saved.application_id.clone()), + deploy, + }, + Some(deletion.generation), + false, + None, + ) + .await, + Err(StoreError::IllegalTransition) + )); + } + assert!(matches!( + store + .save_application(&application, None, Some(deletion.generation)) + .await, + Err(StoreError::IllegalTransition) + )); + let current = store.get(&id).await.unwrap(); + assert!(current.delete_intent() && current.application.delete_intent); + assert_eq!(current.application.generation, deletion.generation); + assert_eq!( + store + .latest_operation_for_environment(&id) + .await + .unwrap() + .unwrap() + .id, + deletion.operations[0].operation_id + ); +} + +#[tokio::test] +async fn saved_changes_cannot_enter_deployments_or_retries_after_restart() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("db"); + let store = Store::open_unsynced(&path).await.unwrap(); + let saved = save(&store, empty(), 0).await; + let id = store.saved_production(&saved).await; + assert_eq!( + store.status(&id).await.unwrap().state, + ApplicationState::NotDeployed + ); + assert!( + store + .latest_operation_for_environment(&id) + .await + .unwrap() + .is_none() + ); + let (first, wake) = deploy(&store, &id, saved.generation, Some("deploy-once")).await; + assert!(wake); + let original = store + .deployment_snapshot(&first.operation_id) + .await + .unwrap() + .template; + store.mark_running(&first.operation_id).await; + let mut edited = original.to_manifest(); + edited.spec.volumes.push(piqueld_core::manifest::Volume { + name: "later".into(), + }); + let edited = edited + .validate_template() + .unwrap() + .normalize(original.id().clone()); + let changed = save(&store, edited, 1).await; + assert_eq!(changed.generation, 2); + drop(store); + let store = Store::open_unsynced(&path).await.unwrap(); + store.recover_interrupted().await.unwrap(); + let op = store.operation(&first.operation_id).await.unwrap(); + let attempts = store.deployment_attempts(&op.id, None, 100).await.unwrap(); + assert_eq!(attempts.items.len(), 1); + assert_eq!(attempts.items[0].attempt, 1); + assert_eq!(attempts.items[0].state, OperationState::Cancelled); + assert!(attempts.items[0].finished_at_ms.is_some()); + assert_eq!(store.recover_interrupted().await.unwrap(), 0); + assert_eq!(op.generation, 1); + assert_eq!( + store.deployment_snapshot(&op.id).await.unwrap().template, + original + ); + let (replay, wake) = deploy(&store, &id, 1, Some("deploy-once")).await; + assert!(!wake); + assert_eq!(replay.operation_id, op.id); + let (next, _) = deploy(&store, &id, 2, None).await; + assert_ne!(next.operation_id, op.id); + assert!(matches!( + store.retry_operation(&op).await, + Err(StoreError::IllegalTransition) + )); + assert_eq!( + store.deployments(&id, None, 3).await.unwrap().items.len(), + 2 + ); + assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 0); +} + +#[tokio::test] +async fn failure_survives_success_and_empty_target_has_no_resources() { + let (_temp, store) = Store::temporary().await; + let saved = save(&store, empty(), 0).await; + let id = store.saved_production(&saved).await; + let op = store.request_deploy(&id, Some(1)).await.unwrap(); + let target = piqueld_core::compile_application( + &store + .deployment_snapshot(&op.id) + .await + .unwrap() + .rendering + .unwrap() + .application, + &id, + store.instance_id().clone(), + &piqueld_core::ResolutionSet::default(), + ) + .unwrap(); + assert!(target.services.is_empty() && target.networks.is_empty() && target.volumes.is_empty()); + store.mark_running(&op.id).await; + store + .transition_operation( + &op.id, + OperationState::Running, + OperationState::Failed, + Some(("docker_unavailable", "Docker is unavailable")), + ) + .await + .unwrap(); + let op = store.operation(&op.id).await.unwrap(); + store.retry_operation(&op).await.unwrap(); + store.mark_running(&op.id).await; + store.save_prepared(&op, &target).await.unwrap(); + store.publish_prepared(&op).await.unwrap(); + store + .transition_operation( + &op.id, + OperationState::Running, + OperationState::Succeeded, + None, + ) + .await + .unwrap(); + store.prune_events(i64::MAX).await.unwrap(); + let history = store.deployment_attempts(&op.id, None, 100).await.unwrap(); + assert_eq!(history.items.len(), 2); + assert_eq!( + history.items[1].error_code.as_deref(), + Some("docker_unavailable") + ); + let deployments = store.deployments(&id, None, 3).await.unwrap(); + assert!(deployments.items[0].current_target && deployments.items[0].last_successful); +} + +/// Deployment IDs are monotonic only within one process, so after a +/// restart with the clock behind, a newer deployment can sort below an +/// older one: the current and last successful deployments are the +/// newest by creation time, not by ID. +#[tokio::test] +async fn current_deployment_is_the_newest_by_creation_time_not_by_id() { + let (_temp, store) = Store::temporary().await; + let saved = store + .save_template(crate::testing::template("alpha", "[spec]"), true) + .await; + let id = store.saved_production(&saved).await; + let alpha = saved.operation_id.unwrap(); + // Published and succeeded, as a finished rollout leaves it. + sqlx::query("UPDATE operations SET promoted=1,state='succeeded',finished_at_ms=created_at_ms WHERE id=?1") + .bind(&alpha) + .execute(&store.pool) + .await + .unwrap(); + sqlx::query("UPDATE deployments SET succeeded_at_ms=created_at_ms WHERE id=?1") + .bind(&alpha) + .execute(&store.pool) + .await + .unwrap(); + // An already-published deployment from before the restart: its ID + // sorts above alpha's, but it was created a minute earlier. + let older = format!("operation-{}", "f".repeat(32)); + sqlx::query("INSERT INTO operations(id,environment_id,kind,state,generation,promoted,created_at_ms,updated_at_ms,finished_at_ms) SELECT ?1,environment_id,kind,'succeeded',generation,1,created_at_ms-60000,created_at_ms-60000,created_at_ms-60000 FROM operations WHERE id=?2") + .bind(&older) + .bind(&alpha) + .execute(&store.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO deployments(id,environment_id,generation,manifest_json,template_json,variables_json,created_at_ms,succeeded_at_ms) SELECT ?1,environment_id,generation,manifest_json,template_json,variables_json,created_at_ms-60000,created_at_ms-60000 FROM deployments WHERE id=?2") + .bind(&older) + .bind(&alpha) + .execute(&store.pool) + .await + .unwrap(); + let latest = store.latest_operation_for_environment(&id).await.unwrap(); + assert_eq!(latest.unwrap().id, alpha); + assert_eq!( + store.current_deployment(&id).await.unwrap().unwrap().id, + alpha + ); + // Paging stays in ID order, so the older deployment lists first. + let deployments = store.deployments(&id, None, 2).await.unwrap().items; + let flags = deployments + .iter() + .map(|deployment| { + ( + deployment.operation.id.as_str(), + deployment.current_target, + deployment.last_successful, + ) + }) + .collect::>(); + assert_eq!( + flags, + [(older.as_str(), false, false), (alpha.as_str(), true, true)] + ); +} diff --git a/crates/piqueld-store/src/ingress.rs b/crates/piqueld-store/src/ingress/mod.rs similarity index 51% rename from crates/piqueld-store/src/ingress.rs rename to crates/piqueld-store/src/ingress/mod.rs index b3df6dfa1..2a32b404a 100644 --- a/crates/piqueld-store/src/ingress.rs +++ b/crates/piqueld-store/src/ingress/mod.rs @@ -672,630 +672,4 @@ impl Store { } #[cfg(test)] -mod tests { - use super::*; - use crate::testing::template; - use crate::{Mutation, MutationResponse}; - use piqueld_core::NormalizedApplication; - use piqueld_core::manifest::{ApplicationTemplate, Variable}; - use std::fmt::Write as _; - - fn app(name: &str, hostname: Option<&str>) -> NormalizedApplication { - routed(name, hostname.as_slice()) - } - - /// An application routing each of `hostnames` to its service. - fn routed(name: &str, hostnames: &[&str]) -> NormalizedApplication { - let mut text = format!( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='{name}'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'" - ); - for hostname in hostnames { - write!( - text, - "\n[[spec.routes]]\nhostname='{hostname}'\nservice='web'\nport=80" - ) - .unwrap(); - } - piqueld_core::parse_toml(&text) - .unwrap() - .normalize(piqueld_core::ApplicationId::parse("input-app").unwrap()) - } - - async fn save( - store: &Store, - application: NormalizedApplication, - deploy: bool, - ) -> Result { - let (response, _) = store - .accept( - crate::Actor::Daemon, - Mutation::Save { - application: Box::new(ApplicationTemplate::from(&application)), - expected_application_id: None, - deploy, - }, - None, - true, - None, - ) - .await?; - let MutationResponse::Saved(saved) = response else { - panic!("saved response") - }; - Ok(saved) - } - - #[tokio::test] - async fn installation_hostnames_and_subdomains_are_never_routed() { - let (_directory, store) = Store::temporary().await; - let early = app("early", Some("app.piqueld.example.com")); - let saved = save(&store, early.clone(), true).await.unwrap(); - let id = store.saved_production(&saved).await; - store - .stage_routes(&id, &early.spec().routes, true, None) - .await - .unwrap(); - - // Routes saved before the website hostname was configured are withheld. - let website = Hostname::parse("piqueld.example.com").unwrap(); - let conflicts = store - .reserve_installation_hostnames(std::slice::from_ref(&website)) - .await - .unwrap(); - assert_eq!(conflicts, [early.spec().routes[0].hostname.clone()]); - let table = store.routing_table().await.unwrap(); - assert_eq!(table[&id], []); - // The gateway can still acknowledge the table without them. - store.acknowledge_routes(&table).await.unwrap(); - - for hostname in ["piqueld.example.com", "api.piqueld.example.com"] { - assert!(matches!( - save(&store, app("late", Some(hostname)), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - } - save( - &store, - app("sibling", Some("notpiqueld.example.com")), - false, - ) - .await - .unwrap(); - } - - #[tokio::test] - async fn wildcards_keep_the_names_they_serve_from_other_applications() { - let (_directory, store) = Store::temporary().await; - // An exact name claimed first stays its owner's, and wins. - save( - &store, - app("exact", Some("early.tenants.example.com")), - false, - ) - .await - .unwrap(); - save(&store, app("tenants", Some("*.tenants.example.com")), false) - .await - .unwrap(); - assert!(matches!( - save(&store, app("other", Some("late.tenants.example.com")), false).await, - Err(StoreError::HostnameConflict { hostname }) if hostname == "late.tenants.example.com" - )); - // Names it does not match are free, and its own application may - // route exact names below it. - save( - &store, - app("other", Some("a.late.tenants.example.com")), - false, - ) - .await - .unwrap(); - let both = ["*.tenants.example.com", "admin.tenants.example.com"]; - save(&store, routed("tenants", &both), false).await.unwrap(); - } - - #[tokio::test] - async fn environments_of_one_application_cannot_share_a_hostname() { - let (_directory, store) = Store::temporary().await; - let saved = save(&store, app("one", Some("site.example.com")), false) - .await - .unwrap(); - let staging = Mutation::CreateEnvironment { - application: piqueld_core::ApplicationId::parse(&saved.application_id).unwrap(), - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: None, - }; - assert!(matches!( - store.force(staging).await, - Err(StoreError::SharedHostnameConflict { hostname, environment }) - if hostname == "site.example.com" && environment.as_str() == "production" - )); - assert_eq!( - store - .environments(&piqueld_core::ApplicationId::parse(saved.application_id).unwrap()) - .await - .unwrap() - .len(), - 1, - "failed creation rolls back the environment" - ); - } - - #[tokio::test] - async fn environments_render_their_own_hostnames_from_variables() { - let (_directory, store) = Store::temporary().await; - let template = template( - "notes", - "[spec.variables]\ndomain='piquel.fr'\n[spec.environments.production]\n[spec.environments.staging.variables]\ndomain='staging.piquel.fr'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'\n[[spec.routes]]\nhostname='${{ vars.domain }}'\nservice='web'\nport=80", - ); - let saved = store.save_template(template, false).await; - let application = piqueld_core::ApplicationId::parse(&saved.application_id).unwrap(); - // The manifest declares both environments. - let staging = store - .environments(&application) - .await - .unwrap() - .into_iter() - .find(|environment| environment.name.as_str() == "staging") - .unwrap(); - let production = store.production(&application).await; - let mut deployed = Vec::new(); - for environment in [&production, &staging.id] { - let (MutationResponse::Operation(operation), _) = store - .accept( - crate::Actor::Daemon, - Mutation::deploy(environment.clone()), - None, - true, - None, - ) - .await - .unwrap() - else { - panic!("operation response") - }; - let rendering = store - .deployment_snapshot(&operation.operation_id) - .await - .unwrap() - .rendering - .unwrap(); - deployed.push(rendering.application.spec().routes[0].hostname.to_string()); - } - assert_eq!(deployed, ["piquel.fr", "staging.piquel.fr"]); - assert!(matches!( - save(&store, app("other", Some("staging.piquel.fr")), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - - // Environments that render the same hostname still conflict. - let same = piqueld_core::edit::Variables { - defaults: [("domain".into(), Variable::String("piquel.fr".into()))].into(), - ..Default::default() - }; - let edit = Mutation::Edit { - id: application, - edit: Box::new(piqueld_core::edit::ApplicationEdit::Variables(same)), - deploy: false, - }; - assert!(matches!( - store.force(edit).await, - Err(StoreError::SharedHostnameConflict { hostname, environment }) - if hostname == "piquel.fr" && environment.as_str() == "production" - )); - } - - #[tokio::test] - async fn replacing_pending_deployment_releases_only_superseded_hostnames() { - let (_directory, store) = Store::temporary().await; - save(&store, app("one", Some("old.example.com")), true) - .await - .unwrap(); - save(&store, app("one", Some("new.example.com")), true) - .await - .unwrap(); - // Commit validates the final snapshot, after the new deployment has - // replaced the old captured input, rather than the intermediate save. - save(&store, app("two", Some("old.example.com")), false) - .await - .unwrap(); - assert!(matches!( - save(&store, app("three", Some("new.example.com")), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - } - - #[tokio::test] - async fn hostname_conflict_rolls_back_deployment_and_replay_receipt() { - let (_directory, store) = Store::temporary().await; - save(&store, app("one", Some("taken.example.com")), false) - .await - .unwrap(); - let saved = save(&store, app("two", None), false).await.unwrap(); - let id = store.saved_production(&saved).await; - let result = store - .accept( - crate::Actor::Daemon, - Mutation::Save { - application: Box::new(ApplicationTemplate::from(&app( - "two", - Some("taken.example.com"), - ))), - expected_application_id: None, - deploy: true, - }, - None, - true, - Some("conflicting-deploy"), - ) - .await; - assert!(matches!(result, Err(StoreError::HostnameConflict { .. }))); - assert_eq!( - store - .get(&id) - .await - .unwrap() - .manifest() - .unwrap() - .spec() - .routes, - [] as [piqueld_core::manifest::Route; 0] - ); - assert!( - store - .latest_operation_for_environment(&id) - .await - .unwrap() - .is_none() - ); - // The rejected request must not consume the replay key. - store - .accept( - crate::Actor::Daemon, - Mutation::Save { - application: Box::new(ApplicationTemplate::from(&app( - "two", - Some("free.example.com"), - ))), - expected_application_id: None, - deploy: true, - }, - None, - true, - Some("conflicting-deploy"), - ) - .await - .unwrap(); - } - - #[tokio::test] - async fn concurrent_saves_cannot_claim_the_same_hostname() { - let (_directory, store) = Store::temporary().await; - let (one, two) = tokio::join!( - save(&store, app("one", Some("site.example.com")), false), - save(&store, app("two", Some("SITE.EXAMPLE.COM.")), false) - ); - assert!(matches!( - (&one, &two), - (Ok(_), Err(StoreError::HostnameConflict { .. })) - | (Err(StoreError::HostnameConflict { .. }), Ok(_)) - )); - assert_eq!( - store.list(None, 10).await.unwrap().items.len(), - 1, - "failed reservation rolls back the entire save" - ); - } - - /// A stopped environment's routes are withdrawn from the gateway, while - /// it keeps their hostnames, certificates and DNS records, which follow - /// the complete table. Deploying it serves them again. - #[tokio::test] - async fn stopped_environments_keep_their_routes_unserved() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), true).await.unwrap(); - let id = store.saved_production(&saved).await; - let routes = &input.spec().routes; - store.stage_routes(&id, routes, true, None).await.unwrap(); - let accept = async |mutation| { - let accepted = store.accept(crate::Actor::Daemon, mutation, None, true, None); - accepted.await.unwrap(); - }; - - accept(Mutation::Stop { id: id.clone() }).await; - assert_eq!(store.served_table().await.unwrap()[&id], []); - assert_eq!(&store.routing_table().await.unwrap()[&id], routes); - store - .acknowledge_routes(&store.served_table().await.unwrap()) - .await - .unwrap(); - assert!(matches!( - save(&store, app("two", Some("site.example.com")), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - - accept(Mutation::deploy(id.clone())).await; - assert_eq!(&store.served_table().await.unwrap()[&id], routes); - } - - /// One hostname's routes read alone agree with the full tables. - #[tokio::test] - async fn one_hostnames_routes_match_the_tables() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - let hostname = RouteHostname::parse("site.example.com").unwrap(); - assert_eq!( - store.hostname_routes(&hostname).await.unwrap(), - HostnameRoutes::default() - ); - let routes = &input.spec().routes; - store.stage_routes(&id, routes, true, None).await.unwrap(); - let desired = HostnameRoutes { - desired: true, - ..HostnameRoutes::default() - }; - assert_eq!(store.hostname_routes(&hostname).await.unwrap(), desired); - store - .acknowledge_routes(&store.routing_table().await.unwrap()) - .await - .unwrap(); - store.track_dns_records(&hostname, false).await.unwrap(); - let applied = HostnameRoutes { - applied: Some(routes[0].visibility), - desired: true, - tracked: true, - }; - assert_eq!(store.hostname_routes(&hostname).await.unwrap(), applied); - // The installation's own hostnames are never desired routes. - let installation = Hostname::parse("example.com").unwrap(); - store - .reserve_installation_hostnames(std::slice::from_ref(&installation)) - .await - .unwrap(); - assert!(!store.hostname_routes(&hostname).await.unwrap().desired); - } - - #[tokio::test] - async fn only_changed_routes_are_acknowledged() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - store - .stage_routes(&id, &input.spec().routes, true, None) - .await - .unwrap(); - let table = store.routing_table().await.unwrap(); - assert!(store.acknowledge_routes(&table).await.unwrap()); - assert!(!store.acknowledge_routes(&table).await.unwrap()); - assert_eq!(store.applied_table().await.unwrap(), table); - store.stage_routes(&id, &[], true, None).await.unwrap(); - let withdrawn = store.routing_table().await.unwrap(); - assert!(store.acknowledge_routes(&withdrawn).await.unwrap()); - assert_eq!(store.applied_table().await.unwrap(), withdrawn); - } - - /// Concurrent acknowledgements run one at a time, in order, so the later - /// table ends up applied whole: the earlier one can't compare against - /// stale routes and leave half of each. - #[tokio::test] - async fn concurrent_acknowledgements_end_with_the_later_table() { - let (_directory, store) = Store::temporary().await; - let mut routes = Vec::new(); - for (name, hostname) in [("one", "one.example.com"), ("two", "two.example.com")] { - let input = app(name, Some(hostname)); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - store.stage_routes(&id, &[], true, None).await.unwrap(); - routes.push((id, input.spec().routes.clone())); - } - let [(one, one_routes), (two, two_routes)] = <[_; 2]>::try_from(routes).unwrap(); - let empty = RoutingTable::from([(one.clone(), vec![]), (two.clone(), vec![])]); - assert_eq!(store.applied_table().await.unwrap(), empty); - let earlier = RoutingTable::from([(one.clone(), one_routes), (two.clone(), vec![])]); - let later = RoutingTable::from([(one, vec![]), (two, two_routes)]); - - // Both queue behind a held acknowledgement, the earlier first: each - // is polled until it waits for the lock. - let held = store.acknowledgements.lock().await; - let mut first = std::pin::pin!(store.acknowledge_routes(&earlier)); - assert!(futures_util::poll!(first.as_mut()).is_pending()); - let mut second = std::pin::pin!(store.acknowledge_routes(&later)); - assert!(futures_util::poll!(second.as_mut()).is_pending()); - drop(held); - let (first, second) = tokio::join!(first, second); - assert!(first.unwrap() && second.unwrap()); - assert_eq!(store.applied_table().await.unwrap(), later); - } - - #[tokio::test] - async fn deployed_names_survive_disabled_ingress_and_failed_gateway_withdrawal() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - store - .stage_routes(&id, &input.spec().routes, true, None) - .await - .unwrap(); - store - .acknowledge_routes(&store.routing_table().await.unwrap()) - .await - .unwrap(); - save(&store, app("one", None), false).await.unwrap(); - assert!(matches!( - save(&store, app("two", Some("site.example.com")), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - store.stage_routes(&id, &[], true, None).await.unwrap(); - assert!( - matches!( - save(&store, app("two", Some("site.example.com")), false).await, - Err(StoreError::HostnameConflict { .. }) - ), - "last accepted configuration still reserves its host" - ); - store - .acknowledge_routes(&store.routing_table().await.unwrap()) - .await - .unwrap(); - save(&store, app("two", Some("site.example.com")), false) - .await - .unwrap(); - } - - #[tokio::test] - async fn captured_and_fetched_deployments_reserve_hostnames() { - let (_directory, store) = Store::temporary().await; - let saved = save(&store, app("one", Some("site.example.com")), true) - .await - .unwrap(); - save(&store, app("one", None), false).await.unwrap(); - assert!(matches!( - save(&store, app("two", Some("site.example.com")), false).await, - Err(StoreError::HostnameConflict { .. }) - )); - save(&store, app("two", Some("taken.example.com")), false) - .await - .unwrap(); - let operation = store.operation(&saved.operation_id.unwrap()).await.unwrap(); - store.mark_running(&operation.id).await; - let environment = store.get(&operation.environment_id).await.unwrap(); - let fetched = ApplicationTemplate::from(&app("one", Some("taken.example.com"))) - .with_id(environment.application.application.id().clone()); - let rendering = environment.render(&fetched, &operation.id).unwrap(); - assert!(matches!( - store - .save_deployment_input(&operation, (&fetched, None), &rendering, (None, None), &[]) - .await, - Err(StoreError::HostnameConflict { .. }) - )); - } - - #[tokio::test] - async fn superseded_operations_cannot_publish_routes() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), true).await.unwrap(); - let id = store.saved_production(&saved).await; - let operation = saved.operation_id.unwrap(); - store.mark_running(&operation).await; - save(&store, app("one", Some("new.example.com")), true) - .await - .unwrap(); - assert!(matches!( - store - .stage_routes(&id, &input.spec().routes, true, Some(&operation)) - .await, - Err(StoreError::IllegalTransition) - )); - assert!(store.routing_table().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn withdrawals_precede_cutover_and_repointing_waits_for_readiness() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - store - .stage_routes(&id, &input.spec().routes, true, None) - .await - .unwrap(); - let mut changed = input.spec().routes.clone(); - changed[0].target = - serde_json::from_value(serde_json::json!({"service":"web","port":3000})).unwrap(); - store - .stage_routes(&id, &changed, false, None) - .await - .unwrap(); - assert_eq!( - store.routing_table().await.unwrap()[&id][0] - .target - .to_string(), - "web:80" - ); - store.stage_routes(&id, &changed, true, None).await.unwrap(); - assert_eq!( - store.routing_table().await.unwrap()[&id][0] - .target - .to_string(), - "web:3000" - ); - store.stage_routes(&id, &[], false, None).await.unwrap(); - assert_eq!( - store.routing_table().await.unwrap()[&id], - [] as [piqueld_core::manifest::ValidatedRoute; 0] - ); - } - - #[tokio::test] - async fn changing_visibility_withdraws_the_route_until_backends_are_ready() { - let (_directory, store) = Store::temporary().await; - let input = app("one", Some("site.example.com")); - let saved = save(&store, input.clone(), false).await.unwrap(); - let id = store.saved_production(&saved).await; - let mut public = input.spec().routes.clone(); - public[0].visibility = piqueld_core::manifest::Visibility::Public; - store.stage_routes(&id, &public, true, None).await.unwrap(); - // Public -> private leaves the public listener as the deployment - // starts; the private route joins once backends are ready. - let private = input.spec().routes.clone(); - store - .stage_routes(&id, &private, false, None) - .await - .unwrap(); - assert_eq!( - store.routing_table().await.unwrap()[&id], - [] as [piqueld_core::manifest::ValidatedRoute; 0] - ); - store.stage_routes(&id, &private, true, None).await.unwrap(); - assert_eq!(store.routing_table().await.unwrap()[&id], private); - } - - #[tokio::test] - async fn route_statuses_are_limited_to_readable_applications() { - let (_directory, store) = Store::temporary().await; - let mut statuses = Vec::new(); - let mut applications = Vec::new(); - for (name, hostname) in [("one", "one.example.com"), ("two", "two.example.com")] { - let input = app(name, Some(hostname)); - let saved = save(&store, input.clone(), false).await.unwrap(); - let application = piqueld_core::ApplicationId::parse(saved.application_id).unwrap(); - let route = &input.spec().routes[0]; - statuses.push(RouteStatus { - name: None, - environment_id: store.production(&application).await.to_string(), - hostname: hostname.into(), - visibility: route.visibility, - dns: piqueld_core::api::DnsRecords::ServerAddresses { - addresses: Vec::new(), - }, - dns_state: piqueld_core::api::DnsRecordState::Manual, - target: route.target.clone(), - state: "ready".into(), - message: String::new(), - }); - applications.push(application); - } - let hostnames = |routes: Vec| { - routes - .into_iter() - .map(|route| route.hostname) - .collect::>() - }; - let all = store.readable_routes(&Scope::All, statuses.clone()).await; - assert_eq!( - hostnames(all.unwrap()), - ["one.example.com", "two.example.com"] - ); - let one = Scope::one(applications[0].clone()); - let limited = store.readable_routes(&one, statuses.clone()).await; - assert_eq!(hostnames(limited.unwrap()), ["one.example.com"]); - let none = store.readable_routes(&Scope::NONE, statuses).await; - assert_eq!(hostnames(none.unwrap()), [] as [String; 0]); - } -} +mod tests; diff --git a/crates/piqueld-store/src/ingress/tests.rs b/crates/piqueld-store/src/ingress/tests.rs new file mode 100644 index 000000000..e825d4c1c --- /dev/null +++ b/crates/piqueld-store/src/ingress/tests.rs @@ -0,0 +1,625 @@ +use super::*; +use crate::testing::template; +use crate::{Mutation, MutationResponse}; +use piqueld_core::NormalizedApplication; +use piqueld_core::manifest::{ApplicationTemplate, Variable}; +use std::fmt::Write as _; + +fn app(name: &str, hostname: Option<&str>) -> NormalizedApplication { + routed(name, hostname.as_slice()) +} + +/// An application routing each of `hostnames` to its service. +fn routed(name: &str, hostnames: &[&str]) -> NormalizedApplication { + let mut text = format!( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='{name}'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'" + ); + for hostname in hostnames { + write!( + text, + "\n[[spec.routes]]\nhostname='{hostname}'\nservice='web'\nport=80" + ) + .unwrap(); + } + piqueld_core::parse_toml(&text) + .unwrap() + .normalize(piqueld_core::ApplicationId::parse("input-app").unwrap()) +} + +async fn save( + store: &Store, + application: NormalizedApplication, + deploy: bool, +) -> Result { + let (response, _) = store + .accept( + crate::Actor::Daemon, + Mutation::Save { + application: Box::new(ApplicationTemplate::from(&application)), + expected_application_id: None, + deploy, + }, + None, + true, + None, + ) + .await?; + let MutationResponse::Saved(saved) = response else { + panic!("saved response") + }; + Ok(saved) +} + +#[tokio::test] +async fn installation_hostnames_and_subdomains_are_never_routed() { + let (_directory, store) = Store::temporary().await; + let early = app("early", Some("app.piqueld.example.com")); + let saved = save(&store, early.clone(), true).await.unwrap(); + let id = store.saved_production(&saved).await; + store + .stage_routes(&id, &early.spec().routes, true, None) + .await + .unwrap(); + + // Routes saved before the website hostname was configured are withheld. + let website = Hostname::parse("piqueld.example.com").unwrap(); + let conflicts = store + .reserve_installation_hostnames(std::slice::from_ref(&website)) + .await + .unwrap(); + assert_eq!(conflicts, [early.spec().routes[0].hostname.clone()]); + let table = store.routing_table().await.unwrap(); + assert_eq!(table[&id], []); + // The gateway can still acknowledge the table without them. + store.acknowledge_routes(&table).await.unwrap(); + + for hostname in ["piqueld.example.com", "api.piqueld.example.com"] { + assert!(matches!( + save(&store, app("late", Some(hostname)), false).await, + Err(StoreError::HostnameConflict { .. }) + )); + } + save( + &store, + app("sibling", Some("notpiqueld.example.com")), + false, + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn wildcards_keep_the_names_they_serve_from_other_applications() { + let (_directory, store) = Store::temporary().await; + // An exact name claimed first stays its owner's, and wins. + save( + &store, + app("exact", Some("early.tenants.example.com")), + false, + ) + .await + .unwrap(); + save(&store, app("tenants", Some("*.tenants.example.com")), false) + .await + .unwrap(); + assert!(matches!( + save(&store, app("other", Some("late.tenants.example.com")), false).await, + Err(StoreError::HostnameConflict { hostname }) if hostname == "late.tenants.example.com" + )); + // Names it does not match are free, and its own application may + // route exact names below it. + save( + &store, + app("other", Some("a.late.tenants.example.com")), + false, + ) + .await + .unwrap(); + let both = ["*.tenants.example.com", "admin.tenants.example.com"]; + save(&store, routed("tenants", &both), false).await.unwrap(); +} + +#[tokio::test] +async fn environments_of_one_application_cannot_share_a_hostname() { + let (_directory, store) = Store::temporary().await; + let saved = save(&store, app("one", Some("site.example.com")), false) + .await + .unwrap(); + let staging = Mutation::CreateEnvironment { + application: piqueld_core::ApplicationId::parse(&saved.application_id).unwrap(), + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: None, + }; + assert!(matches!( + store.force(staging).await, + Err(StoreError::SharedHostnameConflict { hostname, environment }) + if hostname == "site.example.com" && environment.as_str() == "production" + )); + assert_eq!( + store + .environments(&piqueld_core::ApplicationId::parse(saved.application_id).unwrap()) + .await + .unwrap() + .len(), + 1, + "failed creation rolls back the environment" + ); +} + +#[tokio::test] +async fn environments_render_their_own_hostnames_from_variables() { + let (_directory, store) = Store::temporary().await; + let template = template( + "notes", + "[spec.variables]\ndomain='piquel.fr'\n[spec.environments.production]\n[spec.environments.staging.variables]\ndomain='staging.piquel.fr'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'\n[[spec.routes]]\nhostname='${{ vars.domain }}'\nservice='web'\nport=80", + ); + let saved = store.save_template(template, false).await; + let application = piqueld_core::ApplicationId::parse(&saved.application_id).unwrap(); + // The manifest declares both environments. + let staging = store + .environments(&application) + .await + .unwrap() + .into_iter() + .find(|environment| environment.name.as_str() == "staging") + .unwrap(); + let production = store.production(&application).await; + let mut deployed = Vec::new(); + for environment in [&production, &staging.id] { + let (MutationResponse::Operation(operation), _) = store + .accept( + crate::Actor::Daemon, + Mutation::deploy(environment.clone()), + None, + true, + None, + ) + .await + .unwrap() + else { + panic!("operation response") + }; + let rendering = store + .deployment_snapshot(&operation.operation_id) + .await + .unwrap() + .rendering + .unwrap(); + deployed.push(rendering.application.spec().routes[0].hostname.to_string()); + } + assert_eq!(deployed, ["piquel.fr", "staging.piquel.fr"]); + assert!(matches!( + save(&store, app("other", Some("staging.piquel.fr")), false).await, + Err(StoreError::HostnameConflict { .. }) + )); + + // Environments that render the same hostname still conflict. + let same = piqueld_core::edit::Variables { + defaults: [("domain".into(), Variable::String("piquel.fr".into()))].into(), + ..Default::default() + }; + let edit = Mutation::Edit { + id: application, + edit: Box::new(piqueld_core::edit::ApplicationEdit::Variables(same)), + deploy: false, + }; + assert!(matches!( + store.force(edit).await, + Err(StoreError::SharedHostnameConflict { hostname, environment }) + if hostname == "piquel.fr" && environment.as_str() == "production" + )); +} + +#[tokio::test] +async fn replacing_pending_deployment_releases_only_superseded_hostnames() { + let (_directory, store) = Store::temporary().await; + save(&store, app("one", Some("old.example.com")), true) + .await + .unwrap(); + save(&store, app("one", Some("new.example.com")), true) + .await + .unwrap(); + // Commit validates the final snapshot, after the new deployment has + // replaced the old captured input, rather than the intermediate save. + save(&store, app("two", Some("old.example.com")), false) + .await + .unwrap(); + assert!(matches!( + save(&store, app("three", Some("new.example.com")), false).await, + Err(StoreError::HostnameConflict { .. }) + )); +} + +#[tokio::test] +async fn hostname_conflict_rolls_back_deployment_and_replay_receipt() { + let (_directory, store) = Store::temporary().await; + save(&store, app("one", Some("taken.example.com")), false) + .await + .unwrap(); + let saved = save(&store, app("two", None), false).await.unwrap(); + let id = store.saved_production(&saved).await; + let result = store + .accept( + crate::Actor::Daemon, + Mutation::Save { + application: Box::new(ApplicationTemplate::from(&app( + "two", + Some("taken.example.com"), + ))), + expected_application_id: None, + deploy: true, + }, + None, + true, + Some("conflicting-deploy"), + ) + .await; + assert!(matches!(result, Err(StoreError::HostnameConflict { .. }))); + assert_eq!( + store + .get(&id) + .await + .unwrap() + .manifest() + .unwrap() + .spec() + .routes, + [] as [piqueld_core::manifest::Route; 0] + ); + assert!( + store + .latest_operation_for_environment(&id) + .await + .unwrap() + .is_none() + ); + // The rejected request must not consume the replay key. + store + .accept( + crate::Actor::Daemon, + Mutation::Save { + application: Box::new(ApplicationTemplate::from(&app( + "two", + Some("free.example.com"), + ))), + expected_application_id: None, + deploy: true, + }, + None, + true, + Some("conflicting-deploy"), + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn concurrent_saves_cannot_claim_the_same_hostname() { + let (_directory, store) = Store::temporary().await; + let (one, two) = tokio::join!( + save(&store, app("one", Some("site.example.com")), false), + save(&store, app("two", Some("SITE.EXAMPLE.COM.")), false) + ); + assert!(matches!( + (&one, &two), + (Ok(_), Err(StoreError::HostnameConflict { .. })) + | (Err(StoreError::HostnameConflict { .. }), Ok(_)) + )); + assert_eq!( + store.list(None, 10).await.unwrap().items.len(), + 1, + "failed reservation rolls back the entire save" + ); +} + +/// A stopped environment's routes are withdrawn from the gateway, while +/// it keeps their hostnames, certificates and DNS records, which follow +/// the complete table. Deploying it serves them again. +#[tokio::test] +async fn stopped_environments_keep_their_routes_unserved() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), true).await.unwrap(); + let id = store.saved_production(&saved).await; + let routes = &input.spec().routes; + store.stage_routes(&id, routes, true, None).await.unwrap(); + let accept = async |mutation| { + let accepted = store.accept(crate::Actor::Daemon, mutation, None, true, None); + accepted.await.unwrap(); + }; + + accept(Mutation::Stop { id: id.clone() }).await; + assert_eq!(store.served_table().await.unwrap()[&id], []); + assert_eq!(&store.routing_table().await.unwrap()[&id], routes); + store + .acknowledge_routes(&store.served_table().await.unwrap()) + .await + .unwrap(); + assert!(matches!( + save(&store, app("two", Some("site.example.com")), false).await, + Err(StoreError::HostnameConflict { .. }) + )); + + accept(Mutation::deploy(id.clone())).await; + assert_eq!(&store.served_table().await.unwrap()[&id], routes); +} + +/// One hostname's routes read alone agree with the full tables. +#[tokio::test] +async fn one_hostnames_routes_match_the_tables() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + let hostname = RouteHostname::parse("site.example.com").unwrap(); + assert_eq!( + store.hostname_routes(&hostname).await.unwrap(), + HostnameRoutes::default() + ); + let routes = &input.spec().routes; + store.stage_routes(&id, routes, true, None).await.unwrap(); + let desired = HostnameRoutes { + desired: true, + ..HostnameRoutes::default() + }; + assert_eq!(store.hostname_routes(&hostname).await.unwrap(), desired); + store + .acknowledge_routes(&store.routing_table().await.unwrap()) + .await + .unwrap(); + store.track_dns_records(&hostname, false).await.unwrap(); + let applied = HostnameRoutes { + applied: Some(routes[0].visibility), + desired: true, + tracked: true, + }; + assert_eq!(store.hostname_routes(&hostname).await.unwrap(), applied); + // The installation's own hostnames are never desired routes. + let installation = Hostname::parse("example.com").unwrap(); + store + .reserve_installation_hostnames(std::slice::from_ref(&installation)) + .await + .unwrap(); + assert!(!store.hostname_routes(&hostname).await.unwrap().desired); +} + +#[tokio::test] +async fn only_changed_routes_are_acknowledged() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + store + .stage_routes(&id, &input.spec().routes, true, None) + .await + .unwrap(); + let table = store.routing_table().await.unwrap(); + assert!(store.acknowledge_routes(&table).await.unwrap()); + assert!(!store.acknowledge_routes(&table).await.unwrap()); + assert_eq!(store.applied_table().await.unwrap(), table); + store.stage_routes(&id, &[], true, None).await.unwrap(); + let withdrawn = store.routing_table().await.unwrap(); + assert!(store.acknowledge_routes(&withdrawn).await.unwrap()); + assert_eq!(store.applied_table().await.unwrap(), withdrawn); +} + +/// Concurrent acknowledgements run one at a time, in order, so the later +/// table ends up applied whole: the earlier one can't compare against +/// stale routes and leave half of each. +#[tokio::test] +async fn concurrent_acknowledgements_end_with_the_later_table() { + let (_directory, store) = Store::temporary().await; + let mut routes = Vec::new(); + for (name, hostname) in [("one", "one.example.com"), ("two", "two.example.com")] { + let input = app(name, Some(hostname)); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + store.stage_routes(&id, &[], true, None).await.unwrap(); + routes.push((id, input.spec().routes.clone())); + } + let [(one, one_routes), (two, two_routes)] = <[_; 2]>::try_from(routes).unwrap(); + let empty = RoutingTable::from([(one.clone(), vec![]), (two.clone(), vec![])]); + assert_eq!(store.applied_table().await.unwrap(), empty); + let earlier = RoutingTable::from([(one.clone(), one_routes), (two.clone(), vec![])]); + let later = RoutingTable::from([(one, vec![]), (two, two_routes)]); + + // Both queue behind a held acknowledgement, the earlier first: each + // is polled until it waits for the lock. + let held = store.acknowledgements.lock().await; + let mut first = std::pin::pin!(store.acknowledge_routes(&earlier)); + assert!(futures_util::poll!(first.as_mut()).is_pending()); + let mut second = std::pin::pin!(store.acknowledge_routes(&later)); + assert!(futures_util::poll!(second.as_mut()).is_pending()); + drop(held); + let (first, second) = tokio::join!(first, second); + assert!(first.unwrap() && second.unwrap()); + assert_eq!(store.applied_table().await.unwrap(), later); +} + +#[tokio::test] +async fn deployed_names_survive_disabled_ingress_and_failed_gateway_withdrawal() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + store + .stage_routes(&id, &input.spec().routes, true, None) + .await + .unwrap(); + store + .acknowledge_routes(&store.routing_table().await.unwrap()) + .await + .unwrap(); + save(&store, app("one", None), false).await.unwrap(); + assert!(matches!( + save(&store, app("two", Some("site.example.com")), false).await, + Err(StoreError::HostnameConflict { .. }) + )); + store.stage_routes(&id, &[], true, None).await.unwrap(); + assert!( + matches!( + save(&store, app("two", Some("site.example.com")), false).await, + Err(StoreError::HostnameConflict { .. }) + ), + "last accepted configuration still reserves its host" + ); + store + .acknowledge_routes(&store.routing_table().await.unwrap()) + .await + .unwrap(); + save(&store, app("two", Some("site.example.com")), false) + .await + .unwrap(); +} + +#[tokio::test] +async fn captured_and_fetched_deployments_reserve_hostnames() { + let (_directory, store) = Store::temporary().await; + let saved = save(&store, app("one", Some("site.example.com")), true) + .await + .unwrap(); + save(&store, app("one", None), false).await.unwrap(); + assert!(matches!( + save(&store, app("two", Some("site.example.com")), false).await, + Err(StoreError::HostnameConflict { .. }) + )); + save(&store, app("two", Some("taken.example.com")), false) + .await + .unwrap(); + let operation = store.operation(&saved.operation_id.unwrap()).await.unwrap(); + store.mark_running(&operation.id).await; + let environment = store.get(&operation.environment_id).await.unwrap(); + let fetched = ApplicationTemplate::from(&app("one", Some("taken.example.com"))) + .with_id(environment.application.application.id().clone()); + let rendering = environment.render(&fetched, &operation.id).unwrap(); + assert!(matches!( + store + .save_deployment_input(&operation, (&fetched, None), &rendering, (None, None), &[]) + .await, + Err(StoreError::HostnameConflict { .. }) + )); +} + +#[tokio::test] +async fn superseded_operations_cannot_publish_routes() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), true).await.unwrap(); + let id = store.saved_production(&saved).await; + let operation = saved.operation_id.unwrap(); + store.mark_running(&operation).await; + save(&store, app("one", Some("new.example.com")), true) + .await + .unwrap(); + assert!(matches!( + store + .stage_routes(&id, &input.spec().routes, true, Some(&operation)) + .await, + Err(StoreError::IllegalTransition) + )); + assert!(store.routing_table().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn withdrawals_precede_cutover_and_repointing_waits_for_readiness() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + store + .stage_routes(&id, &input.spec().routes, true, None) + .await + .unwrap(); + let mut changed = input.spec().routes.clone(); + changed[0].target = + serde_json::from_value(serde_json::json!({"service":"web","port":3000})).unwrap(); + store + .stage_routes(&id, &changed, false, None) + .await + .unwrap(); + assert_eq!( + store.routing_table().await.unwrap()[&id][0] + .target + .to_string(), + "web:80" + ); + store.stage_routes(&id, &changed, true, None).await.unwrap(); + assert_eq!( + store.routing_table().await.unwrap()[&id][0] + .target + .to_string(), + "web:3000" + ); + store.stage_routes(&id, &[], false, None).await.unwrap(); + assert_eq!( + store.routing_table().await.unwrap()[&id], + [] as [piqueld_core::manifest::ValidatedRoute; 0] + ); +} + +#[tokio::test] +async fn changing_visibility_withdraws_the_route_until_backends_are_ready() { + let (_directory, store) = Store::temporary().await; + let input = app("one", Some("site.example.com")); + let saved = save(&store, input.clone(), false).await.unwrap(); + let id = store.saved_production(&saved).await; + let mut public = input.spec().routes.clone(); + public[0].visibility = piqueld_core::manifest::Visibility::Public; + store.stage_routes(&id, &public, true, None).await.unwrap(); + // Public -> private leaves the public listener as the deployment + // starts; the private route joins once backends are ready. + let private = input.spec().routes.clone(); + store + .stage_routes(&id, &private, false, None) + .await + .unwrap(); + assert_eq!( + store.routing_table().await.unwrap()[&id], + [] as [piqueld_core::manifest::ValidatedRoute; 0] + ); + store.stage_routes(&id, &private, true, None).await.unwrap(); + assert_eq!(store.routing_table().await.unwrap()[&id], private); +} + +#[tokio::test] +async fn route_statuses_are_limited_to_readable_applications() { + let (_directory, store) = Store::temporary().await; + let mut statuses = Vec::new(); + let mut applications = Vec::new(); + for (name, hostname) in [("one", "one.example.com"), ("two", "two.example.com")] { + let input = app(name, Some(hostname)); + let saved = save(&store, input.clone(), false).await.unwrap(); + let application = piqueld_core::ApplicationId::parse(saved.application_id).unwrap(); + let route = &input.spec().routes[0]; + statuses.push(RouteStatus { + name: None, + environment_id: store.production(&application).await.to_string(), + hostname: hostname.into(), + visibility: route.visibility, + dns: piqueld_core::api::DnsRecords::ServerAddresses { + addresses: Vec::new(), + }, + dns_state: piqueld_core::api::DnsRecordState::Manual, + target: route.target.clone(), + state: "ready".into(), + message: String::new(), + }); + applications.push(application); + } + let hostnames = |routes: Vec| { + routes + .into_iter() + .map(|route| route.hostname) + .collect::>() + }; + let all = store.readable_routes(&Scope::All, statuses.clone()).await; + assert_eq!( + hostnames(all.unwrap()), + ["one.example.com", "two.example.com"] + ); + let one = Scope::one(applications[0].clone()); + let limited = store.readable_routes(&one, statuses.clone()).await; + assert_eq!(hostnames(limited.unwrap()), ["one.example.com"]); + let none = store.readable_routes(&Scope::NONE, statuses).await; + assert_eq!(hostnames(none.unwrap()), [] as [String; 0]); +} diff --git a/crates/piqueld-store/src/jobs.rs b/crates/piqueld-store/src/jobs.rs deleted file mode 100644 index 2c395b3f5..000000000 --- a/crates/piqueld-store/src/jobs.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Durable requests to stop job runs, independent of deployment retries. -use super::{EnvironmentId, Store, StoreError}; -use sqlx::SqliteConnection; - -impl Store { - /// Saves cleanup intent before attempting to stop an operation's job runs. - /// - /// # Errors - /// Returns a storage error. - pub async fn request_job_cleanup(&self, operation: &str) -> Result<(), StoreError> { - let _writer = self.writers.lock().await; - Self::request_job_cleanup_on(&mut *self.connection().await?, operation).await - } - - /// Also used inside the transaction that records a terminal job failure, - /// so failed persistence of the earlier request cannot lose cleanup intent. - pub(super) async fn request_job_cleanup_on( - connection: &mut SqliteConnection, - operation: &str, - ) -> Result<(), StoreError> { - sqlx::query!( - "INSERT INTO job_cleanup(operation_id) VALUES(?1) ON CONFLICT DO NOTHING", - operation - ) - .execute(connection) - .await - .map_err(StoreError::constraint)?; - Ok(()) - } - - /// Finds pending cleanup, including runs from superseded operations. - /// - /// # Errors - /// Returns a storage error. - pub async fn pending_job_cleanup( - &self, - environment: &EnvironmentId, - ) -> Result, StoreError> { - let environment = environment.as_str(); - sqlx::query_scalar!( - "SELECT job_cleanup.operation_id FROM job_cleanup JOIN operations ON operations.id=job_cleanup.operation_id WHERE operations.environment_id=?1 ORDER BY job_cleanup.operation_id", - environment - ) - .fetch_all(&self.pool) - .await - .map_err(StoreError::database) - } - - /// Clears intent only after Docker confirms the job containers have stopped. - /// - /// # Errors - /// Returns a storage error. - pub async fn finish_job_cleanup(&self, operation: &str) -> Result<(), StoreError> { - self.write(sqlx::query!( - "DELETE FROM job_cleanup WHERE operation_id=?1", - operation - )) - .await - .map_err(StoreError::database)?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::OperationState; - use piqueld_core::manifest::ApplicationTemplate; - - #[tokio::test] - async fn terminal_job_failure_keeps_cleanup_atomic_and_retained() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("db"); - let store = Store::open_unsynced(&path).await.unwrap(); - let application = piqueld_core::parse_toml( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='jobs'\n[spec]", - ) - .unwrap() - .normalize(piqueld_core::ApplicationId::parse("app-jobs").unwrap()); - let operation = store - .save_application(&ApplicationTemplate::from(&application), None, None) - .await - .unwrap(); - store.mark_running(&operation.id).await; - - // A terminal failure cannot commit without its cleanup request, even - // if the earlier request from job execution could not be persisted. - sqlx::query("CREATE TRIGGER reject_cleanup BEFORE INSERT ON job_cleanup BEGIN SELECT RAISE(FAIL,'cleanup storage unavailable'); END") - .execute(&store.pool).await.unwrap(); - assert!( - store - .transition_operation( - &operation.id, - OperationState::Running, - OperationState::Failed, - Some(("job_timeout", "migration timed out")) - ) - .await - .is_err() - ); - assert_eq!( - store.operation(&operation.id).await.unwrap().state, - OperationState::Running - ); - sqlx::query("DROP TRIGGER reject_cleanup") - .execute(&store.pool) - .await - .unwrap(); - store - .transition_operation( - &operation.id, - OperationState::Running, - OperationState::Failed, - Some(("job_timeout", "migration timed out")), - ) - .await - .unwrap(); - drop(store); - - let store = Store::open_unsynced(&path).await.unwrap(); - assert_eq!( - store - .pending_job_cleanup(&operation.environment_id) - .await - .unwrap(), - std::slice::from_ref(&operation.id) - ); - store - .save_application( - &ApplicationTemplate::from(&application), - None, - Some(operation.generation), - ) - .await - .unwrap(); - // Model expiry of the old deployment snapshot; operation retention - // must still preserve the cleanup request and its journal context. - sqlx::query("DELETE FROM deployments WHERE id=?1") - .bind(&operation.id) - .execute(&store.pool) - .await - .unwrap(); - assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 0); - assert_eq!( - store - .pending_job_cleanup(&operation.environment_id) - .await - .unwrap(), - std::slice::from_ref(&operation.id) - ); - store.finish_job_cleanup(&operation.id).await.unwrap(); - assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 1); - } -} diff --git a/crates/piqueld-store/src/jobs/mod.rs b/crates/piqueld-store/src/jobs/mod.rs new file mode 100644 index 000000000..e81e8e91b --- /dev/null +++ b/crates/piqueld-store/src/jobs/mod.rs @@ -0,0 +1,65 @@ +//! Durable requests to stop job runs, independent of deployment retries. +use super::{EnvironmentId, Store, StoreError}; +use sqlx::SqliteConnection; + +impl Store { + /// Saves cleanup intent before attempting to stop an operation's job runs. + /// + /// # Errors + /// Returns a storage error. + pub async fn request_job_cleanup(&self, operation: &str) -> Result<(), StoreError> { + let _writer = self.writers.lock().await; + Self::request_job_cleanup_on(&mut *self.connection().await?, operation).await + } + + /// Also used inside the transaction that records a terminal job failure, + /// so failed persistence of the earlier request cannot lose cleanup intent. + pub(super) async fn request_job_cleanup_on( + connection: &mut SqliteConnection, + operation: &str, + ) -> Result<(), StoreError> { + sqlx::query!( + "INSERT INTO job_cleanup(operation_id) VALUES(?1) ON CONFLICT DO NOTHING", + operation + ) + .execute(connection) + .await + .map_err(StoreError::constraint)?; + Ok(()) + } + + /// Finds pending cleanup, including runs from superseded operations. + /// + /// # Errors + /// Returns a storage error. + pub async fn pending_job_cleanup( + &self, + environment: &EnvironmentId, + ) -> Result, StoreError> { + let environment = environment.as_str(); + sqlx::query_scalar!( + "SELECT job_cleanup.operation_id FROM job_cleanup JOIN operations ON operations.id=job_cleanup.operation_id WHERE operations.environment_id=?1 ORDER BY job_cleanup.operation_id", + environment + ) + .fetch_all(&self.pool) + .await + .map_err(StoreError::database) + } + + /// Clears intent only after Docker confirms the job containers have stopped. + /// + /// # Errors + /// Returns a storage error. + pub async fn finish_job_cleanup(&self, operation: &str) -> Result<(), StoreError> { + self.write(sqlx::query!( + "DELETE FROM job_cleanup WHERE operation_id=?1", + operation + )) + .await + .map_err(StoreError::database)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/piqueld-store/src/jobs/tests.rs b/crates/piqueld-store/src/jobs/tests.rs new file mode 100644 index 000000000..be0da4426 --- /dev/null +++ b/crates/piqueld-store/src/jobs/tests.rs @@ -0,0 +1,88 @@ +use super::*; +use crate::OperationState; +use piqueld_core::manifest::ApplicationTemplate; + +#[tokio::test] +async fn terminal_job_failure_keeps_cleanup_atomic_and_retained() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("db"); + let store = Store::open_unsynced(&path).await.unwrap(); + let application = piqueld_core::parse_toml( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='jobs'\n[spec]", + ) + .unwrap() + .normalize(piqueld_core::ApplicationId::parse("app-jobs").unwrap()); + let operation = store + .save_application(&ApplicationTemplate::from(&application), None, None) + .await + .unwrap(); + store.mark_running(&operation.id).await; + + // A terminal failure cannot commit without its cleanup request, even + // if the earlier request from job execution could not be persisted. + sqlx::query("CREATE TRIGGER reject_cleanup BEFORE INSERT ON job_cleanup BEGIN SELECT RAISE(FAIL,'cleanup storage unavailable'); END") + .execute(&store.pool).await.unwrap(); + assert!( + store + .transition_operation( + &operation.id, + OperationState::Running, + OperationState::Failed, + Some(("job_timeout", "migration timed out")) + ) + .await + .is_err() + ); + assert_eq!( + store.operation(&operation.id).await.unwrap().state, + OperationState::Running + ); + sqlx::query("DROP TRIGGER reject_cleanup") + .execute(&store.pool) + .await + .unwrap(); + store + .transition_operation( + &operation.id, + OperationState::Running, + OperationState::Failed, + Some(("job_timeout", "migration timed out")), + ) + .await + .unwrap(); + drop(store); + + let store = Store::open_unsynced(&path).await.unwrap(); + assert_eq!( + store + .pending_job_cleanup(&operation.environment_id) + .await + .unwrap(), + std::slice::from_ref(&operation.id) + ); + store + .save_application( + &ApplicationTemplate::from(&application), + None, + Some(operation.generation), + ) + .await + .unwrap(); + // Model expiry of the old deployment snapshot; operation retention + // must still preserve the cleanup request and its journal context. + sqlx::query("DELETE FROM deployments WHERE id=?1") + .bind(&operation.id) + .execute(&store.pool) + .await + .unwrap(); + assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 0); + assert_eq!( + store + .pending_job_cleanup(&operation.environment_id) + .await + .unwrap(), + std::slice::from_ref(&operation.id) + ); + store.finish_job_cleanup(&operation.id).await.unwrap(); + assert_eq!(store.prune_finished_operations(i64::MAX).await.unwrap(), 1); +} diff --git a/crates/piqueld-store/src/observability/traffic.rs b/crates/piqueld-store/src/observability/traffic/mod.rs similarity index 68% rename from crates/piqueld-store/src/observability/traffic.rs rename to crates/piqueld-store/src/observability/traffic/mod.rs index 253bc00b4..0140eb83a 100644 --- a/crates/piqueld-store/src/observability/traffic.rs +++ b/crates/piqueld-store/src/observability/traffic/mod.rs @@ -357,179 +357,4 @@ impl Store { } #[cfg(test)] -mod tests { - use super::*; - use crate::{now_ms, testing::template}; - - /// The `web` service's route on `hostname` of environment `id`. - fn route(id: &EnvironmentId, hostname: &str) -> TrafficRoute { - TrafficRoute { - environment: id.clone(), - service: "web".into(), - hostname: hostname.into(), - } - } - - /// A temporary store with one environment. - async fn environment() -> (tempfile::TempDir, Store, EnvironmentId) { - let (directory, store) = Store::temporary().await; - let saved = store.save_template(template("site", "[spec]"), false).await; - let id = store.saved_production(&saved).await; - (directory, store, id) - } - - /// Every traffic of `id` from `since_ms` until `until_ms`. - fn window(since_ms: i64, until_ms: i64) -> TrafficQuery<'static> { - TrafficQuery { - since_ms, - until_ms, - service: None, - hostname: None, - } - } - - #[tokio::test] - async fn tallies_add_up_into_hourly_and_daily_points() { - let (_directory, store, id) = environment().await; - let day = 20_000 * DAY_MS; - let mut tally = TrafficTally::default(); - let views = HourCounts { - requests: 3, - page_views: 2, - visitors: 1, - duration_us: 3_000, - ..HourCounts::default() - }; - let failure = HourCounts { - requests: 1, - server_errors: 1, - ..HourCounts::default() - }; - tally - .hours - .insert((route(&id, "a.example.com"), day + HOUR_MS), views); - tally - .hours - .insert((route(&id, "b.example.com"), day + 30 * HOUR_MS), failure); - let page = (route(&id, "a.example.com"), day, RankKind::Page, "/".into()); - tally.ranks.insert(page, 2); - // A second flush adds to the first. - store.record_traffic(&tally).await.unwrap(); - store.record_traffic(&tally).await.unwrap(); - - // A window ending within an hour includes that hour whole. - let partial = store - .traffic(&id, window(day, day + HOUR_MS + 1)) - .await - .unwrap(); - assert_eq!( - (partial.until_ms, partial.totals.requests), - (day + 2 * HOUR_MS, 6) - ); - // The latest end the API accepts still rounds to a whole hour. - let latest = store - .traffic(&id, window(i64::MAX - DAY_MS, i64::MAX)) - .await - .unwrap(); - assert_eq!(latest.until_ms % HOUR_MS, 0); - let report = store - .traffic(&id, window(day, day + 2 * DAY_MS)) - .await - .unwrap(); - assert_eq!((report.bucket_ms, report.series.len()), (HOUR_MS, 48)); - assert_eq!(report.series[1].counts.requests, 6); - assert_eq!(report.series[30].counts.server_errors, 2); - assert_eq!( - ( - report.totals.requests, - report.totals.page_views, - report.totals.visitors - ), - (8, 4, 2) - ); - assert_eq!(report.totals.mean_duration_ms, Some(0.75)); - let hostnames: Vec<_> = report.routes.iter().map(|r| r.hostname.as_str()).collect(); - assert_eq!(hostnames, ["a.example.com", "b.example.com"]); - let viewed = TrafficRank { - value: "/".into(), - page_views: 4, - }; - assert_eq!(report.pages, [viewed]); - - // Longer windows have daily points, from the start of a day. - let only_b = TrafficQuery { - hostname: Some("b.example.com"), - ..window(day + 5, day + 7 * DAY_MS) - }; - let daily = store.traffic(&id, only_b).await.unwrap(); - assert_eq!((daily.bucket_ms, daily.since_ms), (DAY_MS, day)); - assert_eq!(daily.series.len(), 7); - assert_eq!(daily.series[1].counts.requests, 2); - assert_eq!(daily.totals.requests, 2); - assert_eq!(daily.pages, []); - } - - #[tokio::test] - async fn ranks_stop_growing_at_their_limit_and_old_counts_are_pruned() { - let (_directory, mut store, id) = environment().await; - let now = now_ms(); - let today = now - now.rem_euclid(DAY_MS); - let page = |value: String| (route(&id, "a.example.com"), today, RankKind::Page, value); - let mut tally = TrafficTally::default(); - for index in 0..=TRAFFIC_RANK_LIMIT { - tally.ranks.insert(page(format!("/{index}")), 1); - } - store.record_traffic(&tally).await.unwrap(); - // A page already counted still counts once the day is full. - let mut again = TrafficTally::default(); - again.ranks.insert(page("/0".into()), 5); - store.record_traffic(&again).await.unwrap(); - let ranks = sqlx::query_scalar!("SELECT COUNT(*) FROM traffic_ranks") - .fetch_one(&store.pool) - .await - .unwrap(); - assert_eq!(ranks, TRAFFIC_RANK_LIMIT); - let report = store - .traffic(&id, window(today, today + DAY_MS)) - .await - .unwrap(); - assert_eq!(report.pages.len(), 20); - assert_eq!( - (report.pages[0].value.as_str(), report.pages[0].page_views), - ("/0", 6) - ); - - let old = today - 3 * DAY_MS; - let mut tally = TrafficTally::default(); - let counts = HourCounts { - requests: 1, - ..HourCounts::default() - }; - tally - .hours - .insert((route(&id, "a.example.com"), old), counts); - tally - .hours - .insert((route(&id, "a.example.com"), today), counts); - let old_page = ( - route(&id, "a.example.com"), - old, - RankKind::Page, - "/old".into(), - ); - tally.ranks.insert(old_page, 50); - store.record_traffic(&tally).await.unwrap(); - store.traffic_days = 1; - store.prune_traffic().await.unwrap(); - let report = store - .traffic(&id, window(old, today + DAY_MS)) - .await - .unwrap(); - assert_eq!(report.totals.requests, 1); - assert!( - report.pages.iter().all(|page| page.value != "/old"), - "ranks of pruned days are removed too" - ); - assert_eq!(report.pages[0].value, "/0"); - } -} +mod tests; diff --git a/crates/piqueld-store/src/observability/traffic/tests.rs b/crates/piqueld-store/src/observability/traffic/tests.rs new file mode 100644 index 000000000..1d70533ad --- /dev/null +++ b/crates/piqueld-store/src/observability/traffic/tests.rs @@ -0,0 +1,174 @@ +use super::*; +use crate::{now_ms, testing::template}; + +/// The `web` service's route on `hostname` of environment `id`. +fn route(id: &EnvironmentId, hostname: &str) -> TrafficRoute { + TrafficRoute { + environment: id.clone(), + service: "web".into(), + hostname: hostname.into(), + } +} + +/// A temporary store with one environment. +async fn environment() -> (tempfile::TempDir, Store, EnvironmentId) { + let (directory, store) = Store::temporary().await; + let saved = store.save_template(template("site", "[spec]"), false).await; + let id = store.saved_production(&saved).await; + (directory, store, id) +} + +/// Every traffic of `id` from `since_ms` until `until_ms`. +fn window(since_ms: i64, until_ms: i64) -> TrafficQuery<'static> { + TrafficQuery { + since_ms, + until_ms, + service: None, + hostname: None, + } +} + +#[tokio::test] +async fn tallies_add_up_into_hourly_and_daily_points() { + let (_directory, store, id) = environment().await; + let day = 20_000 * DAY_MS; + let mut tally = TrafficTally::default(); + let views = HourCounts { + requests: 3, + page_views: 2, + visitors: 1, + duration_us: 3_000, + ..HourCounts::default() + }; + let failure = HourCounts { + requests: 1, + server_errors: 1, + ..HourCounts::default() + }; + tally + .hours + .insert((route(&id, "a.example.com"), day + HOUR_MS), views); + tally + .hours + .insert((route(&id, "b.example.com"), day + 30 * HOUR_MS), failure); + let page = (route(&id, "a.example.com"), day, RankKind::Page, "/".into()); + tally.ranks.insert(page, 2); + // A second flush adds to the first. + store.record_traffic(&tally).await.unwrap(); + store.record_traffic(&tally).await.unwrap(); + + // A window ending within an hour includes that hour whole. + let partial = store + .traffic(&id, window(day, day + HOUR_MS + 1)) + .await + .unwrap(); + assert_eq!( + (partial.until_ms, partial.totals.requests), + (day + 2 * HOUR_MS, 6) + ); + // The latest end the API accepts still rounds to a whole hour. + let latest = store + .traffic(&id, window(i64::MAX - DAY_MS, i64::MAX)) + .await + .unwrap(); + assert_eq!(latest.until_ms % HOUR_MS, 0); + let report = store + .traffic(&id, window(day, day + 2 * DAY_MS)) + .await + .unwrap(); + assert_eq!((report.bucket_ms, report.series.len()), (HOUR_MS, 48)); + assert_eq!(report.series[1].counts.requests, 6); + assert_eq!(report.series[30].counts.server_errors, 2); + assert_eq!( + ( + report.totals.requests, + report.totals.page_views, + report.totals.visitors + ), + (8, 4, 2) + ); + assert_eq!(report.totals.mean_duration_ms, Some(0.75)); + let hostnames: Vec<_> = report.routes.iter().map(|r| r.hostname.as_str()).collect(); + assert_eq!(hostnames, ["a.example.com", "b.example.com"]); + let viewed = TrafficRank { + value: "/".into(), + page_views: 4, + }; + assert_eq!(report.pages, [viewed]); + + // Longer windows have daily points, from the start of a day. + let only_b = TrafficQuery { + hostname: Some("b.example.com"), + ..window(day + 5, day + 7 * DAY_MS) + }; + let daily = store.traffic(&id, only_b).await.unwrap(); + assert_eq!((daily.bucket_ms, daily.since_ms), (DAY_MS, day)); + assert_eq!(daily.series.len(), 7); + assert_eq!(daily.series[1].counts.requests, 2); + assert_eq!(daily.totals.requests, 2); + assert_eq!(daily.pages, []); +} + +#[tokio::test] +async fn ranks_stop_growing_at_their_limit_and_old_counts_are_pruned() { + let (_directory, mut store, id) = environment().await; + let now = now_ms(); + let today = now - now.rem_euclid(DAY_MS); + let page = |value: String| (route(&id, "a.example.com"), today, RankKind::Page, value); + let mut tally = TrafficTally::default(); + for index in 0..=TRAFFIC_RANK_LIMIT { + tally.ranks.insert(page(format!("/{index}")), 1); + } + store.record_traffic(&tally).await.unwrap(); + // A page already counted still counts once the day is full. + let mut again = TrafficTally::default(); + again.ranks.insert(page("/0".into()), 5); + store.record_traffic(&again).await.unwrap(); + let ranks = sqlx::query_scalar!("SELECT COUNT(*) FROM traffic_ranks") + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(ranks, TRAFFIC_RANK_LIMIT); + let report = store + .traffic(&id, window(today, today + DAY_MS)) + .await + .unwrap(); + assert_eq!(report.pages.len(), 20); + assert_eq!( + (report.pages[0].value.as_str(), report.pages[0].page_views), + ("/0", 6) + ); + + let old = today - 3 * DAY_MS; + let mut tally = TrafficTally::default(); + let counts = HourCounts { + requests: 1, + ..HourCounts::default() + }; + tally + .hours + .insert((route(&id, "a.example.com"), old), counts); + tally + .hours + .insert((route(&id, "a.example.com"), today), counts); + let old_page = ( + route(&id, "a.example.com"), + old, + RankKind::Page, + "/old".into(), + ); + tally.ranks.insert(old_page, 50); + store.record_traffic(&tally).await.unwrap(); + store.traffic_days = 1; + store.prune_traffic().await.unwrap(); + let report = store + .traffic(&id, window(old, today + DAY_MS)) + .await + .unwrap(); + assert_eq!(report.totals.requests, 1); + assert!( + report.pages.iter().all(|page| page.value != "/old"), + "ranks of pruned days are removed too" + ); + assert_eq!(report.pages[0].value, "/0"); +} diff --git a/crates/piqueld-store/src/repository.rs b/crates/piqueld-store/src/repository.rs deleted file mode 100644 index bd0b0e752..000000000 --- a/crates/piqueld-store/src/repository.rs +++ /dev/null @@ -1,1224 +0,0 @@ -//! Durable candidate manifests for manual deployments. -//! -//! `deployment_inputs` starts with the configuration captured by Deploy. After -//! fetching, it holds the validated manifest and repository commit; `fetched` -//! tells retries to reuse that snapshot instead of reading a moving branch again. -//! Deployments without repository backing also become fetched, with no commit. -//! The candidate, its rendering, and any warnings are copied to deployment -//! history when fetched, but the candidate only becomes its environment's last -//! fetched manifest after source preparation succeeds. The input also -//! captures the manifest the application last read from its repository, and -//! records the one it fetched: a deployment of the branch `spec.manifest` -//! names deploys the saved manifest while the two are the same. -use super::{Operation, Store, StoreError, now_ms}; -use piqueld_core::{ - EnvironmentKind, - api::{DeploymentOrigin, DiagnosticView}, - manifest::{ApplicationTemplate, Rendering, RepositoryManifest}, -}; -use sqlx::{Sqlite, SqliteConnection, Transaction}; - -/// A deployment's candidate manifest and whether it is the fetched snapshot. -pub struct DeploymentInput { - /// The candidate manifest, with references unresolved. - pub template: ApplicationTemplate, - /// Whether it was fetched from the repository rather than saved. - pub fetched: bool, - /// Commit the fetched manifest was read from. - pub commit: Option, - /// The branch its environment tracked, unpinned, when it was requested. - pub tracked_branch: Option, - /// Where the deployment comes from: a local snapshot is fetched from - /// its own repository instead of the branch. - pub origin: DeploymentOrigin, - /// The manifest the application had last read from its repository when - /// the deployment was requested. - pub repository: Option, -} - -impl DeploymentInput { - /// Whether `fetched` is still the manifest the application had last read - /// from its repository, so a push since left the manifest unchanged. - #[must_use] - pub fn unchanged(&self, fetched: &ApplicationTemplate) -> bool { - self.repository - .as_ref() - .is_some_and(|repository| repository.spec_hash() == fetched.spec_hash()) - } -} - -impl Store { - /// Captures the configuration a Deploy started from, still unfetched, with - /// the branch its environment tracks unpinned now and the application's - /// repository manifest. - /// - /// # Errors - /// Returns a storage error. - pub async fn insert_deployment_on( - tx: &mut Transaction<'_, Sqlite>, - operation: &Operation, - application: &ApplicationTemplate, - ) -> Result<(), StoreError> { - let json = application.canonical_json().map_err(StoreError::corrupt)?; - let environment = operation.environment_id.as_str(); - sqlx::query!( - "INSERT INTO deployment_inputs(operation_id,application_json,tracked_branch,repository_json) VALUES(?1,?2,(SELECT branch FROM environments WHERE id=?3 AND pinned_commit IS NULL),(SELECT a.repository_json FROM applications a JOIN environments e ON e.application_id=a.id WHERE e.id=?3))", - operation.id, - json, - environment - ) - .execute(&mut **tx) - .await - .map_err(StoreError::database)?; - Ok(()) - } - - /// Loads the operation's candidate manifest, if one was captured. - /// - /// # Errors - /// Returns a storage error. - pub async fn deployment_input( - &self, - operation: &Operation, - ) -> Result, StoreError> { - sqlx::query!( - r#"SELECT i.application_json,i.fetched,i.repository_commit,i.tracked_branch,i.repository_json,COALESCE(d.origin_json,'{"type":"build"}') AS "origin_json!: String" FROM deployment_inputs i LEFT JOIN deployments d ON d.id=i.operation_id WHERE i.operation_id=?1"#, - operation.id - ) - .fetch_optional(&self.pool) - .await - .map_err(StoreError::database)? - .map(|row| { - Ok(DeploymentInput { - template: serde_json::from_str(&row.application_json) - .map_err(StoreError::corrupt)?, - fetched: row.fetched != 0, - commit: row.repository_commit, - tracked_branch: row.tracked_branch, - origin: serde_json::from_str(&row.origin_json).map_err(StoreError::corrupt)?, - repository: row - .repository_json - .as_deref() - .map(serde_json::from_str) - .transpose() - .map_err(StoreError::corrupt)?, - }) - }) - .transpose() - } - - /// Stores the fetched manifest and commit for the latest running operation, - /// with `fetched`, the manifest as read from the repository, which the - /// saved one may replace, copying it, its rendering, and - /// `warnings` into deployment history, - /// storing values generated for its secrets and pinning their versions - /// (see `pin_secrets_on`), recording the `branch_head` sync follows - /// from (see `record_branch_head_on`), and re-checking hostname - /// reservations. Fetching happens once: a second save, or one for - /// superseded work, fails with `StoreError::IllegalTransition`. - /// - /// # Errors - /// Returns a storage error. - pub async fn save_deployment_input( - &self, - operation: &Operation, - (template, fetched): (&ApplicationTemplate, Option<&ApplicationTemplate>), - rendering: &Rendering, - (commit, branch_head): (Option<&str>, Option<&super::BranchHead>), - warnings: &[DiagnosticView], - ) -> Result<(), StoreError> { - let json = template.canonical_json().map_err(StoreError::corrupt)?; - let fetched = fetched - .map(|fetched| fetched.clone().without_files().canonical_json()) - .transpose() - .map_err(StoreError::corrupt)?; - let (manifest, variables) = Self::snapshot_json(Some(rendering))?; - let warnings = serde_json::to_string(warnings).map_err(StoreError::corrupt)?; - let application = &rendering.application; - let generated = self - .generated_secrets(&operation.environment_id, application) - .await?; - let (_writer, mut tx) = self.begin_immediate().await?; - let app_id = operation.environment_id.as_str(); - let changed = sqlx::query!("UPDATE deployment_inputs SET application_json=?1,repository_commit=?2,fetched_json=?5,fetched=1 WHERE operation_id=?3 AND fetched=0 AND operation_id=(SELECT id FROM operations WHERE environment_id=?4 ORDER BY created_at_ms DESC,id DESC LIMIT 1) AND EXISTS(SELECT 1 FROM operations WHERE id=?3 AND state='running')", json,commit,operation.id,app_id,fetched).execute(&mut *tx).await.map_err(StoreError::database)?.rows_affected(); - if changed != 1 { - return Err(StoreError::IllegalTransition); - } - sqlx::query!( - "UPDATE deployments SET manifest_json=?1,template_json=?2,variables_json=?3,warnings_json=?4 WHERE id=?5", - manifest, - json, - variables, - warnings, - operation.id - ) - .execute(&mut *tx) - .await - .map_err(StoreError::database)?; - let now = now_ms(); - Self::operation_event(&mut tx, &operation.id, "manifest_fetched", commit, now).await?; - if let Some(head) = branch_head { - Self::record_branch_head_on(&mut tx, &operation.environment_id, head, now).await?; - } - self.pin_secrets_on(&mut tx, operation, application, &generated) - .await?; - Self::commit_environment_changes(tx, [app_id]).await - } - - /// Records a fetched repository manifest, under the application's current - /// name, as its environment's last fetched one, while the environment - /// still follows a branch. Other environments keep their own. - /// - /// While the application is still repository-backed, a deployment of an - /// environment that fetched from the path, branch and commit - /// `spec.manifest` names (see `reads_connection_on`) also converges the - /// environments the saved manifest declares, and saves the manifest a - /// push changed (see `read_repository_on`). Other paths, branches, - /// one-off revisions and previews never do, so a manifest fetched before - /// the connection changed never replaces it. Records `application_applied` - /// when any manifest changed. - /// Fails with `secret_name_conflict` when the application's store now holds - /// a name the fetched manifest declares. - /// Called in the same transaction that saves the fully prepared runtime target. - pub(super) async fn accept_deployment_on( - tx: &mut Transaction<'_, Sqlite>, - operation: &Operation, - fetching: &EnvironmentKind, - ) -> Result<(), StoreError> { - let row = sqlx::query!( - "SELECT application_json,repository_json,fetched_json FROM deployment_inputs WHERE operation_id=?1 AND fetched=1 AND repository_commit IS NOT NULL", - operation.id - ) - .fetch_optional(&mut **tx) - .await - .map_err(StoreError::database)?; - let Some(row) = row else { - return Ok(()); - }; - let deployed: ApplicationTemplate = - serde_json::from_str(&row.application_json).map_err(StoreError::corrupt)?; - let stored = Self::application_on(tx, deployed.id().as_str()) - .await? - .ok_or(StoreError::NotFound)?; - let application = &stored.application; - // A secret stored since the manifest was fetched may now share a name - // with one of its declarations. - Self::check_declared_against_store_on( - tx, - application.id().as_str(), - &deployed.spec().secrets, - ) - .await?; - // A retry may accept a manifest fetched before a rename. The - // deployment keeps the files it captured. - let deployed = deployed - .with_name(application.metadata().name.clone()) - .without_files(); - let manifest = deployed.canonical_json().map_err(StoreError::corrupt)?; - let now = now_ms(); - let environment = operation.environment_id.as_str(); - let mut changed = sqlx::query!( - "UPDATE environments SET manifest_json=?1,updated_at_ms=?2 WHERE id=?3 AND branch IS NOT NULL AND manifest_json IS NOT ?1", - manifest, - now, - environment - ) - .execute(&mut **tx) - .await - .map_err(StoreError::database)? - .rows_affected(); - if let Some(connection) = - Self::reads_connection_on(tx, operation, fetching, &deployed, application).await? - { - // Without the files a deployment captured, which the spec hash - // covers, as the application keeps the one it last read. - let hash = |json: Option<&str>| { - json.map(|json| { - serde_json::from_str::(json) - .map(|manifest| manifest.without_files().spec_hash()) - .map_err(StoreError::corrupt) - }) - .transpose() - }; - let read = ( - hash(row.repository_json.as_deref())?, - hash(row.fetched_json.as_deref())?, - ); - changed += Self::read_repository_on( - tx, - operation, - &stored, - (deployed.with_manifest(Some(connection)), read), - now, - ) - .await?; - } - if changed > 0 { - Self::operation_event(tx, &operation.id, "application_applied", None, now).await?; - } - Ok(()) - } - - /// Converges the environments of `stored` to the ones its saved manifest - /// declares, retrying changes that had to wait, after saving `deployed`, - /// which `operation` deployed from its connection, when a push changed - /// the manifest. `read` holds the spec hashes of the manifest the - /// application had last read when `operation` was requested and of the - /// one it fetched: a push changed it when the fetched one differs from - /// that one, so `deployed` is the fetched one, and from the one the - /// application read last. It then becomes both the saved manifest, as - /// saving it would, and the one last read. Advances the revision when the - /// saved manifest changes, resolving `operation`, which deploys it, at - /// the new one unless its environment's source changed, or when - /// converging changed the source of an environment with a deployment in - /// progress, which then leaves it unresolved. Returns the rows changed. - async fn read_repository_on( - tx: &mut Transaction<'_, Sqlite>, - operation: &Operation, - stored: &super::StoredApplication, - (deployed, (captured, fetched)): (ApplicationTemplate, (Option, Option)), - now: i64, - ) -> Result { - let application = &stored.application; - let read = Self::repository_manifest_on(tx, stored) - .await? - .map(|read| read.spec_hash()); - let pushed = fetched.is_some() && fetched != captured && fetched != read; - let saved = if pushed { &deployed } else { application }; - let source = async |tx: &mut Transaction<'_, Sqlite>| { - Self::environment_on(tx, operation.environment_id.as_str()) - .await - .map(|environment| environment.map(|environment| environment.environment.source)) - }; - let before = source(tx).await?; - let converged = Self::converge_environments_on( - tx, - application.id(), - &saved - .spec() - .declared_environments_since(Some(application.spec()))?, - Some(&operation.environment_id), - now, - ) - .await?; - let edited = saved != application; - if converged || edited { - Self::bump_generation_on(tx, application.id(), stored.generation, None).await?; - } - if edited && source(tx).await? == before { - let (previous, revision) = ( - i64::try_from(stored.generation).map_err(StoreError::corrupt)?, - i64::try_from(stored.generation + 1).map_err(StoreError::corrupt)?, - ); - sqlx::query!( - "UPDATE operations SET generation=?1 WHERE id=?2 AND generation=?3", - revision, - operation.id, - previous - ) - .execute(&mut **tx) - .await - .map_err(StoreError::database)?; - } - if !pushed { - return Ok(0); - } - let deployed = deployed.canonical_json().map_err(StoreError::corrupt)?; - let id = application.id().as_str(); - Ok(sqlx::query!( - "UPDATE applications SET desired_json=?1,repository_json=?1,updated_at_ms=?2 WHERE id=?3", - deployed, - now, - id - ) - .execute(&mut **tx) - .await - .map_err(StoreError::database)? - .rows_affected()) - } - - /// Whether `operation`, a deployment of `kind`, fetched `fetched` - /// from the connection of `application`, which this returns: the - /// manifest an environment, not a preview, reads from it. - /// See [`Self::reads_connection_on`]. - /// - /// # Errors - /// Returns a storage error. - pub async fn reads_connection( - &self, - operation: &Operation, - kind: &EnvironmentKind, - fetched: &ApplicationTemplate, - ) -> Result { - let connection = &mut *self.connection().await?; - let application = Self::application_on(connection, fetched.id().as_str()) - .await? - .ok_or(StoreError::NotFound)?; - Ok(Self::reads_connection_on( - connection, - operation, - kind, - fetched, - &application.application, - ) - .await? - .is_some()) - } - - /// See [`Self::reads_connection`]. - async fn reads_connection_on( - connection: &mut SqliteConnection, - operation: &Operation, - kind: &EnvironmentKind, - fetched: &ApplicationTemplate, - application: &ApplicationTemplate, - ) -> Result, StoreError> { - let Some(wanted) = application.spec().manifest.clone() else { - return Ok(None); - }; - let reads = matches!(kind, EnvironmentKind::Environment) - && Self::fetched_connection_on(connection, operation, fetched, &wanted).await?; - Ok(reads.then_some(wanted)) - } - - /// Whether `fetched`, the manifest `operation` fetched, came from the - /// path and revision `wanted` names. Its own connection is the path - /// and revision it was fetched from; sync pins the head it listed of a - /// branch it follows, so its deployments of the connection's unpinned - /// branch count too. - async fn fetched_connection_on( - connection: &mut SqliteConnection, - operation: &Operation, - fetched: &ApplicationTemplate, - wanted: &RepositoryManifest, - ) -> Result { - let Some(fetched) = fetched - .spec() - .manifest - .as_ref() - .filter(|fetched| fetched.path == wanted.path) - .map(|fetched| &fetched.repository) - else { - return Ok(false); - }; - let wanted = &wanted.repository; - if fetched == wanted { - return Ok(true); - } - if fetched.url != wanted.url || fetched.branch != wanted.branch || wanted.commit.is_some() { - return Ok(false); - } - Self::requested_by_sync_on(connection, operation).await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Actor::Daemon; - use crate::testing::template; - use crate::{Mutation, MutationResponse}; - use piqueld_core::{ApplicationId, EnvironmentId, OperationState, ResolutionSet}; - - #[tokio::test] - async fn fetched_snapshot_preserves_intervening_saved_configuration() { - let (_directory, store) = Store::temporary().await; - let initial = template( - "test", - "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/app.git'\nbranch='main'", - ); - let saved = store.save_template(initial, true).await; - let op = store.operation(&saved.operation_id.unwrap()).await.unwrap(); - store.mark_running(&op.id).await; - let captured = store.deployment_snapshot(&op.id).await.unwrap().template; - let mut fetched = captured.to_manifest(); - fetched.spec.manifest = None; - let fetched = fetched - .validate_template() - .unwrap() - .normalize(captured.id().clone()); - let environment = store.get(&op.environment_id).await.unwrap(); - let rendering = environment.render(&fetched, &op.id).unwrap(); - store - .save_deployment_input( - &op, - (&fetched, Some(&fetched)), - &rendering, - (Some(&"a".repeat(40)), None), - &[], - ) - .await - .unwrap(); - let mut edited = captured.to_manifest(); - edited.spec.manifest.as_mut().unwrap().path = "fixed.toml".into(); - let edited = edited - .validate_template() - .unwrap() - .normalize(captured.id().clone()); - store - .accept( - crate::Actor::Daemon, - Mutation::Save { - application: Box::new(edited.clone()), - expected_application_id: Some(captured.id().to_string()), - deploy: false, - }, - Some(1), - false, - None, - ) - .await - .unwrap(); - let target = piqueld_core::compile_application( - &rendering.application, - &op.environment_id, - store.instance_id().clone(), - &ResolutionSet::default(), - ) - .unwrap(); - store.save_prepared(&op, &target).await.unwrap(); - let saved = store.get(&op.environment_id).await.unwrap().application; - assert_eq!((saved.application, saved.generation), (edited.clone(), 2)); - assert_eq!(store.operation(&op.id).await.unwrap().generation, 1); - let snapshot = store.deployment_snapshot(&op.id).await.unwrap(); - assert_eq!(snapshot.template, fetched); - assert_eq!(snapshot.rendering, Some(rendering.clone())); - assert_eq!( - store - .deployments(&op.environment_id, None, 3) - .await - .unwrap() - .items[0] - .application, - Some(rendering.application.clone()) - ); - assert!(matches!( - store - .save_deployment_input(&op, (&edited, None), &rendering, (None, None), &[]) - .await, - Err(StoreError::IllegalTransition) - )); - } - - /// A repository-backed application `notes` whose saved manifest is only - /// its connection to `main`. - fn connection() -> piqueld_core::manifest::ValidatedTemplate { - template( - "notes", - "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'", - ) - } - - /// Deploys `environment` from a fetched manifest with `spec`, as the - /// controller does, through preparation. - async fn fetch(store: &Store, environment: &EnvironmentId, spec: &str) { - let (op, target) = fetched(store, environment, spec).await; - store.save_prepared(&op, &target).await.unwrap(); - } - - /// Starts a deployment of `environment` and fetches a manifest with - /// `spec`, returning the operation and the target it prepares. - async fn fetched( - store: &Store, - environment: &EnvironmentId, - spec: &str, - ) -> (Operation, piqueld_core::ResolvedApplication) { - let (MutationResponse::Operation(accepted), _) = store - .accept( - crate::Actor::Daemon, - Mutation::deploy(environment.clone()), - None, - true, - None, - ) - .await - .unwrap() - else { - panic!("operation") - }; - prepared(store, environment, &accepted.operation_id, spec).await - } - - /// Runs operation `id` of `environment` through fetching a manifest with - /// `spec`, returning it and the target it prepares. - async fn prepared( - store: &Store, - environment: &EnvironmentId, - id: &str, - spec: &str, - ) -> (Operation, piqueld_core::ResolvedApplication) { - let (op, fetched, rendering) = rendered(store, environment, id, spec).await; - store - .save_deployment_input( - &op, - (&fetched, Some(&fetched)), - &rendering, - (Some(&"a".repeat(40)), None), - &[], - ) - .await - .unwrap(); - let resolutions = ResolutionSet { - sources: [( - piqueld_core::ServiceName::parse("web").unwrap(), - piqueld_core::ResolvedSource::parse_image( - "ghcr.io/example/notes:1.4.0", - format!("ghcr.io/example/notes@sha256:{}", "a".repeat(64)), - ) - .unwrap(), - )] - .into(), - ..ResolutionSet::default() - }; - let target = piqueld_core::compile_application( - &rendering.application, - environment, - store.instance_id().clone(), - &resolutions, - ) - .unwrap(); - (op, target) - } - - /// Marks operation `id` of `environment` running and renders a manifest - /// with `spec` fetched for it, returning the operation, the manifest and - /// its rendering. - async fn rendered( - store: &Store, - environment: &EnvironmentId, - id: &str, - spec: &str, - ) -> (Operation, ApplicationTemplate, Rendering) { - let op = store.operation(id).await.unwrap(); - store.mark_running(&op.id).await; - let current = store.get(environment).await.unwrap(); - // As fetching does, the connection replaces the file's own before validation. - let mut fetched = piqueld_core::manifest::ApplicationManifest::decode_toml(&format!( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n{spec}" - )) - .unwrap(); - fetched.spec.manifest = current.tracking().unwrap().repository(); - let fetched = fetched - .validate_template() - .unwrap() - .normalize(current.application.application.id().clone()); - let rendering = current.render(&fetched, &op.id).unwrap(); - (op, fetched, rendering) - } - - /// A fetch saved for superseded work stores none of the secret values - /// generated for it, so rejected candidates never use up the quota. - #[tokio::test] - async fn rejected_fetches_store_no_generated_secrets() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let deploy = async || { - let (MutationResponse::Operation(accepted), _) = store - .accept( - Daemon, - Mutation::deploy(production.clone()), - None, - true, - None, - ) - .await - .unwrap() - else { - panic!("operation") - }; - accepted.operation_id - }; - let first = deploy().await; - let spec = format!( - "{}\n[[spec.services.secrets]]\nname='token'\ntarget='/run/secrets/token'", - token_spec(true) - ); - let (op, fetched, rendering) = rendered(&store, &production, &first, &spec).await; - deploy().await; - assert!(matches!( - store - .save_deployment_input(&op, (&fetched, None), &rendering, (None, None), &[]) - .await, - Err(StoreError::IllegalTransition) - )); - assert!(store.secrets(&production).await.unwrap().is_empty()); - } - - /// A manifest fetched before a rename is accepted under the new name, as - /// when a deployment is retried. - #[tokio::test] - async fn fetched_manifests_keep_the_current_name() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (op, target) = fetched(&store, &production, &token_spec(false)).await; - store - .transition_operation( - &op.id, - OperationState::Running, - OperationState::Failed, - Some(("build_failed", "build failed")), - ) - .await - .unwrap(); - // Repository-backed applications are renamed while disconnected. - let repository = |repository| Mutation::Edit { - id: application.clone(), - edit: Box::new(piqueld_core::edit::ApplicationEdit::Repository(repository)), - deploy: false, - }; - for mutation in [ - repository(None), - crate::testing::rename_application(&application, "journal"), - repository(connection().spec().manifest.clone()), - ] { - store.force(mutation).await.unwrap(); - } - let op = store.retry_operation(&op).await.unwrap(); - store.mark_running(&op.id).await; - store.save_prepared(&op, &target).await.unwrap(); - let current = store.get(&production).await.unwrap(); - assert_eq!( - current.application.application.metadata().name.as_str(), - "journal" - ); - assert_eq!( - current.manifest().unwrap().metadata().name.as_str(), - "journal" - ); - } - - /// A manifest fetched before the connection changed never replaces the - /// configuration saved since: it came from the old path. - #[tokio::test] - async fn fetches_requested_before_a_save_keep_the_saved_configuration() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (op, target) = fetched(&store, &production, &token_spec(false)).await; - store - .force(Mutation::Edit { - id: application.clone(), - edit: Box::new(piqueld_core::edit::ApplicationEdit::RepositoryPath( - "fixed.toml".into(), - )), - deploy: false, - }) - .await - .unwrap(); - store.save_prepared(&op, &target).await.unwrap(); - let saved = store - .get(&production) - .await - .unwrap() - .application - .application; - assert_eq!(saved.spec().manifest.as_ref().unwrap().path, "fixed.toml"); - assert_eq!(saved.spec().services, Vec::new()); - } - - /// Environment changes advance the revision, but leave the connection a - /// manifest was fetched from, so one fetched meanwhile is still saved. - #[tokio::test] - async fn fetches_are_saved_across_environment_changes() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (op, target) = fetched(&store, &production, &token_spec(false)).await; - store - .force(Mutation::CreateEnvironment { - application, - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: None, - }) - .await - .unwrap(); - store.save_prepared(&op, &target).await.unwrap(); - let saved = store.get(&production).await.unwrap().application; - assert!(saved.generation > op.generation); - assert_eq!(saved.application.spec().services.len(), 1); - } - - /// A deployment that fetched the manifest the application had read when - /// it was requested saves nothing, even when it finishes after a push - /// and edits were saved since. - #[tokio::test] - async fn unchanged_fetches_keep_newer_edits() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - fetch(&store, &production, &token_spec(false)).await; - let MutationResponse::Environment(staging) = store - .force(Mutation::CreateEnvironment { - application: application.clone(), - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: None, - }) - .await - .unwrap() - else { - panic!("environment") - }; - let MutationResponse::Operation(delayed) = store - .force(Mutation::deploy(staging.id.clone())) - .await - .unwrap() - else { - panic!("operation") - }; - fetch( - &store, - &production, - &format!("{}\n[[spec.volumes]]\nname='data'", token_spec(false)), - ) - .await; - store - .force(Mutation::Edit { - id: application.clone(), - edit: Box::new(piqueld_core::edit::ApplicationEdit::Service { - name: "web".into(), - edit: piqueld_core::edit::ServiceEdit::Replicas(3.into()), - }), - deploy: false, - }) - .await - .unwrap(); - let (op, target) = prepared( - &store, - &staging.id, - &delayed.operation_id, - &token_spec(false), - ) - .await; - store.save_prepared(&op, &target).await.unwrap(); - let saved = store.application(&application).await.unwrap().application; - assert_eq!(saved.spec().services[0].replicas, 3.into()); - assert_eq!(saved.spec().volumes.len(), 1, "the push is kept"); - } - - /// A fetch is compared without the repository files it captured: the - /// manifest last read keeps none. Deployments fetched before the - /// migration recorded what they deployed, files included. - #[tokio::test] - async fn captured_files_are_not_a_push() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let spec = token_spec(false); - fetch(&store, &production, &spec).await; - store - .force(Mutation::Edit { - id: application.clone(), - edit: Box::new(piqueld_core::edit::ApplicationEdit::Service { - name: "web".into(), - edit: piqueld_core::edit::ServiceEdit::Replicas(3.into()), - }), - deploy: false, - }) - .await - .unwrap(); - let MutationResponse::Operation(accepted) = store - .force(Mutation::deploy(production.clone())) - .await - .unwrap() - else { - panic!("operation") - }; - let (op, target) = prepared(&store, &production, &accepted.operation_id, &spec).await; - let id = op.id.as_str(); - let json = sqlx::query_scalar!( - "SELECT application_json FROM deployment_inputs WHERE operation_id=?1", - id - ) - .fetch_one(&store.pool) - .await - .unwrap(); - let captured = serde_json::from_str::(&json) - .unwrap() - .with_files( - [("notes.yaml".to_owned(), "notes: true".to_owned())] - .into_iter() - .collect(), - ) - .unwrap() - .canonical_json() - .unwrap(); - sqlx::query!( - "UPDATE deployment_inputs SET application_json=?1,fetched_json=?1 WHERE operation_id=?2", - captured, - id - ) - .execute(&store.pool) - .await - .unwrap(); - store.save_prepared(&op, &target).await.unwrap(); - let saved = store.application(&application).await.unwrap().application; - assert_eq!(saved.spec().services[0].replicas, 3.into()); - } - - /// Each environment's hostname reservations and rename checks read its - /// own last fetched manifest, so a fetch for one never changes the other. - #[tokio::test] - async fn environments_reserve_and_rename_by_their_own_fetched_manifest() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (MutationResponse::Environment(staging), _) = store - .accept( - crate::Actor::Daemon, - Mutation::CreateEnvironment { - application, - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: Some(crate::SourceChoice::Branch( - piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), - )), - }, - None, - true, - None, - ) - .await - .unwrap() - else { - panic!("environment") - }; - let reserved = async |environment: &EnvironmentId| { - let id = environment.as_str(); - sqlx::query_scalar!( - "SELECT hostname FROM hostname_reservations WHERE environment_id=?1 ORDER BY hostname", - id - ) - .fetch_all(&store.pool) - .await - .unwrap() - }; - let service = token_spec(false); - fetch( - &store, - &production, - &format!("{service}\n[[spec.routes]]\nhostname='notes.example.com'\nservice='web'\nport=80\n[spec.environments.production.variables]\nlevel='debug'"), - ) - .await; - // Staging has fetched nothing yet, so it reserves nothing. - assert_eq!(reserved(&production).await, ["notes.example.com"]); - assert_eq!(reserved(&staging.id).await, Vec::::new()); - let before = store.get(&production).await.unwrap().own; - fetch( - &store, - &staging.id, - &format!( - "{service}\n[[spec.routes]]\nhostname='staging.example.com'\nservice='web'\nport=80" - ), - ) - .await; - assert_eq!(reserved(&production).await, ["notes.example.com"]); - assert_eq!(reserved(&staging.id).await, ["staging.example.com"]); - assert_eq!(store.get(&production).await.unwrap().own, before); - // Only production's own manifest configures `production`. - let rename = |id: &EnvironmentId| Mutation::RenameEnvironment { - id: id.clone(), - name: piqueld_core::EnvironmentName::parse("qa").unwrap(), - }; - assert!(matches!( - store.force(rename(&production)).await, - Err(StoreError::EnvironmentConfigured { .. }) - )); - store.force(rename(&staging.id)).await.unwrap(); - } - - /// Saves the repository-backed application `notes` (see `connection`). - async fn saved_connection(store: &Store) -> ApplicationId { - let saved = store.save_template(connection(), false).await; - ApplicationId::parse(&saved.application_id).unwrap() - } - - /// A manifest with the image service `web` that declares the generated - /// secret `token` when `declared`. - fn token_spec(declared: bool) -> String { - let secret = "[[spec.secrets]]\nname='token'\n[spec.secrets.generate]\ntype='random'\nbytes=16\nencoding='hex'\n"; - format!( - "{}[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='ghcr.io/example/notes:1.4.0'", - if declared { secret } else { "" } - ) - } - - /// Fetching a manifest from the branch `spec.manifest` names converges - /// the environments it declares, including the fetching one, whose own - /// deployment is past building; other branches never do. - #[tokio::test] - async fn fetches_of_the_connection_branch_converge_declared_environments() { - use piqueld_core::{EnvironmentSource, TrackedBranch}; - let (_directory, store) = Store::temporary().await; - let polled = template( - "notes", - "[spec.manifest]\npath='app.toml'\nsync={mode='poll'}\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'", - ); - let saved = store.save_template(polled, false).await; - let application = ApplicationId::parse(&saved.application_id).unwrap(); - let production = store.production(&application).await; - let declared = format!( - "[spec.environments.staging]\nsync=true\n[spec.environments.production]\npromote_from='staging'\n[spec.environments.canary]\nbranch='next'\n{}", - token_spec(false) - ); - fetch(&store, &production, &declared).await; - let environments = store.environments(&application).await.unwrap(); - let named = |name: &str| { - environments - .iter() - .find(|environment| environment.name.as_str() == name) - .unwrap() - .clone() - }; - let (staging, canary) = (named("staging"), named("canary")); - assert_eq!( - staging.source, - EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()) - ); - assert!(staging.sync); - assert_eq!( - canary.source, - EnvironmentSource::Branch(TrackedBranch::new("next".into(), None).unwrap()) - ); - assert_eq!( - named("production").source.promoted_from(), - Some(&staging.id) - ); - - // A manifest on another branch declares nothing. - fetch(&store, &canary.id, &token_spec(false)).await; - assert_eq!(store.environments(&application).await.unwrap().len(), 3); - // Sync pins the head it listed, and still fetches `main`. - let id = staging.id.as_str(); - let first = "a".repeat(40); - sqlx::query!( - "UPDATE environments SET synced_commit=?1,synced_at_ms=1 WHERE id=?2", - first, - id - ) - .execute(&store.pool) - .await - .unwrap(); - let (MutationResponse::Synced(crate::SyncOutcome::Deployed(synced)), _) = store - .accept( - crate::Actor::System(piqueld_core::sync::SystemActor::SyncPoll), - Mutation::Sync(crate::ListedHead { - id: staging.id.clone(), - repository: "https://example.com/notes.git".into(), - branch: piqueld_core::GitBranch::parse("main").unwrap(), - head: "b".repeat(40), - since: store.get(&staging.id).await.unwrap().environment.synced, - }), - None, - false, - None, - ) - .await - .unwrap() - else { - panic!("sync deployment expected") - }; - let (op, target) = prepared( - &store, - &staging.id, - &synced.operation_id, - &format!("{declared}\n[spec.environments.qa]\n"), - ) - .await; - store.save_prepared(&op, &target).await.unwrap(); - assert_eq!(store.environments(&application).await.unwrap().len(), 4); - // The next one from `main` stops staging syncing, and leaves canary - // and qa, no longer declared, as they are. - fetch( - &store, - &staging.id, - &format!( - "[spec.environments.staging]\n[spec.environments.production]\npromote_from='staging'\n{}", - token_spec(false) - ), - ) - .await; - let environments = store.environments(&application).await.unwrap(); - assert_eq!(environments.len(), 4); - assert!(!environments.iter().any(|environment| environment.sync)); - } - - /// A fetch that changes the saved manifest resolves its environment at - /// the revision it saved, unless it changes that environment's source. - #[tokio::test] - async fn fetches_resolve_their_environment_at_the_revision_they_save() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (op, target) = fetched(&store, &production, &token_spec(false)).await; - store.save_prepared(&op, &target).await.unwrap(); - store.publish_prepared(&op).await.unwrap(); - let current = store.get(&production).await.unwrap(); - assert_eq!(current.application.generation, op.generation + 1); - assert_eq!( - current.environment.resolved_generation, - Some(current.application.generation) - ); - // Unless the manifest moves the fetching environment elsewhere: it - // deployed its former branch. - let moved = format!( - "[spec.environments.production]\nbranch='release'\n{}", - token_spec(false) - ); - let (op, target) = fetched(&store, &production, &moved).await; - store.save_prepared(&op, &target).await.unwrap(); - store.publish_prepared(&op).await.unwrap(); - let current = store.get(&production).await.unwrap(); - assert_ne!( - current.environment.resolved_generation, - Some(current.application.generation) - ); - } - - /// A fetch that changes an environment's source leaves it unresolved, as - /// changing it with `env branch` does, and, like any fetch changing the - /// saved manifest, advances the revision. - #[tokio::test] - async fn fetched_source_changes_leave_environments_unresolved() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let canary = |branch: &str| { - format!( - "[spec.environments.canary]\nbranch='{branch}'\n{}", - token_spec(false) - ) - }; - fetch(&store, &production, &canary("next")).await; - let id = store - .environments(&application) - .await - .unwrap() - .into_iter() - .find(|environment| environment.name.as_str() == "canary") - .unwrap() - .id; - let canary_id = id.as_str(); - sqlx::query!( - "UPDATE environments SET resolved_generation=(SELECT generation FROM applications) WHERE id=?1", - canary_id - ) - .execute(&store.pool) - .await - .unwrap(); - let generation = store.get(&id).await.unwrap().application.generation; - fetch(&store, &production, &canary("release")).await; - let current = store.get(&id).await.unwrap(); - assert_eq!(current.environment.resolved_generation, None); - assert_eq!(current.application.generation, generation + 1); - - store - .accept(Daemon, Mutation::deploy(id.clone()), None, false, None) - .await - .unwrap(); - fetch(&store, &production, &canary("beta")).await; - assert_eq!( - store.get(&id).await.unwrap().application.generation, - generation + 2 - ); - } - - /// The saved manifest's declarations hold their names even for an - /// environment whose own fetched manifest, from another branch, has no - /// block: renaming it would leave the declaration to recreate it. - #[tokio::test] - async fn declared_environments_keep_their_names() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - fetch( - &store, - &production, - &format!( - "[spec.environments.staging]\nbranch='release'\n{}", - token_spec(false) - ), - ) - .await; - let staging = store - .environments(&application) - .await - .unwrap() - .into_iter() - .find(|environment| environment.name.as_str() == "staging") - .unwrap() - .id; - fetch(&store, &staging, &token_spec(false)).await; - let rename = Mutation::RenameEnvironment { - id: staging, - name: piqueld_core::EnvironmentName::parse("qa").unwrap(), - }; - assert!(matches!( - store.force(rename).await, - Err(StoreError::EnvironmentDeclared { environment }) if environment.as_str() == "staging" - )); - } - - /// A secret stored after a manifest was fetched but before it is accepted - /// may not share a name with one of its declarations. - #[tokio::test] - async fn accepting_a_fetched_manifest_rejects_declarations_stored_meanwhile() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let production = store.production(&application).await; - let (op, target) = fetched(&store, &production, &token_spec(true)).await; - // The saved manifest does not declare `token` yet, so storing it succeeds. - store - .put_stored_secret(Daemon, &application, "token", 0, b"value".to_vec(), None) - .await - .unwrap(); - let Err(StoreError::Validation(errors)) = store.save_prepared(&op, &target).await else { - panic!("secret name conflict expected") - }; - assert_eq!( - errors.0[0].code, - piqueld_core::ApiErrorCode::SecretNameConflict - ); - assert!(store.get(&production).await.unwrap().manifest().is_none()); - } - - /// A name an environment's last fetched manifest declares cannot be - /// stored, even once another environment's fetch replaced the saved one. - #[tokio::test] - async fn fetched_declarations_of_every_environment_reserve_their_names() { - let (_directory, store) = Store::temporary().await; - let application = saved_connection(&store).await; - let (MutationResponse::Environment(staging), _) = store - .accept( - Daemon, - Mutation::CreateEnvironment { - application: application.clone(), - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: Some(crate::SourceChoice::Branch( - piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), - )), - }, - None, - true, - None, - ) - .await - .unwrap() - else { - panic!("environment") - }; - let production = store.production(&application).await; - fetch(&store, &production, &token_spec(true)).await; - fetch(&store, &staging.id, &token_spec(false)).await; - let Err(StoreError::Validation(errors)) = store - .put_stored_secret(Daemon, &application, "token", 0, b"value".to_vec(), None) - .await - else { - panic!("secret name conflict expected") - }; - assert_eq!( - errors.0[0].code, - piqueld_core::ApiErrorCode::SecretNameConflict - ); - } -} diff --git a/crates/piqueld-store/src/repository/mod.rs b/crates/piqueld-store/src/repository/mod.rs new file mode 100644 index 000000000..98750acfa --- /dev/null +++ b/crates/piqueld-store/src/repository/mod.rs @@ -0,0 +1,416 @@ +//! Durable candidate manifests for manual deployments. +//! +//! `deployment_inputs` starts with the configuration captured by Deploy. After +//! fetching, it holds the validated manifest and repository commit; `fetched` +//! tells retries to reuse that snapshot instead of reading a moving branch again. +//! Deployments without repository backing also become fetched, with no commit. +//! The candidate, its rendering, and any warnings are copied to deployment +//! history when fetched, but the candidate only becomes its environment's last +//! fetched manifest after source preparation succeeds. The input also +//! captures the manifest the application last read from its repository, and +//! records the one it fetched: a deployment of the branch `spec.manifest` +//! names deploys the saved manifest while the two are the same. +use super::{Operation, Store, StoreError, now_ms}; +use piqueld_core::{ + EnvironmentKind, + api::{DeploymentOrigin, DiagnosticView}, + manifest::{ApplicationTemplate, Rendering, RepositoryManifest}, +}; +use sqlx::{Sqlite, SqliteConnection, Transaction}; + +/// A deployment's candidate manifest and whether it is the fetched snapshot. +pub struct DeploymentInput { + /// The candidate manifest, with references unresolved. + pub template: ApplicationTemplate, + /// Whether it was fetched from the repository rather than saved. + pub fetched: bool, + /// Commit the fetched manifest was read from. + pub commit: Option, + /// The branch its environment tracked, unpinned, when it was requested. + pub tracked_branch: Option, + /// Where the deployment comes from: a local snapshot is fetched from + /// its own repository instead of the branch. + pub origin: DeploymentOrigin, + /// The manifest the application had last read from its repository when + /// the deployment was requested. + pub repository: Option, +} + +impl DeploymentInput { + /// Whether `fetched` is still the manifest the application had last read + /// from its repository, so a push since left the manifest unchanged. + #[must_use] + pub fn unchanged(&self, fetched: &ApplicationTemplate) -> bool { + self.repository + .as_ref() + .is_some_and(|repository| repository.spec_hash() == fetched.spec_hash()) + } +} + +impl Store { + /// Captures the configuration a Deploy started from, still unfetched, with + /// the branch its environment tracks unpinned now and the application's + /// repository manifest. + /// + /// # Errors + /// Returns a storage error. + pub async fn insert_deployment_on( + tx: &mut Transaction<'_, Sqlite>, + operation: &Operation, + application: &ApplicationTemplate, + ) -> Result<(), StoreError> { + let json = application.canonical_json().map_err(StoreError::corrupt)?; + let environment = operation.environment_id.as_str(); + sqlx::query!( + "INSERT INTO deployment_inputs(operation_id,application_json,tracked_branch,repository_json) VALUES(?1,?2,(SELECT branch FROM environments WHERE id=?3 AND pinned_commit IS NULL),(SELECT a.repository_json FROM applications a JOIN environments e ON e.application_id=a.id WHERE e.id=?3))", + operation.id, + json, + environment + ) + .execute(&mut **tx) + .await + .map_err(StoreError::database)?; + Ok(()) + } + + /// Loads the operation's candidate manifest, if one was captured. + /// + /// # Errors + /// Returns a storage error. + pub async fn deployment_input( + &self, + operation: &Operation, + ) -> Result, StoreError> { + sqlx::query!( + r#"SELECT i.application_json,i.fetched,i.repository_commit,i.tracked_branch,i.repository_json,COALESCE(d.origin_json,'{"type":"build"}') AS "origin_json!: String" FROM deployment_inputs i LEFT JOIN deployments d ON d.id=i.operation_id WHERE i.operation_id=?1"#, + operation.id + ) + .fetch_optional(&self.pool) + .await + .map_err(StoreError::database)? + .map(|row| { + Ok(DeploymentInput { + template: serde_json::from_str(&row.application_json) + .map_err(StoreError::corrupt)?, + fetched: row.fetched != 0, + commit: row.repository_commit, + tracked_branch: row.tracked_branch, + origin: serde_json::from_str(&row.origin_json).map_err(StoreError::corrupt)?, + repository: row + .repository_json + .as_deref() + .map(serde_json::from_str) + .transpose() + .map_err(StoreError::corrupt)?, + }) + }) + .transpose() + } + + /// Stores the fetched manifest and commit for the latest running operation, + /// with `fetched`, the manifest as read from the repository, which the + /// saved one may replace, copying it, its rendering, and + /// `warnings` into deployment history, + /// storing values generated for its secrets and pinning their versions + /// (see `pin_secrets_on`), recording the `branch_head` sync follows + /// from (see `record_branch_head_on`), and re-checking hostname + /// reservations. Fetching happens once: a second save, or one for + /// superseded work, fails with `StoreError::IllegalTransition`. + /// + /// # Errors + /// Returns a storage error. + pub async fn save_deployment_input( + &self, + operation: &Operation, + (template, fetched): (&ApplicationTemplate, Option<&ApplicationTemplate>), + rendering: &Rendering, + (commit, branch_head): (Option<&str>, Option<&super::BranchHead>), + warnings: &[DiagnosticView], + ) -> Result<(), StoreError> { + let json = template.canonical_json().map_err(StoreError::corrupt)?; + let fetched = fetched + .map(|fetched| fetched.clone().without_files().canonical_json()) + .transpose() + .map_err(StoreError::corrupt)?; + let (manifest, variables) = Self::snapshot_json(Some(rendering))?; + let warnings = serde_json::to_string(warnings).map_err(StoreError::corrupt)?; + let application = &rendering.application; + let generated = self + .generated_secrets(&operation.environment_id, application) + .await?; + let (_writer, mut tx) = self.begin_immediate().await?; + let app_id = operation.environment_id.as_str(); + let changed = sqlx::query!("UPDATE deployment_inputs SET application_json=?1,repository_commit=?2,fetched_json=?5,fetched=1 WHERE operation_id=?3 AND fetched=0 AND operation_id=(SELECT id FROM operations WHERE environment_id=?4 ORDER BY created_at_ms DESC,id DESC LIMIT 1) AND EXISTS(SELECT 1 FROM operations WHERE id=?3 AND state='running')", json,commit,operation.id,app_id,fetched).execute(&mut *tx).await.map_err(StoreError::database)?.rows_affected(); + if changed != 1 { + return Err(StoreError::IllegalTransition); + } + sqlx::query!( + "UPDATE deployments SET manifest_json=?1,template_json=?2,variables_json=?3,warnings_json=?4 WHERE id=?5", + manifest, + json, + variables, + warnings, + operation.id + ) + .execute(&mut *tx) + .await + .map_err(StoreError::database)?; + let now = now_ms(); + Self::operation_event(&mut tx, &operation.id, "manifest_fetched", commit, now).await?; + if let Some(head) = branch_head { + Self::record_branch_head_on(&mut tx, &operation.environment_id, head, now).await?; + } + self.pin_secrets_on(&mut tx, operation, application, &generated) + .await?; + Self::commit_environment_changes(tx, [app_id]).await + } + + /// Records a fetched repository manifest, under the application's current + /// name, as its environment's last fetched one, while the environment + /// still follows a branch. Other environments keep their own. + /// + /// While the application is still repository-backed, a deployment of an + /// environment that fetched from the path, branch and commit + /// `spec.manifest` names (see `reads_connection_on`) also converges the + /// environments the saved manifest declares, and saves the manifest a + /// push changed (see `read_repository_on`). Other paths, branches, + /// one-off revisions and previews never do, so a manifest fetched before + /// the connection changed never replaces it. Records `application_applied` + /// when any manifest changed. + /// Fails with `secret_name_conflict` when the application's store now holds + /// a name the fetched manifest declares. + /// Called in the same transaction that saves the fully prepared runtime target. + pub(super) async fn accept_deployment_on( + tx: &mut Transaction<'_, Sqlite>, + operation: &Operation, + fetching: &EnvironmentKind, + ) -> Result<(), StoreError> { + let row = sqlx::query!( + "SELECT application_json,repository_json,fetched_json FROM deployment_inputs WHERE operation_id=?1 AND fetched=1 AND repository_commit IS NOT NULL", + operation.id + ) + .fetch_optional(&mut **tx) + .await + .map_err(StoreError::database)?; + let Some(row) = row else { + return Ok(()); + }; + let deployed: ApplicationTemplate = + serde_json::from_str(&row.application_json).map_err(StoreError::corrupt)?; + let stored = Self::application_on(tx, deployed.id().as_str()) + .await? + .ok_or(StoreError::NotFound)?; + let application = &stored.application; + // A secret stored since the manifest was fetched may now share a name + // with one of its declarations. + Self::check_declared_against_store_on( + tx, + application.id().as_str(), + &deployed.spec().secrets, + ) + .await?; + // A retry may accept a manifest fetched before a rename. The + // deployment keeps the files it captured. + let deployed = deployed + .with_name(application.metadata().name.clone()) + .without_files(); + let manifest = deployed.canonical_json().map_err(StoreError::corrupt)?; + let now = now_ms(); + let environment = operation.environment_id.as_str(); + let mut changed = sqlx::query!( + "UPDATE environments SET manifest_json=?1,updated_at_ms=?2 WHERE id=?3 AND branch IS NOT NULL AND manifest_json IS NOT ?1", + manifest, + now, + environment + ) + .execute(&mut **tx) + .await + .map_err(StoreError::database)? + .rows_affected(); + if let Some(connection) = + Self::reads_connection_on(tx, operation, fetching, &deployed, application).await? + { + // Without the files a deployment captured, which the spec hash + // covers, as the application keeps the one it last read. + let hash = |json: Option<&str>| { + json.map(|json| { + serde_json::from_str::(json) + .map(|manifest| manifest.without_files().spec_hash()) + .map_err(StoreError::corrupt) + }) + .transpose() + }; + let read = ( + hash(row.repository_json.as_deref())?, + hash(row.fetched_json.as_deref())?, + ); + changed += Self::read_repository_on( + tx, + operation, + &stored, + (deployed.with_manifest(Some(connection)), read), + now, + ) + .await?; + } + if changed > 0 { + Self::operation_event(tx, &operation.id, "application_applied", None, now).await?; + } + Ok(()) + } + + /// Converges the environments of `stored` to the ones its saved manifest + /// declares, retrying changes that had to wait, after saving `deployed`, + /// which `operation` deployed from its connection, when a push changed + /// the manifest. `read` holds the spec hashes of the manifest the + /// application had last read when `operation` was requested and of the + /// one it fetched: a push changed it when the fetched one differs from + /// that one, so `deployed` is the fetched one, and from the one the + /// application read last. It then becomes both the saved manifest, as + /// saving it would, and the one last read. Advances the revision when the + /// saved manifest changes, resolving `operation`, which deploys it, at + /// the new one unless its environment's source changed, or when + /// converging changed the source of an environment with a deployment in + /// progress, which then leaves it unresolved. Returns the rows changed. + async fn read_repository_on( + tx: &mut Transaction<'_, Sqlite>, + operation: &Operation, + stored: &super::StoredApplication, + (deployed, (captured, fetched)): (ApplicationTemplate, (Option, Option)), + now: i64, + ) -> Result { + let application = &stored.application; + let read = Self::repository_manifest_on(tx, stored) + .await? + .map(|read| read.spec_hash()); + let pushed = fetched.is_some() && fetched != captured && fetched != read; + let saved = if pushed { &deployed } else { application }; + let source = async |tx: &mut Transaction<'_, Sqlite>| { + Self::environment_on(tx, operation.environment_id.as_str()) + .await + .map(|environment| environment.map(|environment| environment.environment.source)) + }; + let before = source(tx).await?; + let converged = Self::converge_environments_on( + tx, + application.id(), + &saved + .spec() + .declared_environments_since(Some(application.spec()))?, + Some(&operation.environment_id), + now, + ) + .await?; + let edited = saved != application; + if converged || edited { + Self::bump_generation_on(tx, application.id(), stored.generation, None).await?; + } + if edited && source(tx).await? == before { + let (previous, revision) = ( + i64::try_from(stored.generation).map_err(StoreError::corrupt)?, + i64::try_from(stored.generation + 1).map_err(StoreError::corrupt)?, + ); + sqlx::query!( + "UPDATE operations SET generation=?1 WHERE id=?2 AND generation=?3", + revision, + operation.id, + previous + ) + .execute(&mut **tx) + .await + .map_err(StoreError::database)?; + } + if !pushed { + return Ok(0); + } + let deployed = deployed.canonical_json().map_err(StoreError::corrupt)?; + let id = application.id().as_str(); + Ok(sqlx::query!( + "UPDATE applications SET desired_json=?1,repository_json=?1,updated_at_ms=?2 WHERE id=?3", + deployed, + now, + id + ) + .execute(&mut **tx) + .await + .map_err(StoreError::database)? + .rows_affected()) + } + + /// Whether `operation`, a deployment of `kind`, fetched `fetched` + /// from the connection of `application`, which this returns: the + /// manifest an environment, not a preview, reads from it. + /// See [`Self::reads_connection_on`]. + /// + /// # Errors + /// Returns a storage error. + pub async fn reads_connection( + &self, + operation: &Operation, + kind: &EnvironmentKind, + fetched: &ApplicationTemplate, + ) -> Result { + let connection = &mut *self.connection().await?; + let application = Self::application_on(connection, fetched.id().as_str()) + .await? + .ok_or(StoreError::NotFound)?; + Ok(Self::reads_connection_on( + connection, + operation, + kind, + fetched, + &application.application, + ) + .await? + .is_some()) + } + + /// See [`Self::reads_connection`]. + async fn reads_connection_on( + connection: &mut SqliteConnection, + operation: &Operation, + kind: &EnvironmentKind, + fetched: &ApplicationTemplate, + application: &ApplicationTemplate, + ) -> Result, StoreError> { + let Some(wanted) = application.spec().manifest.clone() else { + return Ok(None); + }; + let reads = matches!(kind, EnvironmentKind::Environment) + && Self::fetched_connection_on(connection, operation, fetched, &wanted).await?; + Ok(reads.then_some(wanted)) + } + + /// Whether `fetched`, the manifest `operation` fetched, came from the + /// path and revision `wanted` names. Its own connection is the path + /// and revision it was fetched from; sync pins the head it listed of a + /// branch it follows, so its deployments of the connection's unpinned + /// branch count too. + async fn fetched_connection_on( + connection: &mut SqliteConnection, + operation: &Operation, + fetched: &ApplicationTemplate, + wanted: &RepositoryManifest, + ) -> Result { + let Some(fetched) = fetched + .spec() + .manifest + .as_ref() + .filter(|fetched| fetched.path == wanted.path) + .map(|fetched| &fetched.repository) + else { + return Ok(false); + }; + let wanted = &wanted.repository; + if fetched == wanted { + return Ok(true); + } + if fetched.url != wanted.url || fetched.branch != wanted.branch || wanted.commit.is_some() { + return Ok(false); + } + Self::requested_by_sync_on(connection, operation).await + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/piqueld-store/src/repository/tests.rs b/crates/piqueld-store/src/repository/tests.rs new file mode 100644 index 000000000..1201df92a --- /dev/null +++ b/crates/piqueld-store/src/repository/tests.rs @@ -0,0 +1,807 @@ +use super::*; +use crate::Actor::Daemon; +use crate::testing::template; +use crate::{Mutation, MutationResponse}; +use piqueld_core::{ApplicationId, EnvironmentId, OperationState, ResolutionSet}; + +#[tokio::test] +async fn fetched_snapshot_preserves_intervening_saved_configuration() { + let (_directory, store) = Store::temporary().await; + let initial = template( + "test", + "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/app.git'\nbranch='main'", + ); + let saved = store.save_template(initial, true).await; + let op = store.operation(&saved.operation_id.unwrap()).await.unwrap(); + store.mark_running(&op.id).await; + let captured = store.deployment_snapshot(&op.id).await.unwrap().template; + let mut fetched = captured.to_manifest(); + fetched.spec.manifest = None; + let fetched = fetched + .validate_template() + .unwrap() + .normalize(captured.id().clone()); + let environment = store.get(&op.environment_id).await.unwrap(); + let rendering = environment.render(&fetched, &op.id).unwrap(); + store + .save_deployment_input( + &op, + (&fetched, Some(&fetched)), + &rendering, + (Some(&"a".repeat(40)), None), + &[], + ) + .await + .unwrap(); + let mut edited = captured.to_manifest(); + edited.spec.manifest.as_mut().unwrap().path = "fixed.toml".into(); + let edited = edited + .validate_template() + .unwrap() + .normalize(captured.id().clone()); + store + .accept( + crate::Actor::Daemon, + Mutation::Save { + application: Box::new(edited.clone()), + expected_application_id: Some(captured.id().to_string()), + deploy: false, + }, + Some(1), + false, + None, + ) + .await + .unwrap(); + let target = piqueld_core::compile_application( + &rendering.application, + &op.environment_id, + store.instance_id().clone(), + &ResolutionSet::default(), + ) + .unwrap(); + store.save_prepared(&op, &target).await.unwrap(); + let saved = store.get(&op.environment_id).await.unwrap().application; + assert_eq!((saved.application, saved.generation), (edited.clone(), 2)); + assert_eq!(store.operation(&op.id).await.unwrap().generation, 1); + let snapshot = store.deployment_snapshot(&op.id).await.unwrap(); + assert_eq!(snapshot.template, fetched); + assert_eq!(snapshot.rendering, Some(rendering.clone())); + assert_eq!( + store + .deployments(&op.environment_id, None, 3) + .await + .unwrap() + .items[0] + .application, + Some(rendering.application.clone()) + ); + assert!(matches!( + store + .save_deployment_input(&op, (&edited, None), &rendering, (None, None), &[]) + .await, + Err(StoreError::IllegalTransition) + )); +} + +/// A repository-backed application `notes` whose saved manifest is only +/// its connection to `main`. +fn connection() -> piqueld_core::manifest::ValidatedTemplate { + template( + "notes", + "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'", + ) +} + +/// Deploys `environment` from a fetched manifest with `spec`, as the +/// controller does, through preparation. +async fn fetch(store: &Store, environment: &EnvironmentId, spec: &str) { + let (op, target) = fetched(store, environment, spec).await; + store.save_prepared(&op, &target).await.unwrap(); +} + +/// Starts a deployment of `environment` and fetches a manifest with +/// `spec`, returning the operation and the target it prepares. +async fn fetched( + store: &Store, + environment: &EnvironmentId, + spec: &str, +) -> (Operation, piqueld_core::ResolvedApplication) { + let (MutationResponse::Operation(accepted), _) = store + .accept( + crate::Actor::Daemon, + Mutation::deploy(environment.clone()), + None, + true, + None, + ) + .await + .unwrap() + else { + panic!("operation") + }; + prepared(store, environment, &accepted.operation_id, spec).await +} + +/// Runs operation `id` of `environment` through fetching a manifest with +/// `spec`, returning it and the target it prepares. +async fn prepared( + store: &Store, + environment: &EnvironmentId, + id: &str, + spec: &str, +) -> (Operation, piqueld_core::ResolvedApplication) { + let (op, fetched, rendering) = rendered(store, environment, id, spec).await; + store + .save_deployment_input( + &op, + (&fetched, Some(&fetched)), + &rendering, + (Some(&"a".repeat(40)), None), + &[], + ) + .await + .unwrap(); + let resolutions = ResolutionSet { + sources: [( + piqueld_core::ServiceName::parse("web").unwrap(), + piqueld_core::ResolvedSource::parse_image( + "ghcr.io/example/notes:1.4.0", + format!("ghcr.io/example/notes@sha256:{}", "a".repeat(64)), + ) + .unwrap(), + )] + .into(), + ..ResolutionSet::default() + }; + let target = piqueld_core::compile_application( + &rendering.application, + environment, + store.instance_id().clone(), + &resolutions, + ) + .unwrap(); + (op, target) +} + +/// Marks operation `id` of `environment` running and renders a manifest +/// with `spec` fetched for it, returning the operation, the manifest and +/// its rendering. +async fn rendered( + store: &Store, + environment: &EnvironmentId, + id: &str, + spec: &str, +) -> (Operation, ApplicationTemplate, Rendering) { + let op = store.operation(id).await.unwrap(); + store.mark_running(&op.id).await; + let current = store.get(environment).await.unwrap(); + // As fetching does, the connection replaces the file's own before validation. + let mut fetched = piqueld_core::manifest::ApplicationManifest::decode_toml(&format!( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n{spec}" + )) + .unwrap(); + fetched.spec.manifest = current.tracking().unwrap().repository(); + let fetched = fetched + .validate_template() + .unwrap() + .normalize(current.application.application.id().clone()); + let rendering = current.render(&fetched, &op.id).unwrap(); + (op, fetched, rendering) +} + +/// A fetch saved for superseded work stores none of the secret values +/// generated for it, so rejected candidates never use up the quota. +#[tokio::test] +async fn rejected_fetches_store_no_generated_secrets() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let deploy = async || { + let (MutationResponse::Operation(accepted), _) = store + .accept( + Daemon, + Mutation::deploy(production.clone()), + None, + true, + None, + ) + .await + .unwrap() + else { + panic!("operation") + }; + accepted.operation_id + }; + let first = deploy().await; + let spec = format!( + "{}\n[[spec.services.secrets]]\nname='token'\ntarget='/run/secrets/token'", + token_spec(true) + ); + let (op, fetched, rendering) = rendered(&store, &production, &first, &spec).await; + deploy().await; + assert!(matches!( + store + .save_deployment_input(&op, (&fetched, None), &rendering, (None, None), &[]) + .await, + Err(StoreError::IllegalTransition) + )); + assert!(store.secrets(&production).await.unwrap().is_empty()); +} + +/// A manifest fetched before a rename is accepted under the new name, as +/// when a deployment is retried. +#[tokio::test] +async fn fetched_manifests_keep_the_current_name() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (op, target) = fetched(&store, &production, &token_spec(false)).await; + store + .transition_operation( + &op.id, + OperationState::Running, + OperationState::Failed, + Some(("build_failed", "build failed")), + ) + .await + .unwrap(); + // Repository-backed applications are renamed while disconnected. + let repository = |repository| Mutation::Edit { + id: application.clone(), + edit: Box::new(piqueld_core::edit::ApplicationEdit::Repository(repository)), + deploy: false, + }; + for mutation in [ + repository(None), + crate::testing::rename_application(&application, "journal"), + repository(connection().spec().manifest.clone()), + ] { + store.force(mutation).await.unwrap(); + } + let op = store.retry_operation(&op).await.unwrap(); + store.mark_running(&op.id).await; + store.save_prepared(&op, &target).await.unwrap(); + let current = store.get(&production).await.unwrap(); + assert_eq!( + current.application.application.metadata().name.as_str(), + "journal" + ); + assert_eq!( + current.manifest().unwrap().metadata().name.as_str(), + "journal" + ); +} + +/// A manifest fetched before the connection changed never replaces the +/// configuration saved since: it came from the old path. +#[tokio::test] +async fn fetches_requested_before_a_save_keep_the_saved_configuration() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (op, target) = fetched(&store, &production, &token_spec(false)).await; + store + .force(Mutation::Edit { + id: application.clone(), + edit: Box::new(piqueld_core::edit::ApplicationEdit::RepositoryPath( + "fixed.toml".into(), + )), + deploy: false, + }) + .await + .unwrap(); + store.save_prepared(&op, &target).await.unwrap(); + let saved = store + .get(&production) + .await + .unwrap() + .application + .application; + assert_eq!(saved.spec().manifest.as_ref().unwrap().path, "fixed.toml"); + assert_eq!(saved.spec().services, Vec::new()); +} + +/// Environment changes advance the revision, but leave the connection a +/// manifest was fetched from, so one fetched meanwhile is still saved. +#[tokio::test] +async fn fetches_are_saved_across_environment_changes() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (op, target) = fetched(&store, &production, &token_spec(false)).await; + store + .force(Mutation::CreateEnvironment { + application, + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: None, + }) + .await + .unwrap(); + store.save_prepared(&op, &target).await.unwrap(); + let saved = store.get(&production).await.unwrap().application; + assert!(saved.generation > op.generation); + assert_eq!(saved.application.spec().services.len(), 1); +} + +/// A deployment that fetched the manifest the application had read when +/// it was requested saves nothing, even when it finishes after a push +/// and edits were saved since. +#[tokio::test] +async fn unchanged_fetches_keep_newer_edits() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + fetch(&store, &production, &token_spec(false)).await; + let MutationResponse::Environment(staging) = store + .force(Mutation::CreateEnvironment { + application: application.clone(), + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: None, + }) + .await + .unwrap() + else { + panic!("environment") + }; + let MutationResponse::Operation(delayed) = store + .force(Mutation::deploy(staging.id.clone())) + .await + .unwrap() + else { + panic!("operation") + }; + fetch( + &store, + &production, + &format!("{}\n[[spec.volumes]]\nname='data'", token_spec(false)), + ) + .await; + store + .force(Mutation::Edit { + id: application.clone(), + edit: Box::new(piqueld_core::edit::ApplicationEdit::Service { + name: "web".into(), + edit: piqueld_core::edit::ServiceEdit::Replicas(3.into()), + }), + deploy: false, + }) + .await + .unwrap(); + let (op, target) = prepared( + &store, + &staging.id, + &delayed.operation_id, + &token_spec(false), + ) + .await; + store.save_prepared(&op, &target).await.unwrap(); + let saved = store.application(&application).await.unwrap().application; + assert_eq!(saved.spec().services[0].replicas, 3.into()); + assert_eq!(saved.spec().volumes.len(), 1, "the push is kept"); +} + +/// A fetch is compared without the repository files it captured: the +/// manifest last read keeps none. Deployments fetched before the +/// migration recorded what they deployed, files included. +#[tokio::test] +async fn captured_files_are_not_a_push() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let spec = token_spec(false); + fetch(&store, &production, &spec).await; + store + .force(Mutation::Edit { + id: application.clone(), + edit: Box::new(piqueld_core::edit::ApplicationEdit::Service { + name: "web".into(), + edit: piqueld_core::edit::ServiceEdit::Replicas(3.into()), + }), + deploy: false, + }) + .await + .unwrap(); + let MutationResponse::Operation(accepted) = store + .force(Mutation::deploy(production.clone())) + .await + .unwrap() + else { + panic!("operation") + }; + let (op, target) = prepared(&store, &production, &accepted.operation_id, &spec).await; + let id = op.id.as_str(); + let json = sqlx::query_scalar!( + "SELECT application_json FROM deployment_inputs WHERE operation_id=?1", + id + ) + .fetch_one(&store.pool) + .await + .unwrap(); + let captured = serde_json::from_str::(&json) + .unwrap() + .with_files( + [("notes.yaml".to_owned(), "notes: true".to_owned())] + .into_iter() + .collect(), + ) + .unwrap() + .canonical_json() + .unwrap(); + sqlx::query!( + "UPDATE deployment_inputs SET application_json=?1,fetched_json=?1 WHERE operation_id=?2", + captured, + id + ) + .execute(&store.pool) + .await + .unwrap(); + store.save_prepared(&op, &target).await.unwrap(); + let saved = store.application(&application).await.unwrap().application; + assert_eq!(saved.spec().services[0].replicas, 3.into()); +} + +/// Each environment's hostname reservations and rename checks read its +/// own last fetched manifest, so a fetch for one never changes the other. +#[tokio::test] +async fn environments_reserve_and_rename_by_their_own_fetched_manifest() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (MutationResponse::Environment(staging), _) = store + .accept( + crate::Actor::Daemon, + Mutation::CreateEnvironment { + application, + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: Some(crate::SourceChoice::Branch( + piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), + )), + }, + None, + true, + None, + ) + .await + .unwrap() + else { + panic!("environment") + }; + let reserved = async |environment: &EnvironmentId| { + let id = environment.as_str(); + sqlx::query_scalar!( + "SELECT hostname FROM hostname_reservations WHERE environment_id=?1 ORDER BY hostname", + id + ) + .fetch_all(&store.pool) + .await + .unwrap() + }; + let service = token_spec(false); + fetch( + &store, + &production, + &format!("{service}\n[[spec.routes]]\nhostname='notes.example.com'\nservice='web'\nport=80\n[spec.environments.production.variables]\nlevel='debug'"), + ) + .await; + // Staging has fetched nothing yet, so it reserves nothing. + assert_eq!(reserved(&production).await, ["notes.example.com"]); + assert_eq!(reserved(&staging.id).await, Vec::::new()); + let before = store.get(&production).await.unwrap().own; + fetch( + &store, + &staging.id, + &format!( + "{service}\n[[spec.routes]]\nhostname='staging.example.com'\nservice='web'\nport=80" + ), + ) + .await; + assert_eq!(reserved(&production).await, ["notes.example.com"]); + assert_eq!(reserved(&staging.id).await, ["staging.example.com"]); + assert_eq!(store.get(&production).await.unwrap().own, before); + // Only production's own manifest configures `production`. + let rename = |id: &EnvironmentId| Mutation::RenameEnvironment { + id: id.clone(), + name: piqueld_core::EnvironmentName::parse("qa").unwrap(), + }; + assert!(matches!( + store.force(rename(&production)).await, + Err(StoreError::EnvironmentConfigured { .. }) + )); + store.force(rename(&staging.id)).await.unwrap(); +} + +/// Saves the repository-backed application `notes` (see `connection`). +async fn saved_connection(store: &Store) -> ApplicationId { + let saved = store.save_template(connection(), false).await; + ApplicationId::parse(&saved.application_id).unwrap() +} + +/// A manifest with the image service `web` that declares the generated +/// secret `token` when `declared`. +fn token_spec(declared: bool) -> String { + let secret = "[[spec.secrets]]\nname='token'\n[spec.secrets.generate]\ntype='random'\nbytes=16\nencoding='hex'\n"; + format!( + "{}[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='ghcr.io/example/notes:1.4.0'", + if declared { secret } else { "" } + ) +} + +/// Fetching a manifest from the branch `spec.manifest` names converges +/// the environments it declares, including the fetching one, whose own +/// deployment is past building; other branches never do. +#[tokio::test] +async fn fetches_of_the_connection_branch_converge_declared_environments() { + use piqueld_core::{EnvironmentSource, TrackedBranch}; + let (_directory, store) = Store::temporary().await; + let polled = template( + "notes", + "[spec.manifest]\npath='app.toml'\nsync={mode='poll'}\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'", + ); + let saved = store.save_template(polled, false).await; + let application = ApplicationId::parse(&saved.application_id).unwrap(); + let production = store.production(&application).await; + let declared = format!( + "[spec.environments.staging]\nsync=true\n[spec.environments.production]\npromote_from='staging'\n[spec.environments.canary]\nbranch='next'\n{}", + token_spec(false) + ); + fetch(&store, &production, &declared).await; + let environments = store.environments(&application).await.unwrap(); + let named = |name: &str| { + environments + .iter() + .find(|environment| environment.name.as_str() == name) + .unwrap() + .clone() + }; + let (staging, canary) = (named("staging"), named("canary")); + assert_eq!( + staging.source, + EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()) + ); + assert!(staging.sync); + assert_eq!( + canary.source, + EnvironmentSource::Branch(TrackedBranch::new("next".into(), None).unwrap()) + ); + assert_eq!( + named("production").source.promoted_from(), + Some(&staging.id) + ); + + // A manifest on another branch declares nothing. + fetch(&store, &canary.id, &token_spec(false)).await; + assert_eq!(store.environments(&application).await.unwrap().len(), 3); + // Sync pins the head it listed, and still fetches `main`. + let id = staging.id.as_str(); + let first = "a".repeat(40); + sqlx::query!( + "UPDATE environments SET synced_commit=?1,synced_at_ms=1 WHERE id=?2", + first, + id + ) + .execute(&store.pool) + .await + .unwrap(); + let (MutationResponse::Synced(crate::SyncOutcome::Deployed(synced)), _) = store + .accept( + crate::Actor::System(piqueld_core::sync::SystemActor::SyncPoll), + Mutation::Sync(crate::ListedHead { + id: staging.id.clone(), + repository: "https://example.com/notes.git".into(), + branch: piqueld_core::GitBranch::parse("main").unwrap(), + head: "b".repeat(40), + since: store.get(&staging.id).await.unwrap().environment.synced, + }), + None, + false, + None, + ) + .await + .unwrap() + else { + panic!("sync deployment expected") + }; + let (op, target) = prepared( + &store, + &staging.id, + &synced.operation_id, + &format!("{declared}\n[spec.environments.qa]\n"), + ) + .await; + store.save_prepared(&op, &target).await.unwrap(); + assert_eq!(store.environments(&application).await.unwrap().len(), 4); + // The next one from `main` stops staging syncing, and leaves canary + // and qa, no longer declared, as they are. + fetch( + &store, + &staging.id, + &format!( + "[spec.environments.staging]\n[spec.environments.production]\npromote_from='staging'\n{}", + token_spec(false) + ), + ) + .await; + let environments = store.environments(&application).await.unwrap(); + assert_eq!(environments.len(), 4); + assert!(!environments.iter().any(|environment| environment.sync)); +} + +/// A fetch that changes the saved manifest resolves its environment at +/// the revision it saved, unless it changes that environment's source. +#[tokio::test] +async fn fetches_resolve_their_environment_at_the_revision_they_save() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (op, target) = fetched(&store, &production, &token_spec(false)).await; + store.save_prepared(&op, &target).await.unwrap(); + store.publish_prepared(&op).await.unwrap(); + let current = store.get(&production).await.unwrap(); + assert_eq!(current.application.generation, op.generation + 1); + assert_eq!( + current.environment.resolved_generation, + Some(current.application.generation) + ); + // Unless the manifest moves the fetching environment elsewhere: it + // deployed its former branch. + let moved = format!( + "[spec.environments.production]\nbranch='release'\n{}", + token_spec(false) + ); + let (op, target) = fetched(&store, &production, &moved).await; + store.save_prepared(&op, &target).await.unwrap(); + store.publish_prepared(&op).await.unwrap(); + let current = store.get(&production).await.unwrap(); + assert_ne!( + current.environment.resolved_generation, + Some(current.application.generation) + ); +} + +/// A fetch that changes an environment's source leaves it unresolved, as +/// changing it with `env branch` does, and, like any fetch changing the +/// saved manifest, advances the revision. +#[tokio::test] +async fn fetched_source_changes_leave_environments_unresolved() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let canary = |branch: &str| { + format!( + "[spec.environments.canary]\nbranch='{branch}'\n{}", + token_spec(false) + ) + }; + fetch(&store, &production, &canary("next")).await; + let id = store + .environments(&application) + .await + .unwrap() + .into_iter() + .find(|environment| environment.name.as_str() == "canary") + .unwrap() + .id; + let canary_id = id.as_str(); + sqlx::query!( + "UPDATE environments SET resolved_generation=(SELECT generation FROM applications) WHERE id=?1", + canary_id + ) + .execute(&store.pool) + .await + .unwrap(); + let generation = store.get(&id).await.unwrap().application.generation; + fetch(&store, &production, &canary("release")).await; + let current = store.get(&id).await.unwrap(); + assert_eq!(current.environment.resolved_generation, None); + assert_eq!(current.application.generation, generation + 1); + + store + .accept(Daemon, Mutation::deploy(id.clone()), None, false, None) + .await + .unwrap(); + fetch(&store, &production, &canary("beta")).await; + assert_eq!( + store.get(&id).await.unwrap().application.generation, + generation + 2 + ); +} + +/// The saved manifest's declarations hold their names even for an +/// environment whose own fetched manifest, from another branch, has no +/// block: renaming it would leave the declaration to recreate it. +#[tokio::test] +async fn declared_environments_keep_their_names() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + fetch( + &store, + &production, + &format!( + "[spec.environments.staging]\nbranch='release'\n{}", + token_spec(false) + ), + ) + .await; + let staging = store + .environments(&application) + .await + .unwrap() + .into_iter() + .find(|environment| environment.name.as_str() == "staging") + .unwrap() + .id; + fetch(&store, &staging, &token_spec(false)).await; + let rename = Mutation::RenameEnvironment { + id: staging, + name: piqueld_core::EnvironmentName::parse("qa").unwrap(), + }; + assert!(matches!( + store.force(rename).await, + Err(StoreError::EnvironmentDeclared { environment }) if environment.as_str() == "staging" + )); +} + +/// A secret stored after a manifest was fetched but before it is accepted +/// may not share a name with one of its declarations. +#[tokio::test] +async fn accepting_a_fetched_manifest_rejects_declarations_stored_meanwhile() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let production = store.production(&application).await; + let (op, target) = fetched(&store, &production, &token_spec(true)).await; + // The saved manifest does not declare `token` yet, so storing it succeeds. + store + .put_stored_secret(Daemon, &application, "token", 0, b"value".to_vec(), None) + .await + .unwrap(); + let Err(StoreError::Validation(errors)) = store.save_prepared(&op, &target).await else { + panic!("secret name conflict expected") + }; + assert_eq!( + errors.0[0].code, + piqueld_core::ApiErrorCode::SecretNameConflict + ); + assert!(store.get(&production).await.unwrap().manifest().is_none()); +} + +/// A name an environment's last fetched manifest declares cannot be +/// stored, even once another environment's fetch replaced the saved one. +#[tokio::test] +async fn fetched_declarations_of_every_environment_reserve_their_names() { + let (_directory, store) = Store::temporary().await; + let application = saved_connection(&store).await; + let (MutationResponse::Environment(staging), _) = store + .accept( + Daemon, + Mutation::CreateEnvironment { + application: application.clone(), + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: Some(crate::SourceChoice::Branch( + piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), + )), + }, + None, + true, + None, + ) + .await + .unwrap() + else { + panic!("environment") + }; + let production = store.production(&application).await; + fetch(&store, &production, &token_spec(true)).await; + fetch(&store, &staging.id, &token_spec(false)).await; + let Err(StoreError::Validation(errors)) = store + .put_stored_secret(Daemon, &application, "token", 0, b"value".to_vec(), None) + .await + else { + panic!("secret name conflict expected") + }; + assert_eq!( + errors.0[0].code, + piqueld_core::ApiErrorCode::SecretNameConflict + ); +} diff --git a/crates/piqueld-store/src/secrets/generate.rs b/crates/piqueld-store/src/secrets/generate/mod.rs similarity index 68% rename from crates/piqueld-store/src/secrets/generate.rs rename to crates/piqueld-store/src/secrets/generate/mod.rs index f9f570938..cdebaf711 100644 --- a/crates/piqueld-store/src/secrets/generate.rs +++ b/crates/piqueld-store/src/secrets/generate/mod.rs @@ -47,33 +47,4 @@ impl Generate for SecretGenerator { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn random_values_are_fresh_and_encoded() { - let hex = SecretGenerator::Random { - bytes: 32, - encoding: SecretEncoding::Hex, - }; - let first = hex.generate().unwrap(); - assert_eq!(first.len(), 64); - assert!(first.iter().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))); - assert_ne!(first, hex.generate().unwrap()); - - let base64 = SecretGenerator::Random { - bytes: 32, - encoding: SecretEncoding::Base64url, - }; - let value = base64.generate().unwrap(); - assert_eq!(URL_SAFE_NO_PAD.decode(&*value).unwrap().len(), 32); - } - - #[test] - fn rsa_keys_are_pkcs8_pem() { - let pem = SecretGenerator::Rsa { bits: 2048 }.generate().unwrap(); - assert!(pem.starts_with(b"-----BEGIN PRIVATE KEY-----")); - let key = PKey::private_key_from_pem(&pem).unwrap(); - assert_eq!(key.rsa().unwrap().size() * 8, 2048); - } -} +mod tests; diff --git a/crates/piqueld-store/src/secrets/generate/tests.rs b/crates/piqueld-store/src/secrets/generate/tests.rs new file mode 100644 index 000000000..19e6ce987 --- /dev/null +++ b/crates/piqueld-store/src/secrets/generate/tests.rs @@ -0,0 +1,28 @@ +use super::*; + +#[test] +fn random_values_are_fresh_and_encoded() { + let hex = SecretGenerator::Random { + bytes: 32, + encoding: SecretEncoding::Hex, + }; + let first = hex.generate().unwrap(); + assert_eq!(first.len(), 64); + assert!(first.iter().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))); + assert_ne!(first, hex.generate().unwrap()); + + let base64 = SecretGenerator::Random { + bytes: 32, + encoding: SecretEncoding::Base64url, + }; + let value = base64.generate().unwrap(); + assert_eq!(URL_SAFE_NO_PAD.decode(&*value).unwrap().len(), 32); +} + +#[test] +fn rsa_keys_are_pkcs8_pem() { + let pem = SecretGenerator::Rsa { bits: 2048 }.generate().unwrap(); + assert!(pem.starts_with(b"-----BEGIN PRIVATE KEY-----")); + let key = PKey::private_key_from_pem(&pem).unwrap(); + assert_eq!(key.rsa().unwrap().size() * 8, 2048); +} diff --git a/crates/piqueld-store/src/sync.rs b/crates/piqueld-store/src/sync/mod.rs similarity index 50% rename from crates/piqueld-store/src/sync.rs rename to crates/piqueld-store/src/sync/mod.rs index b0f488c1d..4805e0304 100644 --- a/crates/piqueld-store/src/sync.rs +++ b/crates/piqueld-store/src/sync/mod.rs @@ -566,546 +566,4 @@ impl Store { } #[cfg(test)] -mod tests { - use super::*; - use crate::testing::template; - use crate::{Actor, Mutation, MutationResponse}; - use piqueld_core::sync::{RepositorySync, SyncedHead}; - - const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - const B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; - const C: &str = "cccccccccccccccccccccccccccccccccccccccc"; - - /// Saves the repository-backed `notes`, polling `main`, and returns its - /// only environment, opted in and never deployed. - async fn notes(store: &Store) -> EnvironmentId { - let template = template( - "notes", - "[spec.manifest]\npath='app.toml'\nsync={mode='poll'}\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'\n", - ); - let saved = store.save_template(template, false).await; - let application = ApplicationId::parse(saved.application_id).unwrap(); - let id = store.environments(&application).await.unwrap()[0] - .id - .clone(); - let opt_in = Mutation::SetSync { - id: id.clone(), - enabled: true, - }; - store - .accept(Actor::Daemon, opt_in, None, false, None) - .await - .unwrap(); - id - } - - /// Submits sync's mutation for `head` at `main`, as `sync:poll`. - async fn sync(store: &Store, id: &EnvironmentId, head: &str) -> SyncOutcome { - listed(store, id, "https://example.com/notes.git", head).await - } - - /// Submits sync's mutation for `head` at `main` of `repository`, listed - /// since the current head of its last deployment. - async fn listed( - store: &Store, - id: &EnvironmentId, - repository: &str, - head: &str, - ) -> SyncOutcome { - let since = store.get(id).await.unwrap().environment.synced; - submit(store, id, repository, head, since).await - } - - /// Submits sync's mutation for `head` at `main` of `repository`, listed - /// since `since`. - async fn submit( - store: &Store, - id: &EnvironmentId, - repository: &str, - head: &str, - since: Option, - ) -> SyncOutcome { - let mutation = Mutation::Sync(ListedHead { - id: id.clone(), - repository: repository.into(), - branch: piqueld_core::GitBranch::parse("main").unwrap(), - head: head.into(), - since, - }); - let actor = Actor::System(piqueld_core::sync::SystemActor::SyncPoll); - match store - .accept(actor, mutation, None, false, None) - .await - .unwrap() - { - (MutationResponse::Synced(outcome), _) => outcome, - _ => panic!("synced"), - } - } - - async fn operations(store: &Store, id: &EnvironmentId) -> i64 { - sqlx::query_scalar("SELECT COUNT(*) FROM operations WHERE environment_id=?1") - .bind(id.as_str()) - .fetch_one(&store.pool) - .await - .unwrap() - } - - #[tokio::test] - async fn a_moved_head_deploys_once_by_its_actor_and_pushes_coalesce_while_deploying() { - let (_temp, store) = Store::temporary().await; - let id = notes(&store).await; - store.deployed_at(&id, A).await; - - let SyncOutcome::Deployed(deployed) = sync(&store, &id, B).await else { - panic!("deployed") - }; - // It deploys exactly the head sync listed, not whatever the branch - // holds when it fetches. - let operation = store.operation(&deployed.operation_id).await.unwrap(); - let input = store.deployment_input(&operation).await.unwrap().unwrap(); - let fetched = input.template.spec().manifest.clone().unwrap().repository; - assert_eq!( - (fetched.branch.as_str(), fetched.commit.as_deref()), - ("main", Some(B)) - ); - let actors: Vec<(String, Option)> = sqlx::query_as( - "SELECT kind,actor_system FROM events WHERE operation_id=?1 ORDER BY id", - ) - .bind(&deployed.operation_id) - .fetch_all(&store.pool) - .await - .unwrap(); - assert!(actors.iter().any(|(kind, _)| kind == "branch_synced")); - assert!( - actors - .iter() - .all(|(_, actor)| actor.as_deref() == Some("sync:poll")), - "{actors:?}" - ); - let attributed: Option = - sqlx::query_scalar("SELECT actor_system FROM operations WHERE id=?1") - .bind(&deployed.operation_id) - .fetch_one(&store.pool) - .await - .unwrap(); - assert_eq!(attributed.as_deref(), Some("sync:poll")); - assert_eq!( - store - .get(&id) - .await - .unwrap() - .environment - .synced - .unwrap() - .commit, - Some(B.into()) - ); - - // A push while that deployment runs waits for it instead of - // superseding it. - assert!(matches!(sync(&store, &id, B).await, SyncOutcome::Busy)); - assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Busy)); - assert_eq!(operations(&store, &id).await, 2); - - // A failing deployment is superseded: the push may fix it. - sqlx::query("UPDATE operations SET state='running',error_code='image_pull_failed',error_message='failed' WHERE id=?1") - .bind(&deployed.operation_id) - .execute(&store.pool) - .await - .unwrap(); - let SyncOutcome::Deployed(retrying) = sync(&store, &id, C).await else { - panic!("deployed") - }; - assert_eq!( - store.operation(&deployed.operation_id).await.unwrap().state, - piqueld_core::OperationState::Superseded - ); - - // C fails before fetching too, then the branch is rolled back to A. - // A deployed once, but C's retry would replace it: A deploys again. - sqlx::query("UPDATE operations SET state='running',error_code='image_pull_failed',error_message='failed' WHERE id=?1") - .bind(&retrying.operation_id) - .execute(&store.pool) - .await - .unwrap(); - assert!(matches!( - sync(&store, &id, A).await, - SyncOutcome::Deployed(_) - )); - assert_eq!( - store.operation(&retrying.operation_id).await.unwrap().state, - piqueld_core::OperationState::Superseded - ); - } - - #[tokio::test] - async fn a_rollback_after_a_manual_deployment_deploys_the_branch_head_again() { - let (_temp, store) = Store::temporary().await; - let id = notes(&store).await; - store.deployed_at(&id, A).await; - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); - // A listing that started before another deployment finished never - // undoes it, even when that deployment recorded the same commit - // again: it lists again. - let before = store.get(&id).await.unwrap().environment.synced; - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - store.deployed_at(&id, A).await; - let stale = submit(&store, &id, "https://example.com/notes.git", B, before).await; - assert!(matches!(stale, SyncOutcome::Busy)); - // Someone deploys the branch at C by hand, then it goes back to A. - store.deployed_at(&id, C).await; - assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); - assert!(matches!( - sync(&store, &id, A).await, - SyncOutcome::Deployed(_) - )); - // Once deployed, the same head never deploys twice. - sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE environment_id=?1 AND state='requested'") - .bind(id.as_str()) - .execute(&store.pool) - .await - .unwrap(); - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); - // A rollback while a deployment by hand runs waits for it: that - // deployment may still record another head. - let deploy = Mutation::deploy(id.clone()); - store.force(deploy).await.unwrap(); - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Busy)); - } - - #[tokio::test] - async fn nothing_follows_before_its_first_deployment_nor_while_pinned_or_opted_out() { - let (_temp, store) = Store::temporary().await; - let id = notes(&store).await; - - // Never deployed: pushes do nothing, not even record a head. - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); - assert_eq!(store.get(&id).await.unwrap().environment.synced, None); - // While its first deployment runs, a push waits for it, since that - // records the head it fetched; one that failed records nothing. - let deploy = Mutation::deploy(id.clone()); - store.force(deploy).await.unwrap(); - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Busy)); - sqlx::query("UPDATE operations SET state='failed',finished_at_ms=1,error_code='manifest_invalid',error_message='invalid' WHERE environment_id=?1") - .bind(id.as_str()) - .execute(&store.pool) - .await - .unwrap(); - assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); - // A deployment's head is what it follows from. - store.deployed_at(&id, B).await; - assert!(matches!(sync(&store, &id, B).await, SyncOutcome::Current)); - // Heads listed from a repository it no longer reads deploy nothing. - let elsewhere = listed(&store, &id, "https://example.com/fork.git", C).await; - assert!(matches!(elsewhere, SyncOutcome::Current)); - assert_eq!(operations(&store, &id).await, 2); - - let opt_out = Mutation::SetSync { - id: id.clone(), - enabled: false, - }; - store - .accept(Actor::Daemon, opt_out, None, false, None) - .await - .unwrap(); - assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); - let opt_in = Mutation::SetSync { - id: id.clone(), - enabled: true, - }; - store - .accept(Actor::Daemon, opt_in, None, false, None) - .await - .unwrap(); - let pin = Mutation::SetBranch { - id: id.clone(), - branch: piqueld_core::TrackedBranch::new("main".into(), Some(B.into())).unwrap(), - }; - store.force(pin).await.unwrap(); - assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); - // Unpinned again, it follows only from its next deployment. - let unpin = Mutation::SetBranch { - id: id.clone(), - branch: piqueld_core::TrackedBranch::new("main".into(), None).unwrap(), - }; - store.force(unpin).await.unwrap(); - assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); - assert_eq!(operations(&store, &id).await, 2); - } - - #[tokio::test] - async fn only_turning_sync_on_or_opting_in_needs_the_permission_to_deploy() { - use piqueld_core::access::Scope; - use piqueld_core::edit::ApplicationEdit; - let (_temp, store) = Store::temporary().await; - let id = notes(&store).await; - let application = store.get(&id).await.unwrap().environment.application_id; - let mut grants = piqueld_core::access::Grants::default(); - grants - .grant( - Permission::App(AppPermission::Write), - &Scope::one(application.clone()), - ) - .unwrap(); - let alice = store.seed_caller("alice", &grants).await; - let edit = |edit| Mutation::Edit { - id: application.clone(), - edit: Box::new(edit), - deploy: false, - }; - let opt_in = || Mutation::SetSync { - id: id.clone(), - enabled: true, - }; - let poll = RepositorySync::Poll { - interval_seconds: 60, - }; - let refused = |result: Result<_, StoreError>| { - assert!( - matches!(result, Err(StoreError::Denied(_))), - "{:?}", - result.err() - ); - }; - // While it syncs, opting in lets sync deploy the environment. - refused(store.accept(alice, opt_in(), None, false, None).await); - // Changing branches, repositories, or environments deploys nothing: - // each follows only from its next deployment. - let create = Mutation::CreateEnvironment { - application: application.clone(), - name: piqueld_core::EnvironmentName::parse("staging").unwrap(), - source: None, - }; - let branch = Mutation::SetBranch { - id: id.clone(), - branch: piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), - }; - let url = edit(ApplicationEdit::RepositoryUrl( - "https://example.com/fork.git".into(), - )); - for mutation in [ - create, - branch, - url, - edit(ApplicationEdit::RepositorySync(poll)), - ] { - store - .accept(alice, mutation, None, true, None) - .await - .unwrap(); - } - // Turning it off needs nothing more; turning it back on does. - let off = edit(ApplicationEdit::RepositorySync(RepositorySync::Off)); - store.accept(alice, off, None, true, None).await.unwrap(); - refused( - store - .accept( - alice, - edit(ApplicationEdit::RepositorySync(poll)), - None, - true, - None, - ) - .await, - ); - // Opting in while it does not sync deploys nothing yet. - store - .accept(alice, opt_in(), None, false, None) - .await - .unwrap(); - } - - #[tokio::test] - async fn a_deployment_records_its_head_only_while_it_follows_that_branch_and_repository() { - let (_temp, store) = Store::temporary().await; - let id = notes(&store).await; - store.deployed_at(&id, A).await; - let record = |url: &str, branch: &str| { - let head = BranchHead { - url: url.into(), - branch: branch.into(), - commit: Some(C.into()), - }; - let store = &store; - let id = id.clone(); - async move { - let (_writer, mut tx) = store.begin_immediate().await.unwrap(); - Store::record_branch_head_on(&mut tx, &id, &head, 1) - .await - .unwrap(); - tx.commit().await.unwrap(); - } - }; - // A fetch from a branch or repository it left changes nothing. - record("https://example.com/notes.git", "release").await; - record("https://example.com/fork.git", "main").await; - assert_eq!( - store - .get(&id) - .await - .unwrap() - .environment - .synced - .unwrap() - .commit, - Some(A.into()) - ); - record("https://example.com/notes.git", "main").await; - assert_eq!( - store - .get(&id) - .await - .unwrap() - .environment - .synced - .unwrap() - .commit, - Some(C.into()) - ); - // A deployment remembers the branch it was requested for, so one - // queued before a branch change never records the new branch's head. - let deploy = Mutation::deploy(id.clone()); - let (MutationResponse::Operation(queued), _) = store - .accept(Actor::Daemon, deploy, None, true, None) - .await - .unwrap() - else { - panic!("operation") - }; - let release = Mutation::SetBranch { - id: id.clone(), - branch: piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), - }; - store.force(release).await.unwrap(); - let queued = store.operation(&queued.operation_id).await.unwrap(); - let input = store.deployment_input(&queued).await.unwrap().unwrap(); - assert_eq!(input.tracked_branch.as_deref(), Some("main")); - } - - /// Deploys a local snapshot to the preview of `main` in slot `agent` of - /// `application`, and finishes it as the controller would, having found - /// `main` at `head`, or absent. Returns the preview. - async fn snapshot_deployed( - store: &Store, - application: &ApplicationId, - head: Option<&str>, - ) -> EnvironmentId { - let mutation = Mutation::Preview(crate::PreviewMutation::Local { - application: application.clone(), - branch: piqueld_core::GitBranch::parse("main").unwrap(), - slot: Some(piqueld_core::PreviewSlot::parse("agent").unwrap()), - repository: "https://example.com/notes.git".into(), - snapshot: piqueld_core::api::LocalSnapshot { - commit: C.into(), - base: None, - }, - }); - let (MutationResponse::Preview(created), _) = store - .accept(Actor::Daemon, mutation, None, false, None) - .await - .unwrap() - else { - panic!("preview") - }; - let (id, operation) = (created.preview.id, created.operation.operation_id); - let (_writer, mut tx) = store.begin_immediate().await.unwrap(); - sqlx::query( - "UPDATE deployment_inputs SET fetched=1,repository_commit=?1 WHERE operation_id=?2", - ) - .bind(C) - .bind(&operation) - .execute(&mut *tx) - .await - .unwrap(); - sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE id=?1") - .bind(&operation) - .execute(&mut *tx) - .await - .unwrap(); - let head = BranchHead { - url: "https://example.com/notes.git".into(), - branch: "main".into(), - commit: head.map(str::to_owned), - }; - Store::record_branch_head_on(&mut tx, &id, &head, 1) - .await - .unwrap(); - tx.commit().await.unwrap(); - id - } - - /// A local snapshot differs from its branch head, which sync must not - /// take for a move: it stays until the branch really moves, or, for a - /// branch never pushed, until it is pushed. - #[tokio::test] - async fn local_snapshots_stay_until_their_branch_moves_or_is_first_pushed() { - let (_temp, store) = Store::temporary().await; - let environment = notes(&store).await; - let application = store - .get(&environment) - .await - .unwrap() - .environment - .application_id; - - // The branch is at A, so the snapshot stays while it is. - let preview = snapshot_deployed(&store, &application, Some(A)).await; - assert!(matches!( - sync(&store, &preview, A).await, - SyncOutcome::Current - )); - assert_eq!(operations(&store, &preview).await, 1); - let SyncOutcome::Deployed(pushed) = sync(&store, &preview, B).await else { - panic!("deployed") - }; - assert_eq!( - store - .preview_origins(&preview) - .await - .unwrap() - .latest - .unwrap(), - piqueld_core::api::DeploymentOrigin::Build - ); - sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE id=?1") - .bind(&pushed.operation_id) - .execute(&store.pool) - .await - .unwrap(); - - // Never pushed: following, and the first push deploys. - let preview = snapshot_deployed(&store, &application, None).await; - let synced = store.get(&preview).await.unwrap().environment; - assert_eq!(synced.synced.as_ref().unwrap().commit, None); - assert_eq!( - synced.sync_state( - store - .application(&application) - .await - .unwrap() - .application - .spec() - .manifest - .as_ref() - ), - piqueld_core::sync::SyncState::Following - ); - assert!(matches!( - sync(&store, &preview, B).await, - SyncOutcome::Deployed(_) - )); - assert_eq!( - store - .get(&preview) - .await - .unwrap() - .environment - .synced - .unwrap() - .commit - .as_deref(), - Some(B) - ); - } -} +mod tests; diff --git a/crates/piqueld-store/src/sync/tests.rs b/crates/piqueld-store/src/sync/tests.rs new file mode 100644 index 000000000..4079a606f --- /dev/null +++ b/crates/piqueld-store/src/sync/tests.rs @@ -0,0 +1,535 @@ +use super::*; +use crate::testing::template; +use crate::{Actor, Mutation, MutationResponse}; +use piqueld_core::sync::{RepositorySync, SyncedHead}; + +const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const C: &str = "cccccccccccccccccccccccccccccccccccccccc"; + +/// Saves the repository-backed `notes`, polling `main`, and returns its +/// only environment, opted in and never deployed. +async fn notes(store: &Store) -> EnvironmentId { + let template = template( + "notes", + "[spec.manifest]\npath='app.toml'\nsync={mode='poll'}\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'\n", + ); + let saved = store.save_template(template, false).await; + let application = ApplicationId::parse(saved.application_id).unwrap(); + let id = store.environments(&application).await.unwrap()[0] + .id + .clone(); + let opt_in = Mutation::SetSync { + id: id.clone(), + enabled: true, + }; + store + .accept(Actor::Daemon, opt_in, None, false, None) + .await + .unwrap(); + id +} + +/// Submits sync's mutation for `head` at `main`, as `sync:poll`. +async fn sync(store: &Store, id: &EnvironmentId, head: &str) -> SyncOutcome { + listed(store, id, "https://example.com/notes.git", head).await +} + +/// Submits sync's mutation for `head` at `main` of `repository`, listed +/// since the current head of its last deployment. +async fn listed(store: &Store, id: &EnvironmentId, repository: &str, head: &str) -> SyncOutcome { + let since = store.get(id).await.unwrap().environment.synced; + submit(store, id, repository, head, since).await +} + +/// Submits sync's mutation for `head` at `main` of `repository`, listed +/// since `since`. +async fn submit( + store: &Store, + id: &EnvironmentId, + repository: &str, + head: &str, + since: Option, +) -> SyncOutcome { + let mutation = Mutation::Sync(ListedHead { + id: id.clone(), + repository: repository.into(), + branch: piqueld_core::GitBranch::parse("main").unwrap(), + head: head.into(), + since, + }); + let actor = Actor::System(piqueld_core::sync::SystemActor::SyncPoll); + match store + .accept(actor, mutation, None, false, None) + .await + .unwrap() + { + (MutationResponse::Synced(outcome), _) => outcome, + _ => panic!("synced"), + } +} + +async fn operations(store: &Store, id: &EnvironmentId) -> i64 { + sqlx::query_scalar("SELECT COUNT(*) FROM operations WHERE environment_id=?1") + .bind(id.as_str()) + .fetch_one(&store.pool) + .await + .unwrap() +} + +#[tokio::test] +async fn a_moved_head_deploys_once_by_its_actor_and_pushes_coalesce_while_deploying() { + let (_temp, store) = Store::temporary().await; + let id = notes(&store).await; + store.deployed_at(&id, A).await; + + let SyncOutcome::Deployed(deployed) = sync(&store, &id, B).await else { + panic!("deployed") + }; + // It deploys exactly the head sync listed, not whatever the branch + // holds when it fetches. + let operation = store.operation(&deployed.operation_id).await.unwrap(); + let input = store.deployment_input(&operation).await.unwrap().unwrap(); + let fetched = input.template.spec().manifest.clone().unwrap().repository; + assert_eq!( + (fetched.branch.as_str(), fetched.commit.as_deref()), + ("main", Some(B)) + ); + let actors: Vec<(String, Option)> = + sqlx::query_as("SELECT kind,actor_system FROM events WHERE operation_id=?1 ORDER BY id") + .bind(&deployed.operation_id) + .fetch_all(&store.pool) + .await + .unwrap(); + assert!(actors.iter().any(|(kind, _)| kind == "branch_synced")); + assert!( + actors + .iter() + .all(|(_, actor)| actor.as_deref() == Some("sync:poll")), + "{actors:?}" + ); + let attributed: Option = + sqlx::query_scalar("SELECT actor_system FROM operations WHERE id=?1") + .bind(&deployed.operation_id) + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(attributed.as_deref(), Some("sync:poll")); + assert_eq!( + store + .get(&id) + .await + .unwrap() + .environment + .synced + .unwrap() + .commit, + Some(B.into()) + ); + + // A push while that deployment runs waits for it instead of + // superseding it. + assert!(matches!(sync(&store, &id, B).await, SyncOutcome::Busy)); + assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Busy)); + assert_eq!(operations(&store, &id).await, 2); + + // A failing deployment is superseded: the push may fix it. + sqlx::query("UPDATE operations SET state='running',error_code='image_pull_failed',error_message='failed' WHERE id=?1") + .bind(&deployed.operation_id) + .execute(&store.pool) + .await + .unwrap(); + let SyncOutcome::Deployed(retrying) = sync(&store, &id, C).await else { + panic!("deployed") + }; + assert_eq!( + store.operation(&deployed.operation_id).await.unwrap().state, + piqueld_core::OperationState::Superseded + ); + + // C fails before fetching too, then the branch is rolled back to A. + // A deployed once, but C's retry would replace it: A deploys again. + sqlx::query("UPDATE operations SET state='running',error_code='image_pull_failed',error_message='failed' WHERE id=?1") + .bind(&retrying.operation_id) + .execute(&store.pool) + .await + .unwrap(); + assert!(matches!( + sync(&store, &id, A).await, + SyncOutcome::Deployed(_) + )); + assert_eq!( + store.operation(&retrying.operation_id).await.unwrap().state, + piqueld_core::OperationState::Superseded + ); +} + +#[tokio::test] +async fn a_rollback_after_a_manual_deployment_deploys_the_branch_head_again() { + let (_temp, store) = Store::temporary().await; + let id = notes(&store).await; + store.deployed_at(&id, A).await; + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); + // A listing that started before another deployment finished never + // undoes it, even when that deployment recorded the same commit + // again: it lists again. + let before = store.get(&id).await.unwrap().environment.synced; + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + store.deployed_at(&id, A).await; + let stale = submit(&store, &id, "https://example.com/notes.git", B, before).await; + assert!(matches!(stale, SyncOutcome::Busy)); + // Someone deploys the branch at C by hand, then it goes back to A. + store.deployed_at(&id, C).await; + assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); + assert!(matches!( + sync(&store, &id, A).await, + SyncOutcome::Deployed(_) + )); + // Once deployed, the same head never deploys twice. + sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE environment_id=?1 AND state='requested'") + .bind(id.as_str()) + .execute(&store.pool) + .await + .unwrap(); + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); + // A rollback while a deployment by hand runs waits for it: that + // deployment may still record another head. + let deploy = Mutation::deploy(id.clone()); + store.force(deploy).await.unwrap(); + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Busy)); +} + +#[tokio::test] +async fn nothing_follows_before_its_first_deployment_nor_while_pinned_or_opted_out() { + let (_temp, store) = Store::temporary().await; + let id = notes(&store).await; + + // Never deployed: pushes do nothing, not even record a head. + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); + assert_eq!(store.get(&id).await.unwrap().environment.synced, None); + // While its first deployment runs, a push waits for it, since that + // records the head it fetched; one that failed records nothing. + let deploy = Mutation::deploy(id.clone()); + store.force(deploy).await.unwrap(); + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Busy)); + sqlx::query("UPDATE operations SET state='failed',finished_at_ms=1,error_code='manifest_invalid',error_message='invalid' WHERE environment_id=?1") + .bind(id.as_str()) + .execute(&store.pool) + .await + .unwrap(); + assert!(matches!(sync(&store, &id, A).await, SyncOutcome::Current)); + // A deployment's head is what it follows from. + store.deployed_at(&id, B).await; + assert!(matches!(sync(&store, &id, B).await, SyncOutcome::Current)); + // Heads listed from a repository it no longer reads deploy nothing. + let elsewhere = listed(&store, &id, "https://example.com/fork.git", C).await; + assert!(matches!(elsewhere, SyncOutcome::Current)); + assert_eq!(operations(&store, &id).await, 2); + + let opt_out = Mutation::SetSync { + id: id.clone(), + enabled: false, + }; + store + .accept(Actor::Daemon, opt_out, None, false, None) + .await + .unwrap(); + assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); + let opt_in = Mutation::SetSync { + id: id.clone(), + enabled: true, + }; + store + .accept(Actor::Daemon, opt_in, None, false, None) + .await + .unwrap(); + let pin = Mutation::SetBranch { + id: id.clone(), + branch: piqueld_core::TrackedBranch::new("main".into(), Some(B.into())).unwrap(), + }; + store.force(pin).await.unwrap(); + assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); + // Unpinned again, it follows only from its next deployment. + let unpin = Mutation::SetBranch { + id: id.clone(), + branch: piqueld_core::TrackedBranch::new("main".into(), None).unwrap(), + }; + store.force(unpin).await.unwrap(); + assert!(matches!(sync(&store, &id, C).await, SyncOutcome::Current)); + assert_eq!(operations(&store, &id).await, 2); +} + +#[tokio::test] +async fn only_turning_sync_on_or_opting_in_needs_the_permission_to_deploy() { + use piqueld_core::access::Scope; + use piqueld_core::edit::ApplicationEdit; + let (_temp, store) = Store::temporary().await; + let id = notes(&store).await; + let application = store.get(&id).await.unwrap().environment.application_id; + let mut grants = piqueld_core::access::Grants::default(); + grants + .grant( + Permission::App(AppPermission::Write), + &Scope::one(application.clone()), + ) + .unwrap(); + let alice = store.seed_caller("alice", &grants).await; + let edit = |edit| Mutation::Edit { + id: application.clone(), + edit: Box::new(edit), + deploy: false, + }; + let opt_in = || Mutation::SetSync { + id: id.clone(), + enabled: true, + }; + let poll = RepositorySync::Poll { + interval_seconds: 60, + }; + let refused = |result: Result<_, StoreError>| { + assert!( + matches!(result, Err(StoreError::Denied(_))), + "{:?}", + result.err() + ); + }; + // While it syncs, opting in lets sync deploy the environment. + refused(store.accept(alice, opt_in(), None, false, None).await); + // Changing branches, repositories, or environments deploys nothing: + // each follows only from its next deployment. + let create = Mutation::CreateEnvironment { + application: application.clone(), + name: piqueld_core::EnvironmentName::parse("staging").unwrap(), + source: None, + }; + let branch = Mutation::SetBranch { + id: id.clone(), + branch: piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), + }; + let url = edit(ApplicationEdit::RepositoryUrl( + "https://example.com/fork.git".into(), + )); + for mutation in [ + create, + branch, + url, + edit(ApplicationEdit::RepositorySync(poll)), + ] { + store + .accept(alice, mutation, None, true, None) + .await + .unwrap(); + } + // Turning it off needs nothing more; turning it back on does. + let off = edit(ApplicationEdit::RepositorySync(RepositorySync::Off)); + store.accept(alice, off, None, true, None).await.unwrap(); + refused( + store + .accept( + alice, + edit(ApplicationEdit::RepositorySync(poll)), + None, + true, + None, + ) + .await, + ); + // Opting in while it does not sync deploys nothing yet. + store + .accept(alice, opt_in(), None, false, None) + .await + .unwrap(); +} + +#[tokio::test] +async fn a_deployment_records_its_head_only_while_it_follows_that_branch_and_repository() { + let (_temp, store) = Store::temporary().await; + let id = notes(&store).await; + store.deployed_at(&id, A).await; + let record = |url: &str, branch: &str| { + let head = BranchHead { + url: url.into(), + branch: branch.into(), + commit: Some(C.into()), + }; + let store = &store; + let id = id.clone(); + async move { + let (_writer, mut tx) = store.begin_immediate().await.unwrap(); + Store::record_branch_head_on(&mut tx, &id, &head, 1) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + }; + // A fetch from a branch or repository it left changes nothing. + record("https://example.com/notes.git", "release").await; + record("https://example.com/fork.git", "main").await; + assert_eq!( + store + .get(&id) + .await + .unwrap() + .environment + .synced + .unwrap() + .commit, + Some(A.into()) + ); + record("https://example.com/notes.git", "main").await; + assert_eq!( + store + .get(&id) + .await + .unwrap() + .environment + .synced + .unwrap() + .commit, + Some(C.into()) + ); + // A deployment remembers the branch it was requested for, so one + // queued before a branch change never records the new branch's head. + let deploy = Mutation::deploy(id.clone()); + let (MutationResponse::Operation(queued), _) = store + .accept(Actor::Daemon, deploy, None, true, None) + .await + .unwrap() + else { + panic!("operation") + }; + let release = Mutation::SetBranch { + id: id.clone(), + branch: piqueld_core::TrackedBranch::new("release".into(), None).unwrap(), + }; + store.force(release).await.unwrap(); + let queued = store.operation(&queued.operation_id).await.unwrap(); + let input = store.deployment_input(&queued).await.unwrap().unwrap(); + assert_eq!(input.tracked_branch.as_deref(), Some("main")); +} + +/// Deploys a local snapshot to the preview of `main` in slot `agent` of +/// `application`, and finishes it as the controller would, having found +/// `main` at `head`, or absent. Returns the preview. +async fn snapshot_deployed( + store: &Store, + application: &ApplicationId, + head: Option<&str>, +) -> EnvironmentId { + let mutation = Mutation::Preview(crate::PreviewMutation::Local { + application: application.clone(), + branch: piqueld_core::GitBranch::parse("main").unwrap(), + slot: Some(piqueld_core::PreviewSlot::parse("agent").unwrap()), + repository: "https://example.com/notes.git".into(), + snapshot: piqueld_core::api::LocalSnapshot { + commit: C.into(), + base: None, + }, + }); + let (MutationResponse::Preview(created), _) = store + .accept(Actor::Daemon, mutation, None, false, None) + .await + .unwrap() + else { + panic!("preview") + }; + let (id, operation) = (created.preview.id, created.operation.operation_id); + let (_writer, mut tx) = store.begin_immediate().await.unwrap(); + sqlx::query( + "UPDATE deployment_inputs SET fetched=1,repository_commit=?1 WHERE operation_id=?2", + ) + .bind(C) + .bind(&operation) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE id=?1") + .bind(&operation) + .execute(&mut *tx) + .await + .unwrap(); + let head = BranchHead { + url: "https://example.com/notes.git".into(), + branch: "main".into(), + commit: head.map(str::to_owned), + }; + Store::record_branch_head_on(&mut tx, &id, &head, 1) + .await + .unwrap(); + tx.commit().await.unwrap(); + id +} + +/// A local snapshot differs from its branch head, which sync must not +/// take for a move: it stays until the branch really moves, or, for a +/// branch never pushed, until it is pushed. +#[tokio::test] +async fn local_snapshots_stay_until_their_branch_moves_or_is_first_pushed() { + let (_temp, store) = Store::temporary().await; + let environment = notes(&store).await; + let application = store + .get(&environment) + .await + .unwrap() + .environment + .application_id; + + // The branch is at A, so the snapshot stays while it is. + let preview = snapshot_deployed(&store, &application, Some(A)).await; + assert!(matches!( + sync(&store, &preview, A).await, + SyncOutcome::Current + )); + assert_eq!(operations(&store, &preview).await, 1); + let SyncOutcome::Deployed(pushed) = sync(&store, &preview, B).await else { + panic!("deployed") + }; + assert_eq!( + store + .preview_origins(&preview) + .await + .unwrap() + .latest + .unwrap(), + piqueld_core::api::DeploymentOrigin::Build + ); + sqlx::query("UPDATE operations SET state='succeeded',finished_at_ms=1 WHERE id=?1") + .bind(&pushed.operation_id) + .execute(&store.pool) + .await + .unwrap(); + + // Never pushed: following, and the first push deploys. + let preview = snapshot_deployed(&store, &application, None).await; + let synced = store.get(&preview).await.unwrap().environment; + assert_eq!(synced.synced.as_ref().unwrap().commit, None); + assert_eq!( + synced.sync_state( + store + .application(&application) + .await + .unwrap() + .application + .spec() + .manifest + .as_ref() + ), + piqueld_core::sync::SyncState::Following + ); + assert!(matches!( + sync(&store, &preview, B).await, + SyncOutcome::Deployed(_) + )); + assert_eq!( + store + .get(&preview) + .await + .unwrap() + .environment + .synced + .unwrap() + .commit + .as_deref(), + Some(B) + ); +}