diff --git a/crates/piqueld-core/src/build_machine.rs b/crates/piqueld-core/src/build_machine/mod.rs similarity index 67% rename from crates/piqueld-core/src/build_machine.rs rename to crates/piqueld-core/src/build_machine/mod.rs index 3732fd3f5..5decb0d93 100644 --- a/crates/piqueld-core/src/build_machine.rs +++ b/crates/piqueld-core/src/build_machine/mod.rs @@ -142,71 +142,4 @@ impl std::fmt::Display for BuildRepository { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_builder_is_a_tcp_host_and_port() { - for (endpoint, address) in [ - ( - "tcp://build.example.ts.net:1234", - "build.example.ts.net:1234", - ), - ("tcp://100.64.0.1:1234/", "100.64.0.1:1234"), - ("tcp://[fd7a::1]:1234", "[fd7a::1]:1234"), - ] { - let parsed = BuilderEndpoint::try_from(endpoint.to_owned()).unwrap(); - assert_eq!(parsed.address(), address); - } - for invalid in [ - // No port, another scheme, credentials, a path, and a bare IPv6 host. - "tcp://build.example.ts.net", - "ssh://build.example.ts.net:22", - "tcp://user@build.example:1234", - "tcp://build.example:1234/buildkit", - "tcp://fd7a::1:1234", - "tcp://:1234", - ] { - assert!( - BuilderEndpoint::try_from(invalid.to_owned()).is_err(), - "{invalid}" - ); - } - } - - #[test] - fn a_build_repository_is_on_a_named_registry_without_a_tag() { - let repository = - BuildRepository::try_from("build.example.ts.net:5000/piqueld".to_owned()).unwrap(); - let digest = Sha256Digest::parse(format!("sha256:{}", "a".repeat(64))).unwrap(); - assert_eq!( - repository.image(&digest).as_str(), - format!("build.example.ts.net:5000/piqueld@{digest}") - ); - assert_eq!(repository.registry(), "build.example.ts.net:5000"); - assert_eq!(repository.path(), "piqueld"); - assert_eq!( - repository.digest_of(&repository.image(&digest)), - Some(digest.clone()) - ); - // The same digest in another repository, or one this one prefixes. - for other in [ - "build.example.ts.net:5000/other", - "build.example.ts.net:5000/piqueld/sub", - ] { - let other = BuildRepository::try_from(other.to_owned()).unwrap(); - assert_eq!(repository.digest_of(&other.image(&digest)), None); - } - // Docker Hub's, a tag, and upper case. - for invalid in [ - "piqueld", - "registry.example/piqueld:v1", - "registry.example/Piqueld", - ] { - assert!( - BuildRepository::try_from(invalid.to_owned()).is_err(), - "{invalid}" - ); - } - } -} +mod tests; diff --git a/crates/piqueld-core/src/build_machine/tests.rs b/crates/piqueld-core/src/build_machine/tests.rs new file mode 100644 index 000000000..4909e1df8 --- /dev/null +++ b/crates/piqueld-core/src/build_machine/tests.rs @@ -0,0 +1,66 @@ +use super::*; + +#[test] +fn a_builder_is_a_tcp_host_and_port() { + for (endpoint, address) in [ + ( + "tcp://build.example.ts.net:1234", + "build.example.ts.net:1234", + ), + ("tcp://100.64.0.1:1234/", "100.64.0.1:1234"), + ("tcp://[fd7a::1]:1234", "[fd7a::1]:1234"), + ] { + let parsed = BuilderEndpoint::try_from(endpoint.to_owned()).unwrap(); + assert_eq!(parsed.address(), address); + } + for invalid in [ + // No port, another scheme, credentials, a path, and a bare IPv6 host. + "tcp://build.example.ts.net", + "ssh://build.example.ts.net:22", + "tcp://user@build.example:1234", + "tcp://build.example:1234/buildkit", + "tcp://fd7a::1:1234", + "tcp://:1234", + ] { + assert!( + BuilderEndpoint::try_from(invalid.to_owned()).is_err(), + "{invalid}" + ); + } +} + +#[test] +fn a_build_repository_is_on_a_named_registry_without_a_tag() { + let repository = + BuildRepository::try_from("build.example.ts.net:5000/piqueld".to_owned()).unwrap(); + let digest = Sha256Digest::parse(format!("sha256:{}", "a".repeat(64))).unwrap(); + assert_eq!( + repository.image(&digest).as_str(), + format!("build.example.ts.net:5000/piqueld@{digest}") + ); + assert_eq!(repository.registry(), "build.example.ts.net:5000"); + assert_eq!(repository.path(), "piqueld"); + assert_eq!( + repository.digest_of(&repository.image(&digest)), + Some(digest.clone()) + ); + // The same digest in another repository, or one this one prefixes. + for other in [ + "build.example.ts.net:5000/other", + "build.example.ts.net:5000/piqueld/sub", + ] { + let other = BuildRepository::try_from(other.to_owned()).unwrap(); + assert_eq!(repository.digest_of(&other.image(&digest)), None); + } + // Docker Hub's, a tag, and upper case. + for invalid in [ + "piqueld", + "registry.example/piqueld:v1", + "registry.example/Piqueld", + ] { + assert!( + BuildRepository::try_from(invalid.to_owned()).is_err(), + "{invalid}" + ); + } +} diff --git a/crates/piqueld-core/src/changes.rs b/crates/piqueld-core/src/changes/mod.rs similarity index 66% rename from crates/piqueld-core/src/changes.rs rename to crates/piqueld-core/src/changes/mod.rs index c45118fc7..c6f4d2ec0 100644 --- a/crates/piqueld-core/src/changes.rs +++ b/crates/piqueld-core/src/changes/mod.rs @@ -304,163 +304,4 @@ impl ServiceRolloutView { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn changes_show_configuration_differences_without_exposing_sensitive_values() { - let input = r#"api_version="piqueld.dev/v1alpha1" -kind="Application" -[metadata] -name="example" -[[spec.services]] -name="web" -replicas=1 -[spec.services.source] -type="image" -image="example:1" -[spec.services.environment] -TOKEN="old-secret" -"#; - let id = crate::ApplicationId::parse("app-example-01").unwrap(); - let original = crate::parse_toml(input).unwrap().normalize(id); - let mut changed = original.to_manifest(); - changed.spec.services[0].replicas = 3.into(); - changed.spec.services[0] - .environment - .insert("TOKEN".into(), "new-secret".into()); - let changed = changed.validate().unwrap().normalize(original.id().clone()); - let (original, changed) = (original.spec().to_input(), changed.spec().to_input()); - let differences = ManifestChange::between(Some(&original), &changed); - assert_eq!(differences.len(), 2); - assert!( - differences - .iter() - .any(|change| change.field == "services.web.replicas" - && change.before.as_deref() == Some("1") - && change.after.as_deref() == Some("3")) - ); - let json = serde_json::to_string(&differences).unwrap(); - assert!(!json.contains("old-secret")); - assert!(!json.contains("new-secret")); - assert!(json.contains("redacted")); - assert!(ManifestChange::between(Some(&original), &original).is_empty()); - } - - /// Edits list environment sources too, which plans leave out. - #[test] - fn edits_list_secret_declarations_and_environment_sources() { - let spec = |body: &str| { - crate::manifest::parse_template_toml(&format!( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='example'\n[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/app.git'\nbranch='main'\n[[spec.services]]\nname='web'\nsource={{type='image',image='example:1'}}\n{body}" - )) - .unwrap() - .spec() - .clone() - }; - let read = spec("[spec.environments.production]\n"); - let saved = spec( - "[[spec.secrets]]\nname='token'\n[spec.secrets.generate]\ntype='random'\nbytes=16\nencoding='hex'\n[spec.environments.production]\nbranch='release'\n", - ); - let fields = ManifestChange::edits(&read, &saved) - .into_iter() - .map(|change| change.field) - .collect::>(); - assert_eq!(fields, ["environments.production.branch", "secrets.token"]); - // Plans show a generated secret's declaration, never a value. - let planned = ManifestChange::between(Some(&read), &saved); - assert_eq!( - planned - .iter() - .map(|change| (change.field.as_str(), change.after.as_deref())) - .collect::>(), - [( - "secrets.token", - Some(r#"{"generate":{"bytes":16,"encoding":"hex","type":"random"}}"#) - )] - ); - let rollback = spec("[spec.environments.production]\nrollback='manual'\n"); - let changes = ManifestChange::edits(&read, &rollback); - assert_eq!( - changes - .iter() - .map(|change| (change.field.as_str(), change.after.as_deref())) - .collect::>(), - [("environments.production.rollback", Some("manual"))] - ); - } - - #[test] - fn changes_show_new_and_changed_jobs() { - let input = r#"api_version="piqueld.dev/v1alpha1" -kind="Application" -[metadata] -name="example" -[[spec.services]] -name="web" -[spec.services.source] -type="image" -image="example:1" -"#; - let id = crate::ApplicationId::parse("app-example-01").unwrap(); - let original = crate::parse_toml(input).unwrap().normalize(id.clone()); - let with_jobs = |jobs: &[(&str, &str)]| { - let mut manifest = original.to_manifest(); - manifest.spec.jobs = jobs - .iter() - .map(|(name, command)| crate::manifest::Job { - name: (*name).into(), - service: "web".into(), - command: vec![(*command).into()], - environment: std::collections::BTreeMap::new(), - secrets: Vec::new(), - run: crate::manifest::JobRun::BeforeRollout, - timeout_seconds: 300, - volume_access: crate::manifest::JobVolumeAccess::ReadOnly, - stop_service: false, - }) - .collect(); - manifest - .validate() - .unwrap() - .normalize(id.clone()) - .spec() - .to_input() - }; - let original = original.spec().to_input(); - let fields = |changes: Vec| { - changes - .into_iter() - .map(|change| (change.field, change.before.is_some())) - .collect::>() - }; - let migrate = [("migrate", "migrate")]; - assert_eq!( - fields(ManifestChange::between( - Some(&original), - &with_jobs(&migrate) - )), - [ - ("jobs.migrate.command".to_owned(), false), - ("jobs.migrate.run".to_owned(), false), - ("jobs.migrate.service".to_owned(), false), - ("jobs.migrate.timeout_seconds".to_owned(), false), - ("jobs.order".to_owned(), false), - ] - ); - assert_eq!( - fields(ManifestChange::between( - Some(&with_jobs(&migrate)), - &with_jobs(&[("migrate", "upgrade")]) - )), - [("jobs.migrate.command".to_owned(), true)] - ); - assert_eq!( - fields(ManifestChange::between( - Some(&with_jobs(&[("migrate", "migrate"), ("seed", "seed")])), - &with_jobs(&[("seed", "seed"), ("migrate", "migrate")]) - )), - [("jobs.order".to_owned(), true)] - ); - } -} +mod tests; diff --git a/crates/piqueld-core/src/changes/tests.rs b/crates/piqueld-core/src/changes/tests.rs new file mode 100644 index 000000000..0b487ff7f --- /dev/null +++ b/crates/piqueld-core/src/changes/tests.rs @@ -0,0 +1,158 @@ +use super::*; + +#[test] +fn changes_show_configuration_differences_without_exposing_sensitive_values() { + let input = r#"api_version="piqueld.dev/v1alpha1" +kind="Application" +[metadata] +name="example" +[[spec.services]] +name="web" +replicas=1 +[spec.services.source] +type="image" +image="example:1" +[spec.services.environment] +TOKEN="old-secret" +"#; + let id = crate::ApplicationId::parse("app-example-01").unwrap(); + let original = crate::parse_toml(input).unwrap().normalize(id); + let mut changed = original.to_manifest(); + changed.spec.services[0].replicas = 3.into(); + changed.spec.services[0] + .environment + .insert("TOKEN".into(), "new-secret".into()); + let changed = changed.validate().unwrap().normalize(original.id().clone()); + let (original, changed) = (original.spec().to_input(), changed.spec().to_input()); + let differences = ManifestChange::between(Some(&original), &changed); + assert_eq!(differences.len(), 2); + assert!( + differences + .iter() + .any(|change| change.field == "services.web.replicas" + && change.before.as_deref() == Some("1") + && change.after.as_deref() == Some("3")) + ); + let json = serde_json::to_string(&differences).unwrap(); + assert!(!json.contains("old-secret")); + assert!(!json.contains("new-secret")); + assert!(json.contains("redacted")); + assert!(ManifestChange::between(Some(&original), &original).is_empty()); +} + +/// Edits list environment sources too, which plans leave out. +#[test] +fn edits_list_secret_declarations_and_environment_sources() { + let spec = |body: &str| { + crate::manifest::parse_template_toml(&format!( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='example'\n[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/app.git'\nbranch='main'\n[[spec.services]]\nname='web'\nsource={{type='image',image='example:1'}}\n{body}" + )) + .unwrap() + .spec() + .clone() + }; + let read = spec("[spec.environments.production]\n"); + let saved = spec( + "[[spec.secrets]]\nname='token'\n[spec.secrets.generate]\ntype='random'\nbytes=16\nencoding='hex'\n[spec.environments.production]\nbranch='release'\n", + ); + let fields = ManifestChange::edits(&read, &saved) + .into_iter() + .map(|change| change.field) + .collect::>(); + assert_eq!(fields, ["environments.production.branch", "secrets.token"]); + // Plans show a generated secret's declaration, never a value. + let planned = ManifestChange::between(Some(&read), &saved); + assert_eq!( + planned + .iter() + .map(|change| (change.field.as_str(), change.after.as_deref())) + .collect::>(), + [( + "secrets.token", + Some(r#"{"generate":{"bytes":16,"encoding":"hex","type":"random"}}"#) + )] + ); + let rollback = spec("[spec.environments.production]\nrollback='manual'\n"); + let changes = ManifestChange::edits(&read, &rollback); + assert_eq!( + changes + .iter() + .map(|change| (change.field.as_str(), change.after.as_deref())) + .collect::>(), + [("environments.production.rollback", Some("manual"))] + ); +} + +#[test] +fn changes_show_new_and_changed_jobs() { + let input = r#"api_version="piqueld.dev/v1alpha1" +kind="Application" +[metadata] +name="example" +[[spec.services]] +name="web" +[spec.services.source] +type="image" +image="example:1" +"#; + let id = crate::ApplicationId::parse("app-example-01").unwrap(); + let original = crate::parse_toml(input).unwrap().normalize(id.clone()); + let with_jobs = |jobs: &[(&str, &str)]| { + let mut manifest = original.to_manifest(); + manifest.spec.jobs = jobs + .iter() + .map(|(name, command)| crate::manifest::Job { + name: (*name).into(), + service: "web".into(), + command: vec![(*command).into()], + environment: std::collections::BTreeMap::new(), + secrets: Vec::new(), + run: crate::manifest::JobRun::BeforeRollout, + timeout_seconds: 300, + volume_access: crate::manifest::JobVolumeAccess::ReadOnly, + stop_service: false, + }) + .collect(); + manifest + .validate() + .unwrap() + .normalize(id.clone()) + .spec() + .to_input() + }; + let original = original.spec().to_input(); + let fields = |changes: Vec| { + changes + .into_iter() + .map(|change| (change.field, change.before.is_some())) + .collect::>() + }; + let migrate = [("migrate", "migrate")]; + assert_eq!( + fields(ManifestChange::between( + Some(&original), + &with_jobs(&migrate) + )), + [ + ("jobs.migrate.command".to_owned(), false), + ("jobs.migrate.run".to_owned(), false), + ("jobs.migrate.service".to_owned(), false), + ("jobs.migrate.timeout_seconds".to_owned(), false), + ("jobs.order".to_owned(), false), + ] + ); + assert_eq!( + fields(ManifestChange::between( + Some(&with_jobs(&migrate)), + &with_jobs(&[("migrate", "upgrade")]) + )), + [("jobs.migrate.command".to_owned(), true)] + ); + assert_eq!( + fields(ManifestChange::between( + Some(&with_jobs(&[("migrate", "migrate"), ("seed", "seed")])), + &with_jobs(&[("seed", "seed"), ("migrate", "migrate")]) + )), + [("jobs.order".to_owned(), true)] + ); +} diff --git a/crates/piqueld-core/src/links.rs b/crates/piqueld-core/src/links/mod.rs similarity index 56% rename from crates/piqueld-core/src/links.rs rename to crates/piqueld-core/src/links/mod.rs index 6f72a9213..412cbb44f 100644 --- a/crates/piqueld-core/src/links.rs +++ b/crates/piqueld-core/src/links/mod.rs @@ -285,214 +285,4 @@ pub fn report(environment: &EnvironmentId, parties: &[LinkParty], readable: &Sco } #[cfg(test)] -mod tests { - use super::*; - use crate::EnvironmentName; - - fn party(id: &str, application: &str, name: &str) -> LinkParty { - LinkParty { - environment: EnvironmentId::parse(format!("{id}-0000000")).unwrap(), - application_id: ApplicationId::parse(format!("app-{application}")).unwrap(), - application: ApplicationName::parse(application).unwrap(), - name: name.into(), - preview: false, - exports: Vec::new(), - imports: Vec::new(), - bindings: Bindings::new(), - } - } - - /// Binds every party's names as deploying each now would. - fn deployed(mut parties: Vec) -> Vec { - let applications = parties - .iter() - .map(|party| (party.application.clone(), party.application_id.clone())) - .collect::(); - for party in &mut parties { - party.bindings = bind( - &party.exports, - &party.imports, - &party.bindings, - &applications, - ); - } - parties - } - - fn export(service: &str, applications: &[&str], previews: bool) -> ValidatedExport { - ValidatedExport { - service: ServiceName::parse(service).unwrap(), - applications: applications - .iter() - .map(|application| ApplicationName::parse(*application).unwrap()) - .collect(), - previews, - } - } - - fn import(application: &str, service: &str, environment: Option<&str>) -> ValidatedImport { - ValidatedImport { - application: ApplicationName::parse(application).unwrap(), - service: ServiceName::parse(service).unwrap(), - environment: environment.map(|name| EnvironmentName::parse(name).unwrap()), - } - } - - #[test] - fn imports_connect_to_the_same_named_environment_that_exports_to_them() { - let mut auth_staging = party("a", "auth", "staging"); - auth_staging.exports = vec![export("api", &["notes"], false)]; - let mut auth_production = party("b", "auth", "production"); - auth_production.exports = vec![export("api", &["notes"], false)]; - let mut notes = party("c", "notes", "staging"); - notes.imports = vec![import("auth", "api", None)]; - let mut other = party("d", "other", "staging"); - other.imports = vec![import("auth", "api", None)]; - let parties = deployed(vec![auth_staging, auth_production, notes, other]); - - let links = links(&parties); - assert_eq!(links.len(), 1); - assert_eq!(links[0].importer, parties[2].environment); - assert_eq!(links[0].exporter, parties[0].environment); - assert_eq!(links[0].exporter_application.as_str(), "auth"); - - let report = report(&parties[3].environment, &parties, &Scope::All); - assert_eq!(report.imports[0].state, ImportState::Unavailable); - assert_eq!(report.imports[0].alias, "api.auth"); - let report = super::report(&parties[0].environment, &parties, &Scope::All); - assert_eq!(report.importers.len(), 1); - assert_eq!(report.importers[0].application.as_str(), "notes"); - // Readers who cannot see notes do not learn it imports anything. - let hidden = Scope::one(parties[0].application_id.clone()); - let report = super::report(&parties[0].environment, &parties, &hidden); - assert_eq!(report.importers, Vec::new()); - } - - #[test] - fn imports_name_another_environment_and_previews_need_the_exporters_consent() { - let mut auth = party("a", "auth", "staging"); - auth.exports = vec![export("api", &["notes"], false)]; - let mut preview = party("b", "notes", "notes-feat-1a2b3c"); - preview.preview = true; - preview.imports = vec![import("auth", "api", Some("staging"))]; - let mut missing = party("c", "notes", "production"); - missing.imports = vec![import("auth", "api", None)]; - let mut parties = deployed(vec![auth, preview, missing]); - - assert_eq!(links(&parties), Vec::new()); - // Not exporting to previews and not existing look the same. - for party in &parties[1..] { - assert_eq!( - report(&party.environment, &parties, &Scope::All).imports[0].state, - ImportState::Unavailable - ); - } - - parties[0].exports[0].previews = true; - let links = links(&parties); - assert_eq!(links.len(), 1); - assert_eq!(links[0].importer, parties[1].environment); - } - - #[test] - fn links_group_the_services_one_environment_imports_from_another() { - let mut auth = party("a", "auth", "staging"); - auth.exports = vec![ - export("api", &["notes"], false), - export("events", &["notes"], false), - export("admin", &["other"], false), - ]; - let mut notes = party("b", "notes", "staging"); - notes.imports = vec![ - import("auth", "api", None), - import("auth", "events", None), - import("auth", "admin", None), - ]; - let links = links(&deployed(vec![auth, notes])); - assert_eq!(links.len(), 1); - assert_eq!( - links[0] - .services - .iter() - .map(ServiceName::as_str) - .collect::>(), - ["api", "events"] - ); - } - - #[test] - fn grants_follow_the_application_bound_when_deployed_not_its_name() { - let mut auth = party("a", "auth", "staging"); - auth.exports = vec![export("api", &["notes"], false)]; - let mut notes = party("b", "notes", "staging"); - notes.imports = vec![import("auth", "api", None)]; - let mut parties = deployed(vec![auth, notes]); - assert_eq!(links(&parties).len(), 1); - - // notes is renamed, and another application takes its name: notes - // keeps its link, the newcomer gets none, even after auth redeploys. - parties[1].application = ApplicationName::parse("journal").unwrap(); - let mut impostor = party("c", "notes", "staging"); - impostor.application_id = ApplicationId::parse("app-impostor").unwrap(); - impostor.imports = vec![import("auth", "api", None)]; - parties.push(impostor); - let parties = deployed(parties); - let links = links(&parties); - assert_eq!(links.len(), 1); - assert_eq!(links[0].importer, parties[1].environment); - assert_eq!( - report(&parties[2].environment, &parties, &Scope::All).imports[0].state, - ImportState::Unavailable - ); - - // Renaming auth keeps notes' link, which reports auth's new name. - let mut parties = parties; - parties[0].application = ApplicationName::parse("identity").unwrap(); - let report = report(&parties[1].environment, &parties, &Scope::All); - assert_eq!(report.imports[0].state, ImportState::Connected); - assert_eq!(report.imports[0].alias, "api.identity"); - } - - #[test] - fn unbound_names_match_the_application_holding_them() { - let mut auth = party("a", "auth", "staging"); - auth.exports = vec![export("api", &["notes"], false)]; - // auth deploys before notes exists, so its grant stays unbound. - let auth = deployed(vec![auth]).remove(0); - assert_eq!(auth.bindings, Bindings::new()); - let mut notes = party("b", "notes", "staging"); - notes.imports = vec![import("auth", "api", None)]; - let notes = deployed(vec![auth.clone(), notes]).remove(1); - assert_eq!(links(&[auth, notes]).len(), 1); - } - - #[test] - fn exporters_link_to_at_most_the_oldest_importers() { - let mut auth = party("auth", "auth", "staging"); - auth.exports = vec![export("api", &["notes"], false)]; - let mut parties = vec![auth]; - for index in 0..=MAX_IMPORTERS { - let mut notes = party(&format!("notes{index}"), "notes", "staging"); - notes.imports = vec![import("auth", "api", None)]; - parties.push(notes); - } - let parties = deployed(parties); - let links = links(&parties); - assert_eq!(links.len(), MAX_IMPORTERS); - assert!( - links - .iter() - .all(|link| link.importer != parties[MAX_IMPORTERS + 1].environment) - ); - assert_eq!( - report( - &parties[MAX_IMPORTERS + 1].environment, - &parties, - &Scope::All - ) - .imports[0] - .state, - ImportState::Full - ); - } -} +mod tests; diff --git a/crates/piqueld-core/src/links/tests.rs b/crates/piqueld-core/src/links/tests.rs new file mode 100644 index 000000000..252184fba --- /dev/null +++ b/crates/piqueld-core/src/links/tests.rs @@ -0,0 +1,209 @@ +use super::*; +use crate::EnvironmentName; + +fn party(id: &str, application: &str, name: &str) -> LinkParty { + LinkParty { + environment: EnvironmentId::parse(format!("{id}-0000000")).unwrap(), + application_id: ApplicationId::parse(format!("app-{application}")).unwrap(), + application: ApplicationName::parse(application).unwrap(), + name: name.into(), + preview: false, + exports: Vec::new(), + imports: Vec::new(), + bindings: Bindings::new(), + } +} + +/// Binds every party's names as deploying each now would. +fn deployed(mut parties: Vec) -> Vec { + let applications = parties + .iter() + .map(|party| (party.application.clone(), party.application_id.clone())) + .collect::(); + for party in &mut parties { + party.bindings = bind( + &party.exports, + &party.imports, + &party.bindings, + &applications, + ); + } + parties +} + +fn export(service: &str, applications: &[&str], previews: bool) -> ValidatedExport { + ValidatedExport { + service: ServiceName::parse(service).unwrap(), + applications: applications + .iter() + .map(|application| ApplicationName::parse(*application).unwrap()) + .collect(), + previews, + } +} + +fn import(application: &str, service: &str, environment: Option<&str>) -> ValidatedImport { + ValidatedImport { + application: ApplicationName::parse(application).unwrap(), + service: ServiceName::parse(service).unwrap(), + environment: environment.map(|name| EnvironmentName::parse(name).unwrap()), + } +} + +#[test] +fn imports_connect_to_the_same_named_environment_that_exports_to_them() { + let mut auth_staging = party("a", "auth", "staging"); + auth_staging.exports = vec![export("api", &["notes"], false)]; + let mut auth_production = party("b", "auth", "production"); + auth_production.exports = vec![export("api", &["notes"], false)]; + let mut notes = party("c", "notes", "staging"); + notes.imports = vec![import("auth", "api", None)]; + let mut other = party("d", "other", "staging"); + other.imports = vec![import("auth", "api", None)]; + let parties = deployed(vec![auth_staging, auth_production, notes, other]); + + let links = links(&parties); + assert_eq!(links.len(), 1); + assert_eq!(links[0].importer, parties[2].environment); + assert_eq!(links[0].exporter, parties[0].environment); + assert_eq!(links[0].exporter_application.as_str(), "auth"); + + let report = report(&parties[3].environment, &parties, &Scope::All); + assert_eq!(report.imports[0].state, ImportState::Unavailable); + assert_eq!(report.imports[0].alias, "api.auth"); + let report = super::report(&parties[0].environment, &parties, &Scope::All); + assert_eq!(report.importers.len(), 1); + assert_eq!(report.importers[0].application.as_str(), "notes"); + // Readers who cannot see notes do not learn it imports anything. + let hidden = Scope::one(parties[0].application_id.clone()); + let report = super::report(&parties[0].environment, &parties, &hidden); + assert_eq!(report.importers, Vec::new()); +} + +#[test] +fn imports_name_another_environment_and_previews_need_the_exporters_consent() { + let mut auth = party("a", "auth", "staging"); + auth.exports = vec![export("api", &["notes"], false)]; + let mut preview = party("b", "notes", "notes-feat-1a2b3c"); + preview.preview = true; + preview.imports = vec![import("auth", "api", Some("staging"))]; + let mut missing = party("c", "notes", "production"); + missing.imports = vec![import("auth", "api", None)]; + let mut parties = deployed(vec![auth, preview, missing]); + + assert_eq!(links(&parties), Vec::new()); + // Not exporting to previews and not existing look the same. + for party in &parties[1..] { + assert_eq!( + report(&party.environment, &parties, &Scope::All).imports[0].state, + ImportState::Unavailable + ); + } + + parties[0].exports[0].previews = true; + let links = links(&parties); + assert_eq!(links.len(), 1); + assert_eq!(links[0].importer, parties[1].environment); +} + +#[test] +fn links_group_the_services_one_environment_imports_from_another() { + let mut auth = party("a", "auth", "staging"); + auth.exports = vec![ + export("api", &["notes"], false), + export("events", &["notes"], false), + export("admin", &["other"], false), + ]; + let mut notes = party("b", "notes", "staging"); + notes.imports = vec![ + import("auth", "api", None), + import("auth", "events", None), + import("auth", "admin", None), + ]; + let links = links(&deployed(vec![auth, notes])); + assert_eq!(links.len(), 1); + assert_eq!( + links[0] + .services + .iter() + .map(ServiceName::as_str) + .collect::>(), + ["api", "events"] + ); +} + +#[test] +fn grants_follow_the_application_bound_when_deployed_not_its_name() { + let mut auth = party("a", "auth", "staging"); + auth.exports = vec![export("api", &["notes"], false)]; + let mut notes = party("b", "notes", "staging"); + notes.imports = vec![import("auth", "api", None)]; + let mut parties = deployed(vec![auth, notes]); + assert_eq!(links(&parties).len(), 1); + + // notes is renamed, and another application takes its name: notes + // keeps its link, the newcomer gets none, even after auth redeploys. + parties[1].application = ApplicationName::parse("journal").unwrap(); + let mut impostor = party("c", "notes", "staging"); + impostor.application_id = ApplicationId::parse("app-impostor").unwrap(); + impostor.imports = vec![import("auth", "api", None)]; + parties.push(impostor); + let parties = deployed(parties); + let links = links(&parties); + assert_eq!(links.len(), 1); + assert_eq!(links[0].importer, parties[1].environment); + assert_eq!( + report(&parties[2].environment, &parties, &Scope::All).imports[0].state, + ImportState::Unavailable + ); + + // Renaming auth keeps notes' link, which reports auth's new name. + let mut parties = parties; + parties[0].application = ApplicationName::parse("identity").unwrap(); + let report = report(&parties[1].environment, &parties, &Scope::All); + assert_eq!(report.imports[0].state, ImportState::Connected); + assert_eq!(report.imports[0].alias, "api.identity"); +} + +#[test] +fn unbound_names_match_the_application_holding_them() { + let mut auth = party("a", "auth", "staging"); + auth.exports = vec![export("api", &["notes"], false)]; + // auth deploys before notes exists, so its grant stays unbound. + let auth = deployed(vec![auth]).remove(0); + assert_eq!(auth.bindings, Bindings::new()); + let mut notes = party("b", "notes", "staging"); + notes.imports = vec![import("auth", "api", None)]; + let notes = deployed(vec![auth.clone(), notes]).remove(1); + assert_eq!(links(&[auth, notes]).len(), 1); +} + +#[test] +fn exporters_link_to_at_most_the_oldest_importers() { + let mut auth = party("auth", "auth", "staging"); + auth.exports = vec![export("api", &["notes"], false)]; + let mut parties = vec![auth]; + for index in 0..=MAX_IMPORTERS { + let mut notes = party(&format!("notes{index}"), "notes", "staging"); + notes.imports = vec![import("auth", "api", None)]; + parties.push(notes); + } + let parties = deployed(parties); + let links = links(&parties); + assert_eq!(links.len(), MAX_IMPORTERS); + assert!( + links + .iter() + .all(|link| link.importer != parties[MAX_IMPORTERS + 1].environment) + ); + assert_eq!( + report( + &parties[MAX_IMPORTERS + 1].environment, + &parties, + &Scope::All + ) + .imports[0] + .state, + ImportState::Full + ); +} diff --git a/crates/piqueld-core/src/manifest/declaration.rs b/crates/piqueld-core/src/manifest/declaration/mod.rs similarity index 63% rename from crates/piqueld-core/src/manifest/declaration.rs rename to crates/piqueld-core/src/manifest/declaration/mod.rs index d681f133a..dfd855ee6 100644 --- a/crates/piqueld-core/src/manifest/declaration.rs +++ b/crates/piqueld-core/src/manifest/declaration/mod.rs @@ -499,332 +499,4 @@ impl std::fmt::Display for EnvironmentChange { } #[cfg(test)] -mod tests { - use super::*; - use crate::manifest::parse_template_toml; - use crate::{ApplicationId, EnvironmentId, PromotedFrom}; - - const CONNECTION: &str = "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'\n"; - - fn spec(body: &str) -> Result { - parse_template_toml(&format!( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n{body}" - )) - .map(|template| { - template - .normalize(ApplicationId::parse("app-notes").unwrap()) - .spec() - .clone() - }) - } - - fn codes(body: &str) -> Vec<(String, String)> { - spec(body) - .unwrap_err() - .0 - .into_iter() - .map(|error| (error.path, error.code)) - .collect() - } - - fn name(name: &str) -> EnvironmentName { - EnvironmentName::parse(name).unwrap() - } - - fn branch(branch: &str, commit: Option<&str>) -> DeclaredSource { - DeclaredSource::Branch(TrackedBranch::new(branch.into(), commit.map(Into::into)).unwrap()) - } - - fn environment(id: &str, source: EnvironmentSource, sync: bool) -> EnvironmentView { - EnvironmentView { - id: EnvironmentId::parse(format!("env-0000-{id}")).unwrap(), - application_id: ApplicationId::parse("app-notes").unwrap(), - name: name(id), - source, - kind: crate::EnvironmentKind::Environment, - sync, - synced: None, - telemetry: false, - run_state: crate::api::RunState::Running, - resolved_generation: None, - delete_intent: false, - created_at_ms: 0, - updated_at_ms: 0, - } - } - - #[test] - fn declarations_resolve_sources_with_promotion_sources_first() { - let spec = spec(&format!( - "{CONNECTION}[spec.environments.production]\npromote_from='staging'\n[spec.environments.staging]\nsync=true\n[spec.environments.canary]\nbranch='next'\ncommit='{}'\n", - "a".repeat(40) - )) - .unwrap(); - let declarations = spec.declared_environments().unwrap(); - assert_eq!( - declarations, - [ - Declaration { - name: name("canary"), - source: branch("next", Some(&"a".repeat(40))), - sync: false, - manages_source: true, - }, - Declaration { - name: name("staging"), - source: branch("main", None), - sync: true, - manages_source: true, - }, - Declaration { - name: name("production"), - source: DeclaredSource::Promoted { - from: name("staging") - }, - sync: false, - manages_source: true, - }, - ] - ); - // Without a repository, environments deploy the saved manifest. - let saved = self::spec("[spec.environments.staging.variables]\nx=1\n").unwrap(); - assert_eq!( - saved.declared_environments().unwrap()[0].source, - DeclaredSource::Saved - ); - } - - #[test] - fn the_staging_and_production_example_declares_both() { - let example = - parse_template_toml(include_str!("../../../../examples/staging-production.toml")) - .unwrap() - .normalize(ApplicationId::parse("app-notes").unwrap()); - assert_eq!( - example - .spec() - .declared_environments() - .unwrap() - .into_iter() - .map(|declaration| ( - declaration.name.to_string(), - declaration.source.to_string(), - declaration.sync - )) - .collect::>(), - [ - ("staging".into(), "branch main".into(), true), - ( - "production".into(), - "releases promoted from staging".into(), - false - ), - ] - ); - } - - /// Disconnecting the repository returns declared environments to the - /// saved manifest instead of failing on fields that need one. - #[test] - fn disconnecting_drops_what_needs_a_repository() { - let mut manifest = - parse_template_toml(include_str!("../../../../examples/staging-production.toml")) - .unwrap() - .normalize(ApplicationId::parse("app-notes").unwrap()) - .to_manifest(); - manifest - .spec - .environments - .get_mut("staging") - .unwrap() - .branch = Some("next".into()); - crate::edit::ApplicationEdit::Repository(None) - .apply(&mut manifest) - .unwrap(); - let sources = manifest - .validate_template() - .unwrap() - .spec() - .declared_environments() - .unwrap() - .into_iter() - .map(|declaration| (declaration.source.to_string(), declaration.sync)) - .collect::>(); - assert_eq!( - sources, - [ - ("the saved manifest".into(), false), - ("releases promoted from staging".into(), false), - ] - ); - } - - /// Blocks that set no source, as every block did before blocks declared - /// sources, leave existing environments' sources and sync alone; one that - /// removes the source it set returns its environment to the default. - #[test] - fn only_declared_sources_change_existing_environments() { - let staging = environment( - "staging", - EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()), - true, - ); - let production = environment( - "production", - EnvironmentSource::Promoted(PromotedFrom { - environment: staging.id.clone(), - }), - false, - ); - let environments = [production, staging]; - let legacy = spec(&format!( - "{CONNECTION}[spec.environments.staging.variables]\nx=1\n[spec.environments.production]\nvisibility='private'\n" - )) - .unwrap(); - let declarations = legacy.declared_environments().unwrap(); - assert_eq!(EnvironmentChange::between(&declarations, &environments), []); - - let declared = spec(&format!( - "{CONNECTION}[spec.environments.staging]\nsync=true\n[spec.environments.production]\npromote_from='staging'\n" - )) - .unwrap(); - let removed = legacy.declared_environments_since(Some(&declared)).unwrap(); - assert_eq!( - EnvironmentChange::between(&removed, &environments) - .iter() - .map(ToString::to_string) - .collect::>(), - [ - "production: deploys from branch main instead of releases promoted from staging", - "staging: no longer follows pushes", - ] - ); - } - - #[test] - fn impossible_sources_fail_at_their_field() { - let field = |path: &str, code: ApiErrorCode| (path.to_owned(), code.into()); - assert_eq!( - codes("[spec.environments.staging]\nbranch='main'\nsync=true\n"), - [ - field( - "spec.environments.staging.branch", - ApiErrorCode::ManifestRepositoryRequired - ), - field( - "spec.environments.staging.sync", - ApiErrorCode::ManifestRepositoryRequired - ), - ] - ); - assert_eq!( - codes(&format!( - "{CONNECTION}[spec.environments.production]\npromote_from='staging'\nsync=true\n[spec.environments.staging]\n" - )), - [field( - "spec.environments.production.promote_from", - ApiErrorCode::EnvironmentSourceConflict - )] - ); - assert_eq!( - codes(&format!( - "{CONNECTION}[spec.environments.staging]\ncommit='{}'\nsync=true\n", - "a".repeat(40) - )), - [field( - "spec.environments.staging.sync", - ApiErrorCode::EnvironmentSyncPinned - )] - ); - assert_eq!( - codes(&format!( - "{CONNECTION}[spec.environments.staging]\nbranch='a..b'\n" - )), - [field( - "spec.environments.staging.branch", - ApiErrorCode::GitBranchInvalid - )] - ); - assert_eq!( - codes("[spec.environments.production]\npromote_from='qa'\n"), - [field( - "spec.environments.production.promote_from", - ApiErrorCode::PromotionSourceInvalid - )] - ); - assert_eq!( - codes( - "[spec.environments.a]\npromote_from='b'\n[spec.environments.b]\npromote_from='c'\n[spec.environments.c]\npromote_from='a'\n" - ), - [field( - "spec.environments.c.promote_from", - ApiErrorCode::PromotionCycle - )] - ); - assert_eq!( - codes("[spec.environments.a]\npromote_from='a'\n"), - [field( - "spec.environments.a.promote_from", - ApiErrorCode::PromotionCycle - )] - ); - } - - #[test] - fn changes_create_resource_and_report_what_the_manifest_dropped() { - let staging = environment("staging", EnvironmentSource::Saved, false); - let production = environment( - "production", - EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()), - false, - ); - let old = environment( - "old", - EnvironmentSource::Promoted(PromotedFrom { - environment: staging.id.clone(), - }), - false, - ); - let declarations = [ - Declaration { - name: name("staging"), - source: branch("main", None), - sync: true, - manages_source: true, - }, - Declaration { - name: name("production"), - source: DeclaredSource::Promoted { - from: name("staging"), - }, - sync: false, - manages_source: true, - }, - Declaration { - name: name("qa"), - source: branch("main", None), - sync: false, - manages_source: true, - }, - ]; - let changes = EnvironmentChange::between( - &declarations, - &[old.clone(), production.clone(), staging.clone()], - ); - assert_eq!( - changes.iter().map(ToString::to_string).collect::>(), - [ - "staging: deploys from branch main instead of the saved manifest", - "staging: follows pushes", - "production: deploys from releases promoted from staging instead of branch main", - "qa: created, deploys from branch main", - "old: no longer declared; kept until deleted with `piquelctl env delete`", - ] - ); - // Nothing is managed without declarations. - assert_eq!( - EnvironmentChange::between(&[], &[old, production, staging]), - [] - ); - } -} +mod tests; diff --git a/crates/piqueld-core/src/manifest/declaration/tests.rs b/crates/piqueld-core/src/manifest/declaration/tests.rs new file mode 100644 index 000000000..8531f2a99 --- /dev/null +++ b/crates/piqueld-core/src/manifest/declaration/tests.rs @@ -0,0 +1,329 @@ +use super::*; +use crate::manifest::parse_template_toml; +use crate::{ApplicationId, EnvironmentId, PromotedFrom}; + +const CONNECTION: &str = "[spec.manifest]\npath='app.toml'\n[spec.manifest.repository]\nurl='https://example.com/notes.git'\nbranch='main'\n"; + +fn spec(body: &str) -> Result { + parse_template_toml(&format!( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n{body}" + )) + .map(|template| { + template + .normalize(ApplicationId::parse("app-notes").unwrap()) + .spec() + .clone() + }) +} + +fn codes(body: &str) -> Vec<(String, String)> { + spec(body) + .unwrap_err() + .0 + .into_iter() + .map(|error| (error.path, error.code)) + .collect() +} + +fn name(name: &str) -> EnvironmentName { + EnvironmentName::parse(name).unwrap() +} + +fn branch(branch: &str, commit: Option<&str>) -> DeclaredSource { + DeclaredSource::Branch(TrackedBranch::new(branch.into(), commit.map(Into::into)).unwrap()) +} + +fn environment(id: &str, source: EnvironmentSource, sync: bool) -> EnvironmentView { + EnvironmentView { + id: EnvironmentId::parse(format!("env-0000-{id}")).unwrap(), + application_id: ApplicationId::parse("app-notes").unwrap(), + name: name(id), + source, + kind: crate::EnvironmentKind::Environment, + sync, + synced: None, + telemetry: false, + run_state: crate::api::RunState::Running, + resolved_generation: None, + delete_intent: false, + created_at_ms: 0, + updated_at_ms: 0, + } +} + +#[test] +fn declarations_resolve_sources_with_promotion_sources_first() { + let spec = spec(&format!( + "{CONNECTION}[spec.environments.production]\npromote_from='staging'\n[spec.environments.staging]\nsync=true\n[spec.environments.canary]\nbranch='next'\ncommit='{}'\n", + "a".repeat(40) + )) + .unwrap(); + let declarations = spec.declared_environments().unwrap(); + assert_eq!( + declarations, + [ + Declaration { + name: name("canary"), + source: branch("next", Some(&"a".repeat(40))), + sync: false, + manages_source: true, + }, + Declaration { + name: name("staging"), + source: branch("main", None), + sync: true, + manages_source: true, + }, + Declaration { + name: name("production"), + source: DeclaredSource::Promoted { + from: name("staging") + }, + sync: false, + manages_source: true, + }, + ] + ); + // Without a repository, environments deploy the saved manifest. + let saved = self::spec("[spec.environments.staging.variables]\nx=1\n").unwrap(); + assert_eq!( + saved.declared_environments().unwrap()[0].source, + DeclaredSource::Saved + ); +} + +#[test] +fn the_staging_and_production_example_declares_both() { + let example = parse_template_toml(include_str!( + "../../../../../examples/staging-production.toml" + )) + .unwrap() + .normalize(ApplicationId::parse("app-notes").unwrap()); + assert_eq!( + example + .spec() + .declared_environments() + .unwrap() + .into_iter() + .map(|declaration| ( + declaration.name.to_string(), + declaration.source.to_string(), + declaration.sync + )) + .collect::>(), + [ + ("staging".into(), "branch main".into(), true), + ( + "production".into(), + "releases promoted from staging".into(), + false + ), + ] + ); +} + +/// Disconnecting the repository returns declared environments to the +/// saved manifest instead of failing on fields that need one. +#[test] +fn disconnecting_drops_what_needs_a_repository() { + let mut manifest = parse_template_toml(include_str!( + "../../../../../examples/staging-production.toml" + )) + .unwrap() + .normalize(ApplicationId::parse("app-notes").unwrap()) + .to_manifest(); + manifest + .spec + .environments + .get_mut("staging") + .unwrap() + .branch = Some("next".into()); + crate::edit::ApplicationEdit::Repository(None) + .apply(&mut manifest) + .unwrap(); + let sources = manifest + .validate_template() + .unwrap() + .spec() + .declared_environments() + .unwrap() + .into_iter() + .map(|declaration| (declaration.source.to_string(), declaration.sync)) + .collect::>(); + assert_eq!( + sources, + [ + ("the saved manifest".into(), false), + ("releases promoted from staging".into(), false), + ] + ); +} + +/// Blocks that set no source, as every block did before blocks declared +/// sources, leave existing environments' sources and sync alone; one that +/// removes the source it set returns its environment to the default. +#[test] +fn only_declared_sources_change_existing_environments() { + let staging = environment( + "staging", + EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()), + true, + ); + let production = environment( + "production", + EnvironmentSource::Promoted(PromotedFrom { + environment: staging.id.clone(), + }), + false, + ); + let environments = [production, staging]; + let legacy = spec(&format!( + "{CONNECTION}[spec.environments.staging.variables]\nx=1\n[spec.environments.production]\nvisibility='private'\n" + )) + .unwrap(); + let declarations = legacy.declared_environments().unwrap(); + assert_eq!(EnvironmentChange::between(&declarations, &environments), []); + + let declared = spec(&format!( + "{CONNECTION}[spec.environments.staging]\nsync=true\n[spec.environments.production]\npromote_from='staging'\n" + )) + .unwrap(); + let removed = legacy.declared_environments_since(Some(&declared)).unwrap(); + assert_eq!( + EnvironmentChange::between(&removed, &environments) + .iter() + .map(ToString::to_string) + .collect::>(), + [ + "production: deploys from branch main instead of releases promoted from staging", + "staging: no longer follows pushes", + ] + ); +} + +#[test] +fn impossible_sources_fail_at_their_field() { + let field = |path: &str, code: ApiErrorCode| (path.to_owned(), code.into()); + assert_eq!( + codes("[spec.environments.staging]\nbranch='main'\nsync=true\n"), + [ + field( + "spec.environments.staging.branch", + ApiErrorCode::ManifestRepositoryRequired + ), + field( + "spec.environments.staging.sync", + ApiErrorCode::ManifestRepositoryRequired + ), + ] + ); + assert_eq!( + codes(&format!( + "{CONNECTION}[spec.environments.production]\npromote_from='staging'\nsync=true\n[spec.environments.staging]\n" + )), + [field( + "spec.environments.production.promote_from", + ApiErrorCode::EnvironmentSourceConflict + )] + ); + assert_eq!( + codes(&format!( + "{CONNECTION}[spec.environments.staging]\ncommit='{}'\nsync=true\n", + "a".repeat(40) + )), + [field( + "spec.environments.staging.sync", + ApiErrorCode::EnvironmentSyncPinned + )] + ); + assert_eq!( + codes(&format!( + "{CONNECTION}[spec.environments.staging]\nbranch='a..b'\n" + )), + [field( + "spec.environments.staging.branch", + ApiErrorCode::GitBranchInvalid + )] + ); + assert_eq!( + codes("[spec.environments.production]\npromote_from='qa'\n"), + [field( + "spec.environments.production.promote_from", + ApiErrorCode::PromotionSourceInvalid + )] + ); + assert_eq!( + codes( + "[spec.environments.a]\npromote_from='b'\n[spec.environments.b]\npromote_from='c'\n[spec.environments.c]\npromote_from='a'\n" + ), + [field( + "spec.environments.c.promote_from", + ApiErrorCode::PromotionCycle + )] + ); + assert_eq!( + codes("[spec.environments.a]\npromote_from='a'\n"), + [field( + "spec.environments.a.promote_from", + ApiErrorCode::PromotionCycle + )] + ); +} + +#[test] +fn changes_create_resource_and_report_what_the_manifest_dropped() { + let staging = environment("staging", EnvironmentSource::Saved, false); + let production = environment( + "production", + EnvironmentSource::Branch(TrackedBranch::new("main".into(), None).unwrap()), + false, + ); + let old = environment( + "old", + EnvironmentSource::Promoted(PromotedFrom { + environment: staging.id.clone(), + }), + false, + ); + let declarations = [ + Declaration { + name: name("staging"), + source: branch("main", None), + sync: true, + manages_source: true, + }, + Declaration { + name: name("production"), + source: DeclaredSource::Promoted { + from: name("staging"), + }, + sync: false, + manages_source: true, + }, + Declaration { + name: name("qa"), + source: branch("main", None), + sync: false, + manages_source: true, + }, + ]; + let changes = EnvironmentChange::between( + &declarations, + &[old.clone(), production.clone(), staging.clone()], + ); + assert_eq!( + changes.iter().map(ToString::to_string).collect::>(), + [ + "staging: deploys from branch main instead of the saved manifest", + "staging: follows pushes", + "production: deploys from releases promoted from staging instead of branch main", + "qa: created, deploys from branch main", + "old: no longer declared; kept until deleted with `piquelctl env delete`", + ] + ); + // Nothing is managed without declarations. + assert_eq!( + EnvironmentChange::between(&[], &[old, production, staging]), + [] + ); +} diff --git a/crates/piqueld-core/src/manifest/limits.rs b/crates/piqueld-core/src/manifest/limits/mod.rs similarity index 69% rename from crates/piqueld-core/src/manifest/limits.rs rename to crates/piqueld-core/src/manifest/limits/mod.rs index bbba90bb2..fde9f8797 100644 --- a/crates/piqueld-core/src/manifest/limits.rs +++ b/crates/piqueld-core/src/manifest/limits/mod.rs @@ -143,93 +143,4 @@ impl PreviewLimits { } #[cfg(test)] -mod tests { - use super::*; - use crate::{ - ApplicationId, ApplicationName, EnvironmentKind, GitBranch, Preview, PreviewSlug, - parse_toml, - }; - - /// `web` asks for 3 replicas and sets no limits; `db` sets only its CPU. - fn application() -> NormalizedApplication { - parse_toml( - r#"api_version = "piqueld.dev/v1alpha1" -kind = "Application" -[metadata] -name = "notes" -[[spec.services]] -name = "web" -replicas = 3 -[spec.services.source] -type = "image" -image = "nginx:alpine" -[[spec.services]] -name = "db" -[spec.services.source] -type = "image" -image = "postgres:17" -[spec.services.resources] -cpu_millis = 2000 -"#, - ) - .unwrap() - .normalize(ApplicationId::parse("app-notes-01").unwrap()) - } - - fn preview() -> EnvironmentKind { - let (name, branch) = ( - ApplicationName::parse("notes").unwrap(), - GitBranch::parse("feat/login").unwrap(), - ); - EnvironmentKind::Preview(Box::new(Preview { - slug: PreviewSlug::derive(&name, &branch, None), - branch, - slot: None, - })) - } - - #[test] - fn previews_get_default_limits_and_capped_replicas_with_warnings_and_environments_never() { - let limits = PreviewLimits::default(); - let mut environment = application(); - assert_eq!( - EnvironmentKind::Environment.bound(&mut environment, &limits), - [] - ); - assert_eq!(environment, application()); - - let mut bounded = application(); - let warnings = preview().bound(&mut bounded, &limits); - let services = bounded - .spec() - .services - .iter() - .map(|service| (service.name.as_str(), service.replicas, &service.resources)) - .collect::>(); - let limited = |cpu_millis| { - Some(ValidatedResourceLimits { - cpu_millis: Some(cpu_millis), - memory_bytes: Some(limits.default_memory_bytes), - }) - }; - assert_eq!( - services, - [("db", 1, &limited(2000)), ("web", 1, &limited(500))] - ); - assert_eq!( - warnings - .iter() - .map(|warning| (warning.resource.as_str(), warning.code.as_str())) - .collect::>(), - [ - ("db", ApiErrorCode::PreviewLimitsDefaulted.as_str()), - ("web", ApiErrorCode::PreviewLimitsDefaulted.as_str()), - ("web", ApiErrorCode::PreviewReplicasCapped.as_str()), - ] - ); - assert_eq!( - warnings[2].message, - "web asks for 3 replicas; previews run at most 1 ([previews] max_replicas)" - ); - } -} +mod tests; diff --git a/crates/piqueld-core/src/manifest/limits/tests.rs b/crates/piqueld-core/src/manifest/limits/tests.rs new file mode 100644 index 000000000..a53b447bc --- /dev/null +++ b/crates/piqueld-core/src/manifest/limits/tests.rs @@ -0,0 +1,87 @@ +use super::*; +use crate::{ + ApplicationId, ApplicationName, EnvironmentKind, GitBranch, Preview, PreviewSlug, parse_toml, +}; + +/// `web` asks for 3 replicas and sets no limits; `db` sets only its CPU. +fn application() -> NormalizedApplication { + parse_toml( + r#"api_version = "piqueld.dev/v1alpha1" +kind = "Application" +[metadata] +name = "notes" +[[spec.services]] +name = "web" +replicas = 3 +[spec.services.source] +type = "image" +image = "nginx:alpine" +[[spec.services]] +name = "db" +[spec.services.source] +type = "image" +image = "postgres:17" +[spec.services.resources] +cpu_millis = 2000 +"#, + ) + .unwrap() + .normalize(ApplicationId::parse("app-notes-01").unwrap()) +} + +fn preview() -> EnvironmentKind { + let (name, branch) = ( + ApplicationName::parse("notes").unwrap(), + GitBranch::parse("feat/login").unwrap(), + ); + EnvironmentKind::Preview(Box::new(Preview { + slug: PreviewSlug::derive(&name, &branch, None), + branch, + slot: None, + })) +} + +#[test] +fn previews_get_default_limits_and_capped_replicas_with_warnings_and_environments_never() { + let limits = PreviewLimits::default(); + let mut environment = application(); + assert_eq!( + EnvironmentKind::Environment.bound(&mut environment, &limits), + [] + ); + assert_eq!(environment, application()); + + let mut bounded = application(); + let warnings = preview().bound(&mut bounded, &limits); + let services = bounded + .spec() + .services + .iter() + .map(|service| (service.name.as_str(), service.replicas, &service.resources)) + .collect::>(); + let limited = |cpu_millis| { + Some(ValidatedResourceLimits { + cpu_millis: Some(cpu_millis), + memory_bytes: Some(limits.default_memory_bytes), + }) + }; + assert_eq!( + services, + [("db", 1, &limited(2000)), ("web", 1, &limited(500))] + ); + assert_eq!( + warnings + .iter() + .map(|warning| (warning.resource.as_str(), warning.code.as_str())) + .collect::>(), + [ + ("db", ApiErrorCode::PreviewLimitsDefaulted.as_str()), + ("web", ApiErrorCode::PreviewLimitsDefaulted.as_str()), + ("web", ApiErrorCode::PreviewReplicasCapped.as_str()), + ] + ); + assert_eq!( + warnings[2].message, + "web asks for 3 replicas; previews run at most 1 ([previews] max_replicas)" + ); +} diff --git a/crates/piqueld-core/src/manifest/routes.rs b/crates/piqueld-core/src/manifest/routes/mod.rs similarity index 59% rename from crates/piqueld-core/src/manifest/routes.rs rename to crates/piqueld-core/src/manifest/routes/mod.rs index 8a8af6e3b..4354f0a10 100644 --- a/crates/piqueld-core/src/manifest/routes.rs +++ b/crates/piqueld-core/src/manifest/routes/mod.rs @@ -503,317 +503,4 @@ impl ValidatedRoute { } #[cfg(test)] -mod tests { - use super::{Hostname, RouteTarget, ValidatedRoute}; - use crate::{ - ApiErrorCode, ApplicationId, EnvironmentId, InstanceId, ResolutionSet, ResolvedSource, - ServiceName, api::RouteStatus, compile_application, parse_toml, - }; - - fn manifest(routes: &str) -> String { - format!( - "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'\n{routes}" - ) - } - - #[test] - fn exact_hosts_are_canonical_and_invalid_routes_are_rejected() { - let route = "[[spec.routes]]\nhostname='NOTES.Example.COM.'\nservice='web'\nport=3000"; - let app = parse_toml(&manifest(route)) - .unwrap() - .normalize(ApplicationId::parse("test-app").unwrap()); - assert_eq!(app.spec().routes[0].hostname.as_str(), "notes.example.com"); - assert_eq!( - parse_toml(&app.export_toml().unwrap()) - .unwrap() - .normalize(app.id().clone()), - app - ); - for host in [ - "*.com", - "a.*.example.com", - "*.*.example.com", - "*example.com", - "*", - "https://example.com", - "example.com/path", - "example.com:443", - "localhost", - "127.0.0.1", - "[::1]", - "a..com", - "foo.local", - "é.example.com", - ] { - assert!( - parse_toml(&manifest(&route.replace("NOTES.Example.COM.", host))).is_err(), - "{host}" - ); - } - assert!(parse_toml(&manifest(&route.replace("port=3000", "port=0"))).is_err()); - assert!( - parse_toml(&manifest( - &route.replace("service='web'", "service='database'") - )) - .is_err() - ); - assert!(parse_toml(&manifest(&format!("{route}\n{route}"))).is_err()); - let without = parse_toml(&manifest("")) - .unwrap() - .normalize(app.id().clone()); - assert_ne!(app.spec_hash(), without.spec_hash()); - } - - #[test] - fn wildcards_match_one_label_below_their_parent() { - let route = "[[spec.routes]]\nhostname='*.Tenants.Example.COM.'\nservice='web'\nport=3000"; - let app = parse_toml(&manifest(route)) - .unwrap() - .normalize(ApplicationId::parse("test-app").unwrap()); - let hostname = &app.spec().routes[0].hostname; - assert_eq!(hostname.as_str(), "*.tenants.example.com"); - assert_eq!(hostname.domain().as_str(), "tenants.example.com"); - let host = |name: &str| Hostname::parse(name).unwrap(); - assert!(hostname.matches(&host("alice.tenants.example.com"))); - assert!(!hostname.matches(&host("a.alice.tenants.example.com"))); - assert!(!hostname.matches(&host("tenants.example.com"))); - assert!(hostname.is_within(&host("example.com"))); - assert!(!hostname.is_within(&host("alice.tenants.example.com"))); - assert_eq!( - parse_toml(&app.export_toml().unwrap()) - .unwrap() - .normalize(app.id().clone()), - app - ); - // Wildcards are never exact hostnames. - assert!(Hostname::parse("*.example.com").is_err()); - // Probes skip names exact routes claim, and fit the longest parent. - let claimed = [host("a.tenants.example.com")]; - assert_eq!( - hostname.served(&claimed), - Some(host("b.tenants.example.com")) - ); - let longest = format!("*.{}.com", vec!["a".repeat(61); 4].join(".")); - assert_eq!(longest.len(), 253); - assert!( - super::RouteHostname::parse(longest) - .unwrap() - .served(&[]) - .is_some() - ); - - // A wildcard redirect loops when it reaches a name only it serves. - let redirect = |to: &str, exact: &str| { - parse_toml(&manifest(&format!( - "[[spec.routes]]\nhostname='*.example.com'\nredirect={{to='{to}'}}\n{exact}" - ))) - }; - let www = "[[spec.routes]]\nhostname='www.example.com'\nservice='web'\nport=3000"; - assert!(redirect("https://www.example.com", www).is_ok()); - assert!(redirect("https://example.com", "").is_ok()); - let errors = redirect("https://www.example.com", "").unwrap_err(); - assert!( - errors - .0 - .iter() - .any(|e| e.code == ApiErrorCode::RouteRedirectLoop), - "{errors:?}" - ); - } - - #[test] - fn redirects_are_validated_and_keep_the_flat_wire_shape() { - let redirect = |fields: &str| { - parse_toml(&manifest(&format!( - "[[spec.routes]]\nhostname='www.example.com'\n{fields}" - ))) - }; - let app = redirect("redirect={to='https://example.com/'}") - .unwrap() - .normalize(ApplicationId::parse("test-app").unwrap()); - let route = &app.spec().routes[0]; - assert_eq!( - serde_json::to_value(route).unwrap(), - serde_json::json!({"hostname":"www.example.com","visibility":"private","redirect":{"to":"https://example.com/","status":308,"preserve_path":true}}) - ); - let RouteTarget::Redirect { redirect: target } = &route.target else { - panic!("redirect route") - }; - assert_eq!(target.location(), "https://example.com{http.request.uri}"); - assert_eq!( - parse_toml(&app.export_toml().unwrap()) - .unwrap() - .normalize(app.id().clone()), - app - ); - let fixed = - redirect("redirect={to='http://example.com:8080/a',status=302,preserve_path=false}") - .unwrap() - .normalize(app.id().clone()); - let RouteTarget::Redirect { redirect: fixed } = &fixed.spec().routes[0].target else { - panic!("redirect route") - }; - assert_eq!(fixed.location(), "http://example.com:8080/a"); - - for (fields, code) in [ - ( - "service='web'\nport=80\nredirect={to='https://example.com'}", - ApiErrorCode::RouteTargetInvalid, - ), - ("", ApiErrorCode::RouteTargetInvalid), - ("service='web'", ApiErrorCode::RouteTargetInvalid), - ( - "redirect={to='https://example.com',status=200}", - ApiErrorCode::RouteRedirectStatusInvalid, - ), - ( - "redirect={to='https://www.example.com/'}", - ApiErrorCode::RouteRedirectLoop, - ), - ( - "redirect={to='ftp://example.com'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ( - "redirect={to='https://example.com/?q=1'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ( - "redirect={to='https://example.com/{http.request.host}'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ( - "redirect={to='https://user@example.com'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ( - "redirect={to='https://example.com:0'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ( - "redirect={to='https://Example.com'}", - ApiErrorCode::RouteRedirectInvalid, - ), - ] { - let errors = redirect(fields).unwrap_err(); - assert!( - errors.0.iter().any(|e| e.code == code), - "{fields}: {errors:?}" - ); - } - } - - #[test] - fn decoding_keeps_stored_routes_and_rejects_mixed_targets() { - // Stored proxy routes predate redirects and must still decode. - let stored: ValidatedRoute = serde_json::from_value( - serde_json::json!({"hostname":"a.example.com","service":"web","port":80}), - ) - .unwrap(); - assert_eq!(stored.target.to_string(), "web:80"); - let redirect_json = - serde_json::json!({"to":"https://example.com/","status":308,"preserve_path":true}); - for target in [ - serde_json::json!({"service":"web","port":80,"redirect":redirect_json}), - serde_json::json!({"service":"web"}), - serde_json::json!({}), - ] { - let mut route = serde_json::json!({"hostname":"a.example.com"}); - route - .as_object_mut() - .unwrap() - .extend(target.as_object().unwrap().clone()); - assert!( - serde_json::from_value::(route.clone()).is_err(), - "{route}" - ); - route["environment_id"] = "test-app".into(); - route["visibility"] = "private".into(); - route["dns"] = serde_json::json!({"type":"server_addresses"}); - route["state"] = "ready".into(); - route["message"] = "".into(); - assert!( - serde_json::from_value::(route.clone()).is_err(), - "{route}" - ); - } - } - - #[test] - fn redirect_only_applications_have_no_ingress_network() { - let app = parse_toml("api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='old'\n[[spec.routes]]\nhostname='old.example.com'\nredirect={to='https://new.example.com'}") - .unwrap() - .normalize(ApplicationId::parse("test-app").unwrap()); - let target = compile_application( - &app, - &EnvironmentId::parse("test-app").unwrap(), - InstanceId::parse("test-instance").unwrap(), - &ResolutionSet::default(), - ) - .unwrap() - .with_ingress(true); - assert_eq!(target.networks, []); - assert_eq!(target.routes, app.spec().routes); - } - - #[test] - fn only_exposed_services_join_ingress_and_disabling_preserves_route_intent() { - let routes = "[[spec.routes]]\nhostname='notes.example.com'\nservice='web'\nport=3000\n[[spec.services]]\nname='db'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'"; - let app = parse_toml(&manifest(routes)) - .unwrap() - .normalize(ApplicationId::parse("test-app").unwrap()); - let sources = ["web", "db"] - .into_iter() - .map(|name| { - ( - ServiceName::parse(name).unwrap(), - ResolvedSource::parse_image( - "nginx:alpine", - format!("nginx@sha256:{}", "a".repeat(64)), - ) - .unwrap(), - ) - }) - .collect(); - let target = compile_application( - &app, - &EnvironmentId::parse("test-app").unwrap(), - InstanceId::parse("test-instance").unwrap(), - &ResolutionSet { - sources, - ..ResolutionSet::default() - }, - ) - .unwrap(); - let enabled = target.clone().with_ingress(true); - assert_eq!(enabled.networks.len(), 2); - assert!( - enabled - .networks - .iter() - .all(crate::DesiredNetwork::has_valid_identity) - ); - assert_eq!( - enabled - .services - .iter() - .find(|s| s.logical_name.as_str() == "web") - .unwrap() - .networks - .len(), - 2 - ); - assert_eq!( - enabled - .services - .iter() - .find(|s| s.logical_name.as_str() == "db") - .unwrap() - .networks - .len(), - 1 - ); - assert_eq!(enabled.clone().with_ingress(true), enabled); - assert_eq!(enabled.with_ingress(false), target); - } -} +mod tests; diff --git a/crates/piqueld-core/src/manifest/routes/tests.rs b/crates/piqueld-core/src/manifest/routes/tests.rs new file mode 100644 index 000000000..79df63376 --- /dev/null +++ b/crates/piqueld-core/src/manifest/routes/tests.rs @@ -0,0 +1,312 @@ +use super::{Hostname, RouteTarget, ValidatedRoute}; +use crate::{ + ApiErrorCode, ApplicationId, EnvironmentId, InstanceId, ResolutionSet, ResolvedSource, + ServiceName, api::RouteStatus, compile_application, parse_toml, +}; + +fn manifest(routes: &str) -> String { + format!( + "api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='notes'\n[[spec.services]]\nname='web'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'\n{routes}" + ) +} + +#[test] +fn exact_hosts_are_canonical_and_invalid_routes_are_rejected() { + let route = "[[spec.routes]]\nhostname='NOTES.Example.COM.'\nservice='web'\nport=3000"; + let app = parse_toml(&manifest(route)) + .unwrap() + .normalize(ApplicationId::parse("test-app").unwrap()); + assert_eq!(app.spec().routes[0].hostname.as_str(), "notes.example.com"); + assert_eq!( + parse_toml(&app.export_toml().unwrap()) + .unwrap() + .normalize(app.id().clone()), + app + ); + for host in [ + "*.com", + "a.*.example.com", + "*.*.example.com", + "*example.com", + "*", + "https://example.com", + "example.com/path", + "example.com:443", + "localhost", + "127.0.0.1", + "[::1]", + "a..com", + "foo.local", + "é.example.com", + ] { + assert!( + parse_toml(&manifest(&route.replace("NOTES.Example.COM.", host))).is_err(), + "{host}" + ); + } + assert!(parse_toml(&manifest(&route.replace("port=3000", "port=0"))).is_err()); + assert!( + parse_toml(&manifest( + &route.replace("service='web'", "service='database'") + )) + .is_err() + ); + assert!(parse_toml(&manifest(&format!("{route}\n{route}"))).is_err()); + let without = parse_toml(&manifest("")) + .unwrap() + .normalize(app.id().clone()); + assert_ne!(app.spec_hash(), without.spec_hash()); +} + +#[test] +fn wildcards_match_one_label_below_their_parent() { + let route = "[[spec.routes]]\nhostname='*.Tenants.Example.COM.'\nservice='web'\nport=3000"; + let app = parse_toml(&manifest(route)) + .unwrap() + .normalize(ApplicationId::parse("test-app").unwrap()); + let hostname = &app.spec().routes[0].hostname; + assert_eq!(hostname.as_str(), "*.tenants.example.com"); + assert_eq!(hostname.domain().as_str(), "tenants.example.com"); + let host = |name: &str| Hostname::parse(name).unwrap(); + assert!(hostname.matches(&host("alice.tenants.example.com"))); + assert!(!hostname.matches(&host("a.alice.tenants.example.com"))); + assert!(!hostname.matches(&host("tenants.example.com"))); + assert!(hostname.is_within(&host("example.com"))); + assert!(!hostname.is_within(&host("alice.tenants.example.com"))); + assert_eq!( + parse_toml(&app.export_toml().unwrap()) + .unwrap() + .normalize(app.id().clone()), + app + ); + // Wildcards are never exact hostnames. + assert!(Hostname::parse("*.example.com").is_err()); + // Probes skip names exact routes claim, and fit the longest parent. + let claimed = [host("a.tenants.example.com")]; + assert_eq!( + hostname.served(&claimed), + Some(host("b.tenants.example.com")) + ); + let longest = format!("*.{}.com", vec!["a".repeat(61); 4].join(".")); + assert_eq!(longest.len(), 253); + assert!( + super::RouteHostname::parse(longest) + .unwrap() + .served(&[]) + .is_some() + ); + + // A wildcard redirect loops when it reaches a name only it serves. + let redirect = |to: &str, exact: &str| { + parse_toml(&manifest(&format!( + "[[spec.routes]]\nhostname='*.example.com'\nredirect={{to='{to}'}}\n{exact}" + ))) + }; + let www = "[[spec.routes]]\nhostname='www.example.com'\nservice='web'\nport=3000"; + assert!(redirect("https://www.example.com", www).is_ok()); + assert!(redirect("https://example.com", "").is_ok()); + let errors = redirect("https://www.example.com", "").unwrap_err(); + assert!( + errors + .0 + .iter() + .any(|e| e.code == ApiErrorCode::RouteRedirectLoop), + "{errors:?}" + ); +} + +#[test] +fn redirects_are_validated_and_keep_the_flat_wire_shape() { + let redirect = |fields: &str| { + parse_toml(&manifest(&format!( + "[[spec.routes]]\nhostname='www.example.com'\n{fields}" + ))) + }; + let app = redirect("redirect={to='https://example.com/'}") + .unwrap() + .normalize(ApplicationId::parse("test-app").unwrap()); + let route = &app.spec().routes[0]; + assert_eq!( + serde_json::to_value(route).unwrap(), + serde_json::json!({"hostname":"www.example.com","visibility":"private","redirect":{"to":"https://example.com/","status":308,"preserve_path":true}}) + ); + let RouteTarget::Redirect { redirect: target } = &route.target else { + panic!("redirect route") + }; + assert_eq!(target.location(), "https://example.com{http.request.uri}"); + assert_eq!( + parse_toml(&app.export_toml().unwrap()) + .unwrap() + .normalize(app.id().clone()), + app + ); + let fixed = + redirect("redirect={to='http://example.com:8080/a',status=302,preserve_path=false}") + .unwrap() + .normalize(app.id().clone()); + let RouteTarget::Redirect { redirect: fixed } = &fixed.spec().routes[0].target else { + panic!("redirect route") + }; + assert_eq!(fixed.location(), "http://example.com:8080/a"); + + for (fields, code) in [ + ( + "service='web'\nport=80\nredirect={to='https://example.com'}", + ApiErrorCode::RouteTargetInvalid, + ), + ("", ApiErrorCode::RouteTargetInvalid), + ("service='web'", ApiErrorCode::RouteTargetInvalid), + ( + "redirect={to='https://example.com',status=200}", + ApiErrorCode::RouteRedirectStatusInvalid, + ), + ( + "redirect={to='https://www.example.com/'}", + ApiErrorCode::RouteRedirectLoop, + ), + ( + "redirect={to='ftp://example.com'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ( + "redirect={to='https://example.com/?q=1'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ( + "redirect={to='https://example.com/{http.request.host}'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ( + "redirect={to='https://user@example.com'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ( + "redirect={to='https://example.com:0'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ( + "redirect={to='https://Example.com'}", + ApiErrorCode::RouteRedirectInvalid, + ), + ] { + let errors = redirect(fields).unwrap_err(); + assert!( + errors.0.iter().any(|e| e.code == code), + "{fields}: {errors:?}" + ); + } +} + +#[test] +fn decoding_keeps_stored_routes_and_rejects_mixed_targets() { + // Stored proxy routes predate redirects and must still decode. + let stored: ValidatedRoute = serde_json::from_value( + serde_json::json!({"hostname":"a.example.com","service":"web","port":80}), + ) + .unwrap(); + assert_eq!(stored.target.to_string(), "web:80"); + let redirect_json = + serde_json::json!({"to":"https://example.com/","status":308,"preserve_path":true}); + for target in [ + serde_json::json!({"service":"web","port":80,"redirect":redirect_json}), + serde_json::json!({"service":"web"}), + serde_json::json!({}), + ] { + let mut route = serde_json::json!({"hostname":"a.example.com"}); + route + .as_object_mut() + .unwrap() + .extend(target.as_object().unwrap().clone()); + assert!( + serde_json::from_value::(route.clone()).is_err(), + "{route}" + ); + route["environment_id"] = "test-app".into(); + route["visibility"] = "private".into(); + route["dns"] = serde_json::json!({"type":"server_addresses"}); + route["state"] = "ready".into(); + route["message"] = "".into(); + assert!( + serde_json::from_value::(route.clone()).is_err(), + "{route}" + ); + } +} + +#[test] +fn redirect_only_applications_have_no_ingress_network() { + let app = parse_toml("api_version='piqueld.dev/v1alpha1'\nkind='Application'\n[metadata]\nname='old'\n[[spec.routes]]\nhostname='old.example.com'\nredirect={to='https://new.example.com'}") + .unwrap() + .normalize(ApplicationId::parse("test-app").unwrap()); + let target = compile_application( + &app, + &EnvironmentId::parse("test-app").unwrap(), + InstanceId::parse("test-instance").unwrap(), + &ResolutionSet::default(), + ) + .unwrap() + .with_ingress(true); + assert_eq!(target.networks, []); + assert_eq!(target.routes, app.spec().routes); +} + +#[test] +fn only_exposed_services_join_ingress_and_disabling_preserves_route_intent() { + let routes = "[[spec.routes]]\nhostname='notes.example.com'\nservice='web'\nport=3000\n[[spec.services]]\nname='db'\n[spec.services.source]\ntype='image'\nimage='nginx:alpine'"; + let app = parse_toml(&manifest(routes)) + .unwrap() + .normalize(ApplicationId::parse("test-app").unwrap()); + let sources = ["web", "db"] + .into_iter() + .map(|name| { + ( + ServiceName::parse(name).unwrap(), + ResolvedSource::parse_image( + "nginx:alpine", + format!("nginx@sha256:{}", "a".repeat(64)), + ) + .unwrap(), + ) + }) + .collect(); + let target = compile_application( + &app, + &EnvironmentId::parse("test-app").unwrap(), + InstanceId::parse("test-instance").unwrap(), + &ResolutionSet { + sources, + ..ResolutionSet::default() + }, + ) + .unwrap(); + let enabled = target.clone().with_ingress(true); + assert_eq!(enabled.networks.len(), 2); + assert!( + enabled + .networks + .iter() + .all(crate::DesiredNetwork::has_valid_identity) + ); + assert_eq!( + enabled + .services + .iter() + .find(|s| s.logical_name.as_str() == "web") + .unwrap() + .networks + .len(), + 2 + ); + assert_eq!( + enabled + .services + .iter() + .find(|s| s.logical_name.as_str() == "db") + .unwrap() + .networks + .len(), + 1 + ); + assert_eq!(enabled.clone().with_ingress(true), enabled); + assert_eq!(enabled.with_ingress(false), target); +} diff --git a/crates/piqueld-core/src/observability/time.rs b/crates/piqueld-core/src/observability/time/mod.rs similarity index 65% rename from crates/piqueld-core/src/observability/time.rs rename to crates/piqueld-core/src/observability/time/mod.rs index 23ba1fb16..854efabf4 100644 --- a/crates/piqueld-core/src/observability/time.rs +++ b/crates/piqueld-core/src/observability/time/mod.rs @@ -192,121 +192,4 @@ impl Age { } #[cfg(test)] -mod tests { - use super::{Age, Elapsed, Timestamp, Uptime, UtcTime}; - use std::time::Duration; - - #[test] - fn times_read_as_utc_calendar_dates() { - for (ms, minute, day, exact) in [ - ( - 0, - "1970-01-01 00:00", - "1970-01-01", - "1970-01-01T00:00:00.000Z", - ), - ( - 951_782_400_000, - "2000-02-29 00:00", - "2000-02-29", - "2000-02-29T00:00:00.000Z", - ), - ( - 1_792_672_425_063, - "2026-10-22 12:33", - "2026-10-22", - "2026-10-22T12:33:45.063Z", - ), - ( - -60_000, - "1969-12-31 23:59", - "1969-12-31", - "1969-12-31T23:59:00.000Z", - ), - ] { - assert_eq!(UtcTime(ms).to_string(), minute); - assert_eq!(format!("{:#}", UtcTime(ms)), day); - assert_eq!(UtcTime(ms).rfc3339(), exact); - } - } - - #[test] - fn uptime_keeps_its_two_largest_units() { - for (seconds, text) in [ - (0, "0 s"), - (45, "45 s"), - (720, "12 min"), - (7_500, "2 h 5 min"), - (273_600, "3 d 4 h"), - ] { - assert_eq!(Uptime(Duration::from_secs(seconds)).to_string(), text); - } - } - - #[test] - fn elapsed_uses_the_largest_fitting_units() { - for (milliseconds, text) in [ - (-5, "0 ms"), - (850, "850 ms"), - (999, "999 ms"), - (1_000, "1.0 s"), - (12_340, "12.3 s"), - (12_350, "12.4 s"), - (59_949, "59.9 s"), - (59_950, "1 min 0 s"), - (252_000, "4 min 12 s"), - (7_500_000, "2 h 5 min"), - ] { - assert_eq!(Elapsed::from_millis(milliseconds).to_string(), text); - } - assert_eq!(Elapsed::from_millis_f64(3_245.7).to_string(), "3.2 s"); - assert_eq!(Elapsed::from_millis_f64(f64::NAN).to_string(), "0 ms"); - } - - #[test] - fn timestamps_are_utc_dates_and_times() { - for (milliseconds, text) in [ - (0, "1970-01-01 00:00:00Z"), - (-1, "1969-12-31 23:59:59Z"), - (1_767_225_599_999, "2025-12-31 23:59:59Z"), - (1_792_839_646_134, "2026-10-24 11:00:46Z"), - ] { - assert_eq!(Timestamp(milliseconds).to_string(), text); - } - assert_eq!(Timestamp::from_secs(60).to_string(), "1970-01-01 00:01:00Z"); - } - - /// The label of a moment `seconds` before now. - fn ago(seconds: i64) -> Option { - Age::at(0, seconds * 1000).label() - } - - #[test] - fn ages_switch_units_at_their_boundaries_and_minutes_round() { - for (seconds, label) in [ - (0, "just now"), - (44, "just now"), - (45, "1 min ago"), - (89, "1 min ago"), - (90, "2 min ago"), - (3_569, "59 min ago"), - (3_570, "1 h ago"), - (86_399, "23 h ago"), - (86_400, "1 d ago"), - (604_799, "6 d ago"), - ] { - assert_eq!(ago(seconds).as_deref(), Some(label), "{seconds} s"); - } - assert_eq!(ago(604_800), None); - } - - #[test] - fn ages_of_moments_to_come_read_forward() { - assert_eq!(ago(-44).as_deref(), Some("in a moment")); - assert_eq!(ago(-90).as_deref(), Some("in 2 min")); - assert_eq!(ago(-2 * 86_400).as_deref(), Some("in 2 d")); - assert_eq!(ago(-604_800), None); - // The difference saturates rather than overflowing. - assert_eq!(Age::at(i64::MIN, i64::MAX).label(), None); - } -} +mod tests; diff --git a/crates/piqueld-core/src/observability/time/tests.rs b/crates/piqueld-core/src/observability/time/tests.rs new file mode 100644 index 000000000..38e0a8b94 --- /dev/null +++ b/crates/piqueld-core/src/observability/time/tests.rs @@ -0,0 +1,116 @@ +use super::{Age, Elapsed, Timestamp, Uptime, UtcTime}; +use std::time::Duration; + +#[test] +fn times_read_as_utc_calendar_dates() { + for (ms, minute, day, exact) in [ + ( + 0, + "1970-01-01 00:00", + "1970-01-01", + "1970-01-01T00:00:00.000Z", + ), + ( + 951_782_400_000, + "2000-02-29 00:00", + "2000-02-29", + "2000-02-29T00:00:00.000Z", + ), + ( + 1_792_672_425_063, + "2026-10-22 12:33", + "2026-10-22", + "2026-10-22T12:33:45.063Z", + ), + ( + -60_000, + "1969-12-31 23:59", + "1969-12-31", + "1969-12-31T23:59:00.000Z", + ), + ] { + assert_eq!(UtcTime(ms).to_string(), minute); + assert_eq!(format!("{:#}", UtcTime(ms)), day); + assert_eq!(UtcTime(ms).rfc3339(), exact); + } +} + +#[test] +fn uptime_keeps_its_two_largest_units() { + for (seconds, text) in [ + (0, "0 s"), + (45, "45 s"), + (720, "12 min"), + (7_500, "2 h 5 min"), + (273_600, "3 d 4 h"), + ] { + assert_eq!(Uptime(Duration::from_secs(seconds)).to_string(), text); + } +} + +#[test] +fn elapsed_uses_the_largest_fitting_units() { + for (milliseconds, text) in [ + (-5, "0 ms"), + (850, "850 ms"), + (999, "999 ms"), + (1_000, "1.0 s"), + (12_340, "12.3 s"), + (12_350, "12.4 s"), + (59_949, "59.9 s"), + (59_950, "1 min 0 s"), + (252_000, "4 min 12 s"), + (7_500_000, "2 h 5 min"), + ] { + assert_eq!(Elapsed::from_millis(milliseconds).to_string(), text); + } + assert_eq!(Elapsed::from_millis_f64(3_245.7).to_string(), "3.2 s"); + assert_eq!(Elapsed::from_millis_f64(f64::NAN).to_string(), "0 ms"); +} + +#[test] +fn timestamps_are_utc_dates_and_times() { + for (milliseconds, text) in [ + (0, "1970-01-01 00:00:00Z"), + (-1, "1969-12-31 23:59:59Z"), + (1_767_225_599_999, "2025-12-31 23:59:59Z"), + (1_792_839_646_134, "2026-10-24 11:00:46Z"), + ] { + assert_eq!(Timestamp(milliseconds).to_string(), text); + } + assert_eq!(Timestamp::from_secs(60).to_string(), "1970-01-01 00:01:00Z"); +} + +/// The label of a moment `seconds` before now. +fn ago(seconds: i64) -> Option { + Age::at(0, seconds * 1000).label() +} + +#[test] +fn ages_switch_units_at_their_boundaries_and_minutes_round() { + for (seconds, label) in [ + (0, "just now"), + (44, "just now"), + (45, "1 min ago"), + (89, "1 min ago"), + (90, "2 min ago"), + (3_569, "59 min ago"), + (3_570, "1 h ago"), + (86_399, "23 h ago"), + (86_400, "1 d ago"), + (604_799, "6 d ago"), + ] { + assert_eq!(ago(seconds).as_deref(), Some(label), "{seconds} s"); + } + assert_eq!(ago(604_800), None); +} + +#[test] +fn ages_of_moments_to_come_read_forward() { + assert_eq!(ago(-44).as_deref(), Some("in a moment")); + assert_eq!(ago(-90).as_deref(), Some("in 2 min")); + assert_eq!(ago(-2 * 86_400).as_deref(), Some("in 2 d")); + assert_eq!(ago(-604_800), None); + // The difference saturates rather than overflowing. + assert_eq!(Age::at(i64::MIN, i64::MAX).label(), None); +} diff --git a/crates/piqueld-core/src/observability/units.rs b/crates/piqueld-core/src/observability/units/mod.rs similarity index 62% rename from crates/piqueld-core/src/observability/units.rs rename to crates/piqueld-core/src/observability/units/mod.rs index c668c9915..389a04c1f 100644 --- a/crates/piqueld-core/src/observability/units.rs +++ b/crates/piqueld-core/src/observability/units/mod.rs @@ -90,61 +90,4 @@ impl fmt::Display for Count { } #[cfg(test)] -mod tests { - use super::{Bytes, Count, Tenths}; - - #[test] - fn tenths_round_half_up_and_drop_a_whole_tenth_on_request() { - for (value, unit, text, compact) in [ - (0, 10, "0.0", "0"), - (14, 100, "0.1", "0.1"), - (1_049, 1_000, "1.0", "1"), - (1_050, 1_000, "1.1", "1.1"), - (9_950, 1_000, "10.0", "10"), - ] { - let tenths = Tenths::of(value, unit); - assert_eq!(tenths.to_string(), text, "{value} / {unit}"); - assert_eq!(format!("{tenths:#}"), compact, "{value} / {unit}"); - } - } - - #[test] - fn bytes_use_the_largest_reached_binary_unit() { - for (bytes, text) in [ - (0, "0 B"), - (1023, "1023 B"), - (1024, "1.0 KiB"), - (1536, "1.5 KiB"), - (52_428_800, "50.0 MiB"), - (127_026_911_232, "118.3 GiB"), - (u64::MAX, "16777216.0 TiB"), - ] { - assert_eq!(Bytes(bytes).to_string(), text); - } - assert_eq!(Bytes::from_i64(-1).to_string(), "0 B"); - } - - #[test] - fn counts_group_thousands_and_compact_on_scales() { - for (n, full, compact) in [ - (0, "0", "0"), - (999, "999", "999"), - (1_284, "1,284", "1,284"), - (9_999, "9,999", "9,999"), - (10_000, "10,000", "10K"), - (12_940, "12,940", "12.9K"), - (20_000, "20,000", "20K"), - (999_949, "999,949", "999.9K"), - (999_950, "999,950", "1M"), - (4_210_000, "4,210,000", "4.2M"), - (-1_000, "-1,000", "-1,000"), - (-12_940, "-12,940", "-12.9K"), - (-15_000, "-15,000", "-15K"), - (-4_210_000, "-4,210,000", "-4.2M"), - (i64::MIN, "-9,223,372,036,854,775,808", "-9223372036854.8M"), - ] { - assert_eq!(Count(n).to_string(), full); - assert_eq!(format!("{:#}", Count(n)), compact); - } - } -} +mod tests; diff --git a/crates/piqueld-core/src/observability/units/tests.rs b/crates/piqueld-core/src/observability/units/tests.rs new file mode 100644 index 000000000..36aca632a --- /dev/null +++ b/crates/piqueld-core/src/observability/units/tests.rs @@ -0,0 +1,56 @@ +use super::{Bytes, Count, Tenths}; + +#[test] +fn tenths_round_half_up_and_drop_a_whole_tenth_on_request() { + for (value, unit, text, compact) in [ + (0, 10, "0.0", "0"), + (14, 100, "0.1", "0.1"), + (1_049, 1_000, "1.0", "1"), + (1_050, 1_000, "1.1", "1.1"), + (9_950, 1_000, "10.0", "10"), + ] { + let tenths = Tenths::of(value, unit); + assert_eq!(tenths.to_string(), text, "{value} / {unit}"); + assert_eq!(format!("{tenths:#}"), compact, "{value} / {unit}"); + } +} + +#[test] +fn bytes_use_the_largest_reached_binary_unit() { + for (bytes, text) in [ + (0, "0 B"), + (1023, "1023 B"), + (1024, "1.0 KiB"), + (1536, "1.5 KiB"), + (52_428_800, "50.0 MiB"), + (127_026_911_232, "118.3 GiB"), + (u64::MAX, "16777216.0 TiB"), + ] { + assert_eq!(Bytes(bytes).to_string(), text); + } + assert_eq!(Bytes::from_i64(-1).to_string(), "0 B"); +} + +#[test] +fn counts_group_thousands_and_compact_on_scales() { + for (n, full, compact) in [ + (0, "0", "0"), + (999, "999", "999"), + (1_284, "1,284", "1,284"), + (9_999, "9,999", "9,999"), + (10_000, "10,000", "10K"), + (12_940, "12,940", "12.9K"), + (20_000, "20,000", "20K"), + (999_949, "999,949", "999.9K"), + (999_950, "999,950", "1M"), + (4_210_000, "4,210,000", "4.2M"), + (-1_000, "-1,000", "-1,000"), + (-12_940, "-12,940", "-12.9K"), + (-15_000, "-15,000", "-15K"), + (-4_210_000, "-4,210,000", "-4.2M"), + (i64::MIN, "-9,223,372,036,854,775,808", "-9223372036854.8M"), + ] { + assert_eq!(Count(n).to_string(), full); + assert_eq!(format!("{:#}", Count(n)), compact); + } +} diff --git a/crates/piqueld-core/src/release.rs b/crates/piqueld-core/src/release/mod.rs similarity index 53% rename from crates/piqueld-core/src/release.rs rename to crates/piqueld-core/src/release/mod.rs index 715de9751..e25798c3b 100644 --- a/crates/piqueld-core/src/release.rs +++ b/crates/piqueld-core/src/release/mod.rs @@ -205,199 +205,4 @@ impl Release { } #[cfg(test)] -mod tests { - use super::*; - use crate::{ - ApiErrorCode, ApplicationId, EnvironmentId, InstanceId, ResolutionSet, compile_application, - compile_release, manifest::parse_template_toml, - }; - - const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; - - /// A repository-backed shop whose `web` service builds `self` with `arg` - /// as its `VITE_ORIGIN` build argument and runs with per-environment - /// replicas and origin. - fn template(arg: &str) -> ApplicationTemplate { - parse_template_toml(&format!( - r#"api_version = "piqueld.dev/v1alpha1" -kind = "Application" -[metadata] -name = "shop" -[spec.manifest] -path = "piqueld.toml" -[spec.manifest.repository] -url = "https://example.com/shop.git" -branch = "main" -[spec.variables] -replicas = 1 -[spec.environments.staging.variables] -domain = "staging.example.com" -[spec.environments.production.variables] -domain = "example.com" -replicas = 3 -[[spec.services]] -name = "web" -replicas = "${{{{ vars.replicas }}}}" -[spec.services.environment] -ORIGIN = "https://${{{{ vars.domain }}}}" -[spec.services.source] -type = "git" -repository = "self" -[spec.services.source.build] -type = "docker" -dockerfile = "Dockerfile" -[spec.services.source.build.args] -VITE_ORIGIN = "{arg}" -REVISION = "${{{{ git.sha }}}}" -"# - )) - .unwrap() - .normalize(ApplicationId::parse("app-shop-0001").unwrap()) - } - - fn environment(name: &str) -> EnvironmentId { - EnvironmentId::parse(format!("env-{name}-0001")).unwrap() - } - - fn instance() -> InstanceId { - InstanceId::parse("instance").unwrap() - } - - /// The release staging records after building `web` from `template`. - fn staging_release(template: ApplicationTemplate) -> Release { - let unprepared = Release { - template, - commit: Some(COMMIT.into()), - sources: BTreeMap::new(), - }; - let rendering = unprepared - .render(EnvironmentName::parse("staging").unwrap(), None) - .unwrap(); - let web = &rendering.application.spec().services[0]; - let resolutions = ResolutionSet { - sources: BTreeMap::from([( - web.name.clone(), - ResolvedSource::Git { - requested: web.source.clone(), - commit: COMMIT.into(), - image_id: Sha256Digest::parse(format!("sha256:{}", "a".repeat(64))) - .unwrap() - .into(), - }, - )]), - secret_names: BTreeMap::new(), - }; - let target = compile_application( - &rendering.application, - &environment("staging"), - instance(), - &resolutions, - ) - .unwrap(); - Release::new(unprepared.template, unprepared.commit, &target) - } - - #[test] - fn records_provenance_images_and_fingerprint_and_hashes_content() { - let release = staging_release(template("https://example.com")); - let web = ServiceName::parse("web").unwrap(); - let ResolvedSource::Git { - commit, image_id, .. - } = &release.sources()[&web] - else { - panic!("Git build") - }; - assert_eq!( - (commit.as_str(), image_id.as_str()), - (COMMIT, &*format!("sha256:{}", "a".repeat(64))) - ); - assert_eq!( - *release.fingerprint().services()[&web].fields(), - BTreeMap::from( - [ - ("source.build.args.REVISION", COMMIT), - ("source.build.args.VITE_ORIGIN", "https://example.com"), - ("source.build.context", "."), - ("source.build.dockerfile", "Dockerfile"), - ("source.commit", COMMIT), - ("source.repository", "https://example.com/shop.git"), - ] - .map(|(field, value)| (field.to_owned(), value.to_owned())) - ) - ); - // The name renders through `${{ app.name }}`, so it is content, like - // a build argument. - let renamed = Release { - template: release - .template - .clone() - .with_name(crate::ApplicationName::parse("store").unwrap()), - ..release.clone() - }; - assert_ne!(renamed.content_hash(), release.content_hash()); - // So is the branch the manifest was read from, `${{ git.branch }}`. - let mut manifest = release.template.spec().manifest.clone().unwrap(); - manifest.repository.branch = "release".into(); - let branched = Release { - template: release.template.clone().with_manifest(Some(manifest)), - ..release.clone() - }; - assert_ne!(branched.content_hash(), release.content_hash()); - assert_ne!( - staging_release(template("https://shop.example.com")).content_hash(), - release.content_hash() - ); - } - - #[test] - fn instantiates_for_an_environment_whose_variables_change_only_runtime_fields() { - let release = staging_release(template("https://example.com")); - let rendering = release - .render( - EnvironmentName::parse("production").unwrap(), - Some("deployment".into()), - ) - .unwrap(); - let target = compile_release( - &rendering.application, - &environment("production"), - instance(), - &release, - BTreeMap::new(), - ) - .unwrap(); - let web = &target.services[0]; - assert_eq!(web.replicas, 3); - assert_eq!(web.environment["ORIGIN"], "https://example.com"); - assert_eq!( - web.source, - release.sources().values().next().unwrap().clone() - ); - } - - #[test] - fn refuses_an_environment_that_renders_a_build_argument_differently() { - let release = staging_release(template("https://${{ vars.domain }}")); - let rendering = release - .render(EnvironmentName::parse("production").unwrap(), None) - .unwrap(); - let errors = compile_release( - &rendering.application, - &environment("production"), - instance(), - &release, - BTreeMap::new(), - ) - .unwrap_err(); - assert_eq!( - errors - .iter() - .map(|error| (error.code.as_str(), error.resource.as_str())) - .collect::>(), - [( - ApiErrorCode::ReleaseIncompatible.as_str(), - "web.source.build.args.VITE_ORIGIN" - )] - ); - } -} +mod tests; diff --git a/crates/piqueld-core/src/release/tests.rs b/crates/piqueld-core/src/release/tests.rs new file mode 100644 index 000000000..ca49c404c --- /dev/null +++ b/crates/piqueld-core/src/release/tests.rs @@ -0,0 +1,194 @@ +use super::*; +use crate::{ + ApiErrorCode, ApplicationId, EnvironmentId, InstanceId, ResolutionSet, compile_application, + compile_release, manifest::parse_template_toml, +}; + +const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + +/// A repository-backed shop whose `web` service builds `self` with `arg` +/// as its `VITE_ORIGIN` build argument and runs with per-environment +/// replicas and origin. +fn template(arg: &str) -> ApplicationTemplate { + parse_template_toml(&format!( + r#"api_version = "piqueld.dev/v1alpha1" +kind = "Application" +[metadata] +name = "shop" +[spec.manifest] +path = "piqueld.toml" +[spec.manifest.repository] +url = "https://example.com/shop.git" +branch = "main" +[spec.variables] +replicas = 1 +[spec.environments.staging.variables] +domain = "staging.example.com" +[spec.environments.production.variables] +domain = "example.com" +replicas = 3 +[[spec.services]] +name = "web" +replicas = "${{{{ vars.replicas }}}}" +[spec.services.environment] +ORIGIN = "https://${{{{ vars.domain }}}}" +[spec.services.source] +type = "git" +repository = "self" +[spec.services.source.build] +type = "docker" +dockerfile = "Dockerfile" +[spec.services.source.build.args] +VITE_ORIGIN = "{arg}" +REVISION = "${{{{ git.sha }}}}" +"# + )) + .unwrap() + .normalize(ApplicationId::parse("app-shop-0001").unwrap()) +} + +fn environment(name: &str) -> EnvironmentId { + EnvironmentId::parse(format!("env-{name}-0001")).unwrap() +} + +fn instance() -> InstanceId { + InstanceId::parse("instance").unwrap() +} + +/// The release staging records after building `web` from `template`. +fn staging_release(template: ApplicationTemplate) -> Release { + let unprepared = Release { + template, + commit: Some(COMMIT.into()), + sources: BTreeMap::new(), + }; + let rendering = unprepared + .render(EnvironmentName::parse("staging").unwrap(), None) + .unwrap(); + let web = &rendering.application.spec().services[0]; + let resolutions = ResolutionSet { + sources: BTreeMap::from([( + web.name.clone(), + ResolvedSource::Git { + requested: web.source.clone(), + commit: COMMIT.into(), + image_id: Sha256Digest::parse(format!("sha256:{}", "a".repeat(64))) + .unwrap() + .into(), + }, + )]), + secret_names: BTreeMap::new(), + }; + let target = compile_application( + &rendering.application, + &environment("staging"), + instance(), + &resolutions, + ) + .unwrap(); + Release::new(unprepared.template, unprepared.commit, &target) +} + +#[test] +fn records_provenance_images_and_fingerprint_and_hashes_content() { + let release = staging_release(template("https://example.com")); + let web = ServiceName::parse("web").unwrap(); + let ResolvedSource::Git { + commit, image_id, .. + } = &release.sources()[&web] + else { + panic!("Git build") + }; + assert_eq!( + (commit.as_str(), image_id.as_str()), + (COMMIT, &*format!("sha256:{}", "a".repeat(64))) + ); + assert_eq!( + *release.fingerprint().services()[&web].fields(), + BTreeMap::from( + [ + ("source.build.args.REVISION", COMMIT), + ("source.build.args.VITE_ORIGIN", "https://example.com"), + ("source.build.context", "."), + ("source.build.dockerfile", "Dockerfile"), + ("source.commit", COMMIT), + ("source.repository", "https://example.com/shop.git"), + ] + .map(|(field, value)| (field.to_owned(), value.to_owned())) + ) + ); + // The name renders through `${{ app.name }}`, so it is content, like + // a build argument. + let renamed = Release { + template: release + .template + .clone() + .with_name(crate::ApplicationName::parse("store").unwrap()), + ..release.clone() + }; + assert_ne!(renamed.content_hash(), release.content_hash()); + // So is the branch the manifest was read from, `${{ git.branch }}`. + let mut manifest = release.template.spec().manifest.clone().unwrap(); + manifest.repository.branch = "release".into(); + let branched = Release { + template: release.template.clone().with_manifest(Some(manifest)), + ..release.clone() + }; + assert_ne!(branched.content_hash(), release.content_hash()); + assert_ne!( + staging_release(template("https://shop.example.com")).content_hash(), + release.content_hash() + ); +} + +#[test] +fn instantiates_for_an_environment_whose_variables_change_only_runtime_fields() { + let release = staging_release(template("https://example.com")); + let rendering = release + .render( + EnvironmentName::parse("production").unwrap(), + Some("deployment".into()), + ) + .unwrap(); + let target = compile_release( + &rendering.application, + &environment("production"), + instance(), + &release, + BTreeMap::new(), + ) + .unwrap(); + let web = &target.services[0]; + assert_eq!(web.replicas, 3); + assert_eq!(web.environment["ORIGIN"], "https://example.com"); + assert_eq!( + web.source, + release.sources().values().next().unwrap().clone() + ); +} + +#[test] +fn refuses_an_environment_that_renders_a_build_argument_differently() { + let release = staging_release(template("https://${{ vars.domain }}")); + let rendering = release + .render(EnvironmentName::parse("production").unwrap(), None) + .unwrap(); + let errors = compile_release( + &rendering.application, + &environment("production"), + instance(), + &release, + BTreeMap::new(), + ) + .unwrap_err(); + assert_eq!( + errors + .iter() + .map(|error| (error.code.as_str(), error.resource.as_str())) + .collect::>(), + [( + ApiErrorCode::ReleaseIncompatible.as_str(), + "web.source.build.args.VITE_ORIGIN" + )] + ); +} diff --git a/crates/piqueld-core/src/timeline.rs b/crates/piqueld-core/src/timeline/mod.rs similarity index 62% rename from crates/piqueld-core/src/timeline.rs rename to crates/piqueld-core/src/timeline/mod.rs index 903d457d9..7ebdc8b4f 100644 --- a/crates/piqueld-core/src/timeline.rs +++ b/crates/piqueld-core/src/timeline/mod.rs @@ -1034,618 +1034,4 @@ impl Progress { } #[cfg(test)] -mod tests { - use super::*; - use crate::{EnvironmentId, OperationKind}; - - fn key(phase: Phase, resource: &str) -> StepKey { - StepKey { - phase, - resource: Some(resource.into()), - } - } - - fn timeline(expected: &[(Phase, &str, u64)]) -> Timeline { - let operation = Operation { - id: "op".into(), - environment_id: EnvironmentId::parse("env-web-01").unwrap(), - kind: OperationKind::Refresh, - generation: 1, - attempt: 1, - consecutive_failures: 0, - state: OperationState::Running, - phase: None, - resource: None, - error_code: None, - error_message: None, - created_at_ms: 0, - updated_at_ms: 0, - started_at_ms: Some(0), - finished_at_ms: None, - }; - let expected: Vec<_> = expected - .iter() - .map(|(phase, resource, duration_ms)| ExpectedStep { - key: key(*phase, resource), - duration_ms: *duration_ms, - }) - .collect(); - let forecast = expected.iter().map(|step| step.key.clone()).collect(); - Timeline::new(operation, forecast, expected) - } - - /// Applies events numbered from the timeline's cursor. - fn apply(timeline: &mut Timeline, events: Vec) { - for (offset, mut event) in events.into_iter().enumerate() { - event.id = timeline.cursor + 1 + i64::try_from(offset).unwrap(); - event.operation_id = Some("op".into()); - event.attempt = Some(1); - timeline.apply(&event); - } - } - - fn action(kind: &str, id: &str, phase: Phase, resource: &str, at: i64) -> Event { - Event { - kind: kind.into(), - action_id: Some(id.into()), - phase: Some(phase), - resource: Some(resource.into()), - created_at_ms: at, - ..Event::default() - } - } - - fn planned(coverage: PlanCoverage, steps: &[StepKey]) -> Event { - Event { - kind: "plan_recorded".into(), - detail: Some(EventDetail::Planned { - steps: steps.to_vec(), - coverage, - }), - ..Event::default() - } - } - - fn states(timeline: &Timeline) -> Vec<(Phase, StepState)> { - timeline - .steps - .iter() - .map(|step| (step.key.phase, step.state)) - .collect() - } - - #[test] - fn plans_replace_the_forecast_and_actions_fill_them_in() { - let mut timeline = timeline(&[ - (Phase::BuildGit, "web", 30_000), - (Phase::RunJob, "migrate", 4_000), - (Phase::EnsureService, "web", 2_000), - (Phase::WaitForService, "web", 10_000), - ]); - assert_eq!( - states(&timeline), - [ - (Phase::BuildGit, StepState::Forecast), - (Phase::RunJob, StepState::Forecast), - (Phase::EnsureService, StepState::Forecast), - (Phase::WaitForService, StepState::Forecast), - ] - ); - // Each plan replaces only its own stage's forecast. - apply( - &mut timeline, - vec![planned( - PlanCoverage::Preparation, - &[key(Phase::BuildGit, "web")], - )], - ); - assert_eq!( - states(&timeline), - [ - (Phase::BuildGit, StepState::Planned), - (Phase::RunJob, StepState::Forecast), - (Phase::EnsureService, StepState::Forecast), - (Phase::WaitForService, StepState::Forecast), - ] - ); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 100), - action("action_succeeded", "a1", Phase::BuildGit, "web", 25_100), - planned( - PlanCoverage::Runtime, - &[ - key(Phase::EnsureVolume, "data"), - key(Phase::EnsureService, "web"), - ], - ), - action("action_started", "a2", Phase::EnsureVolume, "data", 25_200), - ], - ); - assert_eq!( - states(&timeline), - [ - (Phase::BuildGit, StepState::Succeeded), - (Phase::EnsureVolume, StepState::Running), - (Phase::EnsureService, StepState::Planned), - ] - ); - let build = &timeline.steps[0]; - assert_eq!( - (build.started_at_ms, build.finished_at_ms, build.expected_ms), - (Some(100), Some(25_100), Some(30_000)) - ); - assert_eq!(timeline.steps[2].expected_ms, Some(2_000)); - } - - #[test] - fn an_operation_that_ended_forecasts_nothing() { - let mut timeline = timeline(&[ - (Phase::BuildGit, "web", 30_000), - (Phase::EnsureService, "web", 2_000), - ]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 0), - action("action_failed", "a1", Phase::BuildGit, "web", 100), - ], - ); - let mut failed = timeline.operation.clone(); - failed.state = OperationState::Failed; - // Followed live, as a new read does. - timeline.set_operation(failed.clone()); - assert_eq!(states(&timeline), [(Phase::BuildGit, StepState::Failed)]); - let read = Timeline::new(failed, vec![key(Phase::EnsureService, "web")], Vec::new()); - assert_eq!(states(&read), Vec::new()); - } - - #[test] - fn retries_and_failures_stay_on_their_step() { - let mut timeline = timeline(&[]); - let mut retry = action("action_retry", "a1", Phase::EnsureService, "web", 200); - retry.diagnostic = Some(Diagnostic::from_recorded_code( - "d1".into(), - "docker_unavailable", - "Docker is unavailable".into(), - )); - let mut requested = action("action_requested", "a1", Phase::EnsureService, "web", 300); - requested.retry = Some(3); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::EnsureService, "web", 100), - retry, - ], - ); - assert_eq!(timeline.steps[0].state, StepState::Retrying); - apply( - &mut timeline, - vec![ - requested, - action("action_failed", "a1", Phase::EnsureService, "web", 400), - // A new attempt runs the same step again as its own. - action("action_started", "a2", Phase::EnsureService, "web", 500), - ], - ); - assert_eq!( - states(&timeline), - [ - (Phase::EnsureService, StepState::Failed), - (Phase::EnsureService, StepState::Running), - ] - ); - assert_eq!(timeline.steps[0].retries, 2); - } - - #[test] - fn only_a_run_whose_steps_all_succeeded_compares_with_the_usual() { - let run = |last: &str, state: OperationState| { - let mut timeline = timeline(&[ - (Phase::BuildGit, "web", 30_000), - (Phase::EnsureService, "web", 2_000), - ]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 0), - action("action_succeeded", "a1", Phase::BuildGit, "web", 5_000), - action("action_started", "a2", Phase::EnsureService, "web", 5_000), - action(last, "a2", Phase::EnsureService, "web", 6_000), - ], - ); - timeline.operation.state = state; - timeline.comparable_usual_ms() - }; - assert_eq!( - run("action_succeeded", OperationState::Succeeded), - Some(32_000) - ); - // A run that failed after 6 s is not 26 s faster than usual, even - // when it failed after its last step succeeded. - assert_eq!(run("action_failed", OperationState::Failed), None); - assert_eq!(run("action_succeeded", OperationState::Failed), None); - // Nor is one with a step it never ran before, whose usual time would - // only count its known steps. - let mut timeline = timeline(&[(Phase::BuildGit, "web", 30_000)]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 0), - action("action_succeeded", "a1", Phase::BuildGit, "web", 30_000), - action("action_started", "a2", Phase::RunJob, "migrate", 30_000), - action("action_succeeded", "a2", Phase::RunJob, "migrate", 90_000), - ], - ); - timeline.operation.state = OperationState::Succeeded; - assert_eq!(timeline.usual_ms(), Some(30_000)); - assert_eq!(timeline.comparable_usual_ms(), None); - } - - #[test] - fn sources_count_once_towards_the_time_left() { - let mut timeline = timeline(&[ - (Phase::BuildGit, "api", 30_000), - (Phase::BuildGit, "web", 20_000), - (Phase::RunJob, "migrate", 5_000), - ]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "api", 0), - action("action_started", "a2", Phase::BuildGit, "web", 0), - ], - ); - // Usually the longest source's 30 s, then the job's 5 s. - assert_eq!(timeline.usual_ms(), Some(35_000)); - // The longest source has 20 s left, then the job's 5 s. - assert_eq!(timeline.remaining_ms(10_000), Some(25_000)); - // A step running over its expectation counts as about to end. - assert_eq!(timeline.remaining_ms(40_000), Some(5_000)); - } - - fn rollout(at: i64, tasks: &[(&str, bool, TaskState)]) -> Event { - Event { - kind: "action_progressed".into(), - action_id: Some("wait".into()), - created_at_ms: at, - detail: Some(EventDetail::Rollout { - tasks: tasks - .iter() - .map(|(id, current, state)| RolloutTask { - id: (*id).into(), - slot: Some(1), - current: *current, - state: *state, - healthy: None, - }) - .collect(), - monitor_seconds: 5, - }), - ..Event::default() - } - } - - #[test] - fn rollouts_record_each_task_state_and_when_none_served() { - use TaskState::{Preparing, Running, Shutdown}; - let mut timeline = timeline(&[]); - apply( - &mut timeline, - vec![ - action("action_started", "wait", Phase::WaitForService, "web", 0), - // Stop-first: the old task stops before the new one runs. - rollout(100, &[("old", false, Running)]), - rollout(200, &[("old", false, Shutdown), ("new", true, Preparing)]), - rollout(300, &[("old", false, Shutdown), ("new", true, Preparing)]), - rollout(900, &[("old", false, Shutdown), ("new", true, Running)]), - ], - ); - let step = &timeline.steps[0]; - assert_eq!(step.monitor_seconds, Some(5)); - let lanes: Vec<_> = step - .tasks - .iter() - .map(|lane| { - let spans: Vec<_> = lane - .spans - .iter() - .map(|span| (span.state, span.from_ms)) - .collect(); - (lane.task.id.as_str(), lane.task.current, spans) - }) - .collect(); - assert_eq!( - lanes, - [ - ("old", false, vec![(Running, 100), (Shutdown, 200)]), - ("new", true, vec![(Preparing, 200), (Running, 900)]), - ] - ); - assert_eq!( - step.gaps(), - [Gap { - from_ms: 200, - to_ms: Some(900) - }] - ); - - // Start-first: the old task serves until the new one does. - let mut start_first = self::timeline(&[]); - apply( - &mut start_first, - vec![ - action("action_started", "wait", Phase::WaitForService, "web", 0), - rollout(100, &[("old", false, Running), ("new", true, Preparing)]), - rollout(500, &[("old", false, Running), ("new", true, Running)]), - rollout(600, &[("old", false, Shutdown), ("new", true, Running)]), - ], - ); - assert_eq!(start_first.steps[0].gaps(), []); - assert!(start_first.steps[0].overlapped()); - // A stop-first rollout neither overlaps, nor, when its handover - // fell between two observations, shows a gap. - assert!(!timeline.steps[0].overlapped()); - let mut unseen = self::timeline(&[]); - apply( - &mut unseen, - vec![ - action("action_started", "wait", Phase::WaitForService, "web", 0), - rollout(100, &[("old", false, Running)]), - rollout(500, &[("old", false, Shutdown), ("new", true, Running)]), - ], - ); - assert_eq!( - (unseen.steps[0].gaps(), unseen.steps[0].overlapped()), - (vec![], false) - ); - } - - #[test] - fn rollouts_summarize_their_new_tasks_monitor_window_and_downtime() { - use TaskState::{Preparing, Running, Shutdown}; - let mut timeline = timeline(&[]); - apply( - &mut timeline, - vec![ - action("action_started", "wait", Phase::WaitForService, "web", 0), - rollout(100, &[("old", false, Running)]), - rollout(200, &[("old", false, Shutdown), ("new", true, Preparing)]), - ], - ); - let step = &timeline.steps[0]; - let tasks = step.new_tasks().unwrap(); - assert_eq!( - tasks, - NewTasks { - running: 0, - total: 1 - } - ); - assert_eq!(tasks.to_string(), "0/1 new task running"); - // Down since the old task stopped, and still. - let down = Downtime { - ms: 800, - ongoing: true, - }; - assert_eq!(step.downtime(1_000), Some(down)); - assert_eq!(step.monitor(1_000), None); - - apply( - &mut timeline, - vec![rollout( - 2_000, - &[("old", false, Shutdown), ("new", true, Running)], - )], - ); - let step = &timeline.steps[0]; - assert_eq!(step.new_tasks().unwrap().running, 1); - // Swarm watches the new task for 5 s from when it ran. - let window = Window { - from_ms: 2_000, - to_ms: 7_000, - }; - assert_eq!(step.monitor(3_000), Some(window)); - assert_eq!(window.left_ms(3_000), 4_000); - assert_eq!(step.monitor(7_000), None); - let down = Downtime { - ms: 1_800, - ongoing: false, - }; - assert_eq!(step.downtime(9_000), Some(down)); - - // Once the step ended, no window is open. - apply( - &mut timeline, - vec![action( - "action_succeeded", - "wait", - Phase::WaitForService, - "web", - 4_000, - )], - ); - assert_eq!(timeline.steps[0].monitor(3_000), None); - } - - #[test] - fn another_attempt_starts_over() { - let mut timeline = timeline(&[]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 1), - action("action_failed", "a1", Phase::BuildGit, "web", 2), - ], - ); - // Requested again, its latest attempt is the run before. - let mut requested = timeline.operation.clone(); - requested.state = OperationState::Requested; - timeline.set_operation(requested.clone()); - assert_eq!(timeline.steps.len(), 0, "{:?}", timeline.steps); - let mut retried = requested; - retried.state = OperationState::Running; - retried.attempt = 2; - timeline.set_operation(retried); - // Events of the earlier attempt no longer apply. - let mut late = action("action_started", "a3", Phase::EnsureService, "web", 3); - late.id = timeline.cursor + 1; - late.operation_id = Some("op".into()); - late.attempt = Some(1); - timeline.apply(&late); - assert_eq!(timeline.steps.len(), 0); - } - - #[test] - fn a_requested_operation_shows_none_of_its_previous_run() { - let mut timeline = timeline(&[(Phase::EnsureService, "web", 2_000)]); - timeline.operation.state = OperationState::Requested; - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::EnsureService, "web", 1), - action("action_succeeded", "a1", Phase::EnsureService, "web", 2), - ], - ); - assert_eq!( - states(&timeline), - [(Phase::EnsureService, StepState::Forecast)] - ); - } - - #[test] - fn only_noticeably_unusual_durations_are_flagged() { - let mut timeline = timeline(&[ - (Phase::BuildGit, "api", 30_000), - (Phase::BuildGit, "web", 20_000), - (Phase::EnsureService, "api", 1_000), - ]); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "api", 0), - action("action_started", "a2", Phase::BuildGit, "web", 0), - action("action_succeeded", "a1", Phase::BuildGit, "api", 50_000), - action("action_succeeded", "a2", Phase::BuildGit, "web", 21_000), - action("action_started", "a3", Phase::EnsureService, "api", 50_000), - ], - ); - let unusual: Vec<_> = timeline.steps.iter().map(Step::unusual_ms).collect(); - // 20 s over its 30 s is unusual; 1 s over 20 s is not. - assert_eq!(unusual, [Some(30_000), None, None]); - // The sources build at once, then the service updates. - assert_eq!(timeline.usual_ms(), Some(31_000)); - } - - #[test] - fn events_already_applied_or_of_other_operations_are_ignored() { - let mut timeline = timeline(&[]); - apply( - &mut timeline, - vec![action( - "action_started", - "a1", - Phase::EnsureService, - "web", - 1, - )], - ); - let mut replayed = action("action_succeeded", "a1", Phase::EnsureService, "web", 2); - replayed.id = timeline.cursor; - replayed.operation_id = Some("op".into()); - timeline.apply(&replayed); - let mut other = action("action_succeeded", "a1", Phase::EnsureService, "web", 2); - other.id = timeline.cursor + 1; - other.operation_id = Some("other".into()); - timeline.apply(&other); - assert_eq!(timeline.steps[0].state, StepState::Running); - } - - #[test] - fn progress_counts_from_the_first_start_and_rounds_down() { - let mut timeline = timeline(&[ - (Phase::BuildGit, "web", 30_000), - (Phase::RunJob, "migrate", 4_000), - (Phase::EnsureService, "web", 2_000), - ]); - timeline.operation.state = OperationState::Requested; - timeline.operation.started_at_ms = None; - let queued = Progress::new(&timeline, 1_000); - assert_eq!( - (queued.status(), queued.steps(), queued.percent()), - ("Queued", "0/3".into(), 0) - ); - assert_eq!(queued.elapsed_ms, None); - - // The operation's own start trails its first step's. - timeline.operation.state = OperationState::Running; - timeline.operation.started_at_ms = Some(2_000); - apply( - &mut timeline, - vec![ - action("action_started", "a1", Phase::BuildGit, "web", 1_000), - action("action_succeeded", "a1", Phase::BuildGit, "web", 11_000), - action("action_started", "a2", Phase::RunJob, "migrate", 11_000), - ], - ); - let running = Progress::new(&timeline, 13_000); - assert_eq!(running.status(), "Deploying"); - assert_eq!(running.running, ["Run job migrate"]); - assert_eq!(running.elapsed_ms, Some(12_000)); - // One step of three: 33 %, and 4 of a 12-cell bar. - assert_eq!((running.percent(), running.filled(12)), (33, 4)); - // The job has 2 s left, then the service's 2 s. - assert_eq!(running.outlook().as_deref(), Some("~4.0 s left")); - } - - #[test] - fn progress_of_no_steps_is_none_done() { - let progress = Progress::new(&timeline(&[]), 0); - assert_eq!((progress.percent(), progress.filled(12)), (0, 0)); - assert_eq!(progress.steps(), "0/0"); - } - - #[test] - fn progress_names_its_state_by_kind() { - let mut timeline = timeline(&[]); - let status = |timeline: &Timeline| Progress::new(timeline, 0).status(); - timeline.operation.kind = OperationKind::Delete; - assert_eq!(status(&timeline), "Deleting"); - timeline.operation.state = OperationState::Succeeded; - assert_eq!(status(&timeline), "Deleted"); - timeline.operation.kind = OperationKind::Apply; - assert_eq!(status(&timeline), "Deployed"); - timeline.operation.state = OperationState::Superseded; - assert_eq!(status(&timeline), "Superseded"); - } - - #[test] - fn progress_tells_the_time_left_then_against_the_usual() { - let mut progress = Progress { - kind: OperationKind::Apply, - state: OperationState::Running, - done: 4, - total: 9, - running: vec!["Build web".into()], - elapsed_ms: Some(30_000), - left_ms: Some(48_000), - usual_ms: Some(80_000), - }; - assert_eq!(progress.steps(), "4/9"); - assert_eq!(progress.outlook().as_deref(), Some("~48.0 s left")); - progress.state = OperationState::Succeeded; - for (elapsed, outlook) in [ - (74_000, "6.0 s faster than usual"), - (79_001, "as long as usual"), - (80_999, "as long as usual"), - (81_000, "1.0 s slower than usual"), - ] { - progress.elapsed_ms = Some(elapsed); - assert_eq!(progress.outlook().as_deref(), Some(outlook), "{elapsed}"); - } - // A run that is not comparable with the usual one says nothing. - progress.usual_ms = None; - assert_eq!(progress.outlook(), None); - } -} +mod tests; diff --git a/crates/piqueld-core/src/timeline/tests.rs b/crates/piqueld-core/src/timeline/tests.rs new file mode 100644 index 000000000..ed4761f05 --- /dev/null +++ b/crates/piqueld-core/src/timeline/tests.rs @@ -0,0 +1,613 @@ +use super::*; +use crate::{EnvironmentId, OperationKind}; + +fn key(phase: Phase, resource: &str) -> StepKey { + StepKey { + phase, + resource: Some(resource.into()), + } +} + +fn timeline(expected: &[(Phase, &str, u64)]) -> Timeline { + let operation = Operation { + id: "op".into(), + environment_id: EnvironmentId::parse("env-web-01").unwrap(), + kind: OperationKind::Refresh, + generation: 1, + attempt: 1, + consecutive_failures: 0, + state: OperationState::Running, + phase: None, + resource: None, + error_code: None, + error_message: None, + created_at_ms: 0, + updated_at_ms: 0, + started_at_ms: Some(0), + finished_at_ms: None, + }; + let expected: Vec<_> = expected + .iter() + .map(|(phase, resource, duration_ms)| ExpectedStep { + key: key(*phase, resource), + duration_ms: *duration_ms, + }) + .collect(); + let forecast = expected.iter().map(|step| step.key.clone()).collect(); + Timeline::new(operation, forecast, expected) +} + +/// Applies events numbered from the timeline's cursor. +fn apply(timeline: &mut Timeline, events: Vec) { + for (offset, mut event) in events.into_iter().enumerate() { + event.id = timeline.cursor + 1 + i64::try_from(offset).unwrap(); + event.operation_id = Some("op".into()); + event.attempt = Some(1); + timeline.apply(&event); + } +} + +fn action(kind: &str, id: &str, phase: Phase, resource: &str, at: i64) -> Event { + Event { + kind: kind.into(), + action_id: Some(id.into()), + phase: Some(phase), + resource: Some(resource.into()), + created_at_ms: at, + ..Event::default() + } +} + +fn planned(coverage: PlanCoverage, steps: &[StepKey]) -> Event { + Event { + kind: "plan_recorded".into(), + detail: Some(EventDetail::Planned { + steps: steps.to_vec(), + coverage, + }), + ..Event::default() + } +} + +fn states(timeline: &Timeline) -> Vec<(Phase, StepState)> { + timeline + .steps + .iter() + .map(|step| (step.key.phase, step.state)) + .collect() +} + +#[test] +fn plans_replace_the_forecast_and_actions_fill_them_in() { + let mut timeline = timeline(&[ + (Phase::BuildGit, "web", 30_000), + (Phase::RunJob, "migrate", 4_000), + (Phase::EnsureService, "web", 2_000), + (Phase::WaitForService, "web", 10_000), + ]); + assert_eq!( + states(&timeline), + [ + (Phase::BuildGit, StepState::Forecast), + (Phase::RunJob, StepState::Forecast), + (Phase::EnsureService, StepState::Forecast), + (Phase::WaitForService, StepState::Forecast), + ] + ); + // Each plan replaces only its own stage's forecast. + apply( + &mut timeline, + vec![planned( + PlanCoverage::Preparation, + &[key(Phase::BuildGit, "web")], + )], + ); + assert_eq!( + states(&timeline), + [ + (Phase::BuildGit, StepState::Planned), + (Phase::RunJob, StepState::Forecast), + (Phase::EnsureService, StepState::Forecast), + (Phase::WaitForService, StepState::Forecast), + ] + ); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 100), + action("action_succeeded", "a1", Phase::BuildGit, "web", 25_100), + planned( + PlanCoverage::Runtime, + &[ + key(Phase::EnsureVolume, "data"), + key(Phase::EnsureService, "web"), + ], + ), + action("action_started", "a2", Phase::EnsureVolume, "data", 25_200), + ], + ); + assert_eq!( + states(&timeline), + [ + (Phase::BuildGit, StepState::Succeeded), + (Phase::EnsureVolume, StepState::Running), + (Phase::EnsureService, StepState::Planned), + ] + ); + let build = &timeline.steps[0]; + assert_eq!( + (build.started_at_ms, build.finished_at_ms, build.expected_ms), + (Some(100), Some(25_100), Some(30_000)) + ); + assert_eq!(timeline.steps[2].expected_ms, Some(2_000)); +} + +#[test] +fn an_operation_that_ended_forecasts_nothing() { + let mut timeline = timeline(&[ + (Phase::BuildGit, "web", 30_000), + (Phase::EnsureService, "web", 2_000), + ]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 0), + action("action_failed", "a1", Phase::BuildGit, "web", 100), + ], + ); + let mut failed = timeline.operation.clone(); + failed.state = OperationState::Failed; + // Followed live, as a new read does. + timeline.set_operation(failed.clone()); + assert_eq!(states(&timeline), [(Phase::BuildGit, StepState::Failed)]); + let read = Timeline::new(failed, vec![key(Phase::EnsureService, "web")], Vec::new()); + assert_eq!(states(&read), Vec::new()); +} + +#[test] +fn retries_and_failures_stay_on_their_step() { + let mut timeline = timeline(&[]); + let mut retry = action("action_retry", "a1", Phase::EnsureService, "web", 200); + retry.diagnostic = Some(Diagnostic::from_recorded_code( + "d1".into(), + "docker_unavailable", + "Docker is unavailable".into(), + )); + let mut requested = action("action_requested", "a1", Phase::EnsureService, "web", 300); + requested.retry = Some(3); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::EnsureService, "web", 100), + retry, + ], + ); + assert_eq!(timeline.steps[0].state, StepState::Retrying); + apply( + &mut timeline, + vec![ + requested, + action("action_failed", "a1", Phase::EnsureService, "web", 400), + // A new attempt runs the same step again as its own. + action("action_started", "a2", Phase::EnsureService, "web", 500), + ], + ); + assert_eq!( + states(&timeline), + [ + (Phase::EnsureService, StepState::Failed), + (Phase::EnsureService, StepState::Running), + ] + ); + assert_eq!(timeline.steps[0].retries, 2); +} + +#[test] +fn only_a_run_whose_steps_all_succeeded_compares_with_the_usual() { + let run = |last: &str, state: OperationState| { + let mut timeline = timeline(&[ + (Phase::BuildGit, "web", 30_000), + (Phase::EnsureService, "web", 2_000), + ]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 0), + action("action_succeeded", "a1", Phase::BuildGit, "web", 5_000), + action("action_started", "a2", Phase::EnsureService, "web", 5_000), + action(last, "a2", Phase::EnsureService, "web", 6_000), + ], + ); + timeline.operation.state = state; + timeline.comparable_usual_ms() + }; + assert_eq!( + run("action_succeeded", OperationState::Succeeded), + Some(32_000) + ); + // A run that failed after 6 s is not 26 s faster than usual, even + // when it failed after its last step succeeded. + assert_eq!(run("action_failed", OperationState::Failed), None); + assert_eq!(run("action_succeeded", OperationState::Failed), None); + // Nor is one with a step it never ran before, whose usual time would + // only count its known steps. + let mut timeline = timeline(&[(Phase::BuildGit, "web", 30_000)]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 0), + action("action_succeeded", "a1", Phase::BuildGit, "web", 30_000), + action("action_started", "a2", Phase::RunJob, "migrate", 30_000), + action("action_succeeded", "a2", Phase::RunJob, "migrate", 90_000), + ], + ); + timeline.operation.state = OperationState::Succeeded; + assert_eq!(timeline.usual_ms(), Some(30_000)); + assert_eq!(timeline.comparable_usual_ms(), None); +} + +#[test] +fn sources_count_once_towards_the_time_left() { + let mut timeline = timeline(&[ + (Phase::BuildGit, "api", 30_000), + (Phase::BuildGit, "web", 20_000), + (Phase::RunJob, "migrate", 5_000), + ]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "api", 0), + action("action_started", "a2", Phase::BuildGit, "web", 0), + ], + ); + // Usually the longest source's 30 s, then the job's 5 s. + assert_eq!(timeline.usual_ms(), Some(35_000)); + // The longest source has 20 s left, then the job's 5 s. + assert_eq!(timeline.remaining_ms(10_000), Some(25_000)); + // A step running over its expectation counts as about to end. + assert_eq!(timeline.remaining_ms(40_000), Some(5_000)); +} + +fn rollout(at: i64, tasks: &[(&str, bool, TaskState)]) -> Event { + Event { + kind: "action_progressed".into(), + action_id: Some("wait".into()), + created_at_ms: at, + detail: Some(EventDetail::Rollout { + tasks: tasks + .iter() + .map(|(id, current, state)| RolloutTask { + id: (*id).into(), + slot: Some(1), + current: *current, + state: *state, + healthy: None, + }) + .collect(), + monitor_seconds: 5, + }), + ..Event::default() + } +} + +#[test] +fn rollouts_record_each_task_state_and_when_none_served() { + use TaskState::{Preparing, Running, Shutdown}; + let mut timeline = timeline(&[]); + apply( + &mut timeline, + vec![ + action("action_started", "wait", Phase::WaitForService, "web", 0), + // Stop-first: the old task stops before the new one runs. + rollout(100, &[("old", false, Running)]), + rollout(200, &[("old", false, Shutdown), ("new", true, Preparing)]), + rollout(300, &[("old", false, Shutdown), ("new", true, Preparing)]), + rollout(900, &[("old", false, Shutdown), ("new", true, Running)]), + ], + ); + let step = &timeline.steps[0]; + assert_eq!(step.monitor_seconds, Some(5)); + let lanes: Vec<_> = step + .tasks + .iter() + .map(|lane| { + let spans: Vec<_> = lane + .spans + .iter() + .map(|span| (span.state, span.from_ms)) + .collect(); + (lane.task.id.as_str(), lane.task.current, spans) + }) + .collect(); + assert_eq!( + lanes, + [ + ("old", false, vec![(Running, 100), (Shutdown, 200)]), + ("new", true, vec![(Preparing, 200), (Running, 900)]), + ] + ); + assert_eq!( + step.gaps(), + [Gap { + from_ms: 200, + to_ms: Some(900) + }] + ); + + // Start-first: the old task serves until the new one does. + let mut start_first = self::timeline(&[]); + apply( + &mut start_first, + vec![ + action("action_started", "wait", Phase::WaitForService, "web", 0), + rollout(100, &[("old", false, Running), ("new", true, Preparing)]), + rollout(500, &[("old", false, Running), ("new", true, Running)]), + rollout(600, &[("old", false, Shutdown), ("new", true, Running)]), + ], + ); + assert_eq!(start_first.steps[0].gaps(), []); + assert!(start_first.steps[0].overlapped()); + // A stop-first rollout neither overlaps, nor, when its handover + // fell between two observations, shows a gap. + assert!(!timeline.steps[0].overlapped()); + let mut unseen = self::timeline(&[]); + apply( + &mut unseen, + vec![ + action("action_started", "wait", Phase::WaitForService, "web", 0), + rollout(100, &[("old", false, Running)]), + rollout(500, &[("old", false, Shutdown), ("new", true, Running)]), + ], + ); + assert_eq!( + (unseen.steps[0].gaps(), unseen.steps[0].overlapped()), + (vec![], false) + ); +} + +#[test] +fn rollouts_summarize_their_new_tasks_monitor_window_and_downtime() { + use TaskState::{Preparing, Running, Shutdown}; + let mut timeline = timeline(&[]); + apply( + &mut timeline, + vec![ + action("action_started", "wait", Phase::WaitForService, "web", 0), + rollout(100, &[("old", false, Running)]), + rollout(200, &[("old", false, Shutdown), ("new", true, Preparing)]), + ], + ); + let step = &timeline.steps[0]; + let tasks = step.new_tasks().unwrap(); + assert_eq!( + tasks, + NewTasks { + running: 0, + total: 1 + } + ); + assert_eq!(tasks.to_string(), "0/1 new task running"); + // Down since the old task stopped, and still. + let down = Downtime { + ms: 800, + ongoing: true, + }; + assert_eq!(step.downtime(1_000), Some(down)); + assert_eq!(step.monitor(1_000), None); + + apply( + &mut timeline, + vec![rollout( + 2_000, + &[("old", false, Shutdown), ("new", true, Running)], + )], + ); + let step = &timeline.steps[0]; + assert_eq!(step.new_tasks().unwrap().running, 1); + // Swarm watches the new task for 5 s from when it ran. + let window = Window { + from_ms: 2_000, + to_ms: 7_000, + }; + assert_eq!(step.monitor(3_000), Some(window)); + assert_eq!(window.left_ms(3_000), 4_000); + assert_eq!(step.monitor(7_000), None); + let down = Downtime { + ms: 1_800, + ongoing: false, + }; + assert_eq!(step.downtime(9_000), Some(down)); + + // Once the step ended, no window is open. + apply( + &mut timeline, + vec![action( + "action_succeeded", + "wait", + Phase::WaitForService, + "web", + 4_000, + )], + ); + assert_eq!(timeline.steps[0].monitor(3_000), None); +} + +#[test] +fn another_attempt_starts_over() { + let mut timeline = timeline(&[]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 1), + action("action_failed", "a1", Phase::BuildGit, "web", 2), + ], + ); + // Requested again, its latest attempt is the run before. + let mut requested = timeline.operation.clone(); + requested.state = OperationState::Requested; + timeline.set_operation(requested.clone()); + assert_eq!(timeline.steps.len(), 0, "{:?}", timeline.steps); + let mut retried = requested; + retried.state = OperationState::Running; + retried.attempt = 2; + timeline.set_operation(retried); + // Events of the earlier attempt no longer apply. + let mut late = action("action_started", "a3", Phase::EnsureService, "web", 3); + late.id = timeline.cursor + 1; + late.operation_id = Some("op".into()); + late.attempt = Some(1); + timeline.apply(&late); + assert_eq!(timeline.steps.len(), 0); +} + +#[test] +fn a_requested_operation_shows_none_of_its_previous_run() { + let mut timeline = timeline(&[(Phase::EnsureService, "web", 2_000)]); + timeline.operation.state = OperationState::Requested; + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::EnsureService, "web", 1), + action("action_succeeded", "a1", Phase::EnsureService, "web", 2), + ], + ); + assert_eq!( + states(&timeline), + [(Phase::EnsureService, StepState::Forecast)] + ); +} + +#[test] +fn only_noticeably_unusual_durations_are_flagged() { + let mut timeline = timeline(&[ + (Phase::BuildGit, "api", 30_000), + (Phase::BuildGit, "web", 20_000), + (Phase::EnsureService, "api", 1_000), + ]); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "api", 0), + action("action_started", "a2", Phase::BuildGit, "web", 0), + action("action_succeeded", "a1", Phase::BuildGit, "api", 50_000), + action("action_succeeded", "a2", Phase::BuildGit, "web", 21_000), + action("action_started", "a3", Phase::EnsureService, "api", 50_000), + ], + ); + let unusual: Vec<_> = timeline.steps.iter().map(Step::unusual_ms).collect(); + // 20 s over its 30 s is unusual; 1 s over 20 s is not. + assert_eq!(unusual, [Some(30_000), None, None]); + // The sources build at once, then the service updates. + assert_eq!(timeline.usual_ms(), Some(31_000)); +} + +#[test] +fn events_already_applied_or_of_other_operations_are_ignored() { + let mut timeline = timeline(&[]); + apply( + &mut timeline, + vec![action( + "action_started", + "a1", + Phase::EnsureService, + "web", + 1, + )], + ); + let mut replayed = action("action_succeeded", "a1", Phase::EnsureService, "web", 2); + replayed.id = timeline.cursor; + replayed.operation_id = Some("op".into()); + timeline.apply(&replayed); + let mut other = action("action_succeeded", "a1", Phase::EnsureService, "web", 2); + other.id = timeline.cursor + 1; + other.operation_id = Some("other".into()); + timeline.apply(&other); + assert_eq!(timeline.steps[0].state, StepState::Running); +} + +#[test] +fn progress_counts_from_the_first_start_and_rounds_down() { + let mut timeline = timeline(&[ + (Phase::BuildGit, "web", 30_000), + (Phase::RunJob, "migrate", 4_000), + (Phase::EnsureService, "web", 2_000), + ]); + timeline.operation.state = OperationState::Requested; + timeline.operation.started_at_ms = None; + let queued = Progress::new(&timeline, 1_000); + assert_eq!( + (queued.status(), queued.steps(), queued.percent()), + ("Queued", "0/3".into(), 0) + ); + assert_eq!(queued.elapsed_ms, None); + + // The operation's own start trails its first step's. + timeline.operation.state = OperationState::Running; + timeline.operation.started_at_ms = Some(2_000); + apply( + &mut timeline, + vec![ + action("action_started", "a1", Phase::BuildGit, "web", 1_000), + action("action_succeeded", "a1", Phase::BuildGit, "web", 11_000), + action("action_started", "a2", Phase::RunJob, "migrate", 11_000), + ], + ); + let running = Progress::new(&timeline, 13_000); + assert_eq!(running.status(), "Deploying"); + assert_eq!(running.running, ["Run job migrate"]); + assert_eq!(running.elapsed_ms, Some(12_000)); + // One step of three: 33 %, and 4 of a 12-cell bar. + assert_eq!((running.percent(), running.filled(12)), (33, 4)); + // The job has 2 s left, then the service's 2 s. + assert_eq!(running.outlook().as_deref(), Some("~4.0 s left")); +} + +#[test] +fn progress_of_no_steps_is_none_done() { + let progress = Progress::new(&timeline(&[]), 0); + assert_eq!((progress.percent(), progress.filled(12)), (0, 0)); + assert_eq!(progress.steps(), "0/0"); +} + +#[test] +fn progress_names_its_state_by_kind() { + let mut timeline = timeline(&[]); + let status = |timeline: &Timeline| Progress::new(timeline, 0).status(); + timeline.operation.kind = OperationKind::Delete; + assert_eq!(status(&timeline), "Deleting"); + timeline.operation.state = OperationState::Succeeded; + assert_eq!(status(&timeline), "Deleted"); + timeline.operation.kind = OperationKind::Apply; + assert_eq!(status(&timeline), "Deployed"); + timeline.operation.state = OperationState::Superseded; + assert_eq!(status(&timeline), "Superseded"); +} + +#[test] +fn progress_tells_the_time_left_then_against_the_usual() { + let mut progress = Progress { + kind: OperationKind::Apply, + state: OperationState::Running, + done: 4, + total: 9, + running: vec!["Build web".into()], + elapsed_ms: Some(30_000), + left_ms: Some(48_000), + usual_ms: Some(80_000), + }; + assert_eq!(progress.steps(), "4/9"); + assert_eq!(progress.outlook().as_deref(), Some("~48.0 s left")); + progress.state = OperationState::Succeeded; + for (elapsed, outlook) in [ + (74_000, "6.0 s faster than usual"), + (79_001, "as long as usual"), + (80_999, "as long as usual"), + (81_000, "1.0 s slower than usual"), + ] { + progress.elapsed_ms = Some(elapsed); + assert_eq!(progress.outlook().as_deref(), Some(outlook), "{elapsed}"); + } + // A run that is not comparable with the usual one says nothing. + progress.usual_ms = None; + assert_eq!(progress.outlook(), None); +} diff --git a/crates/piqueld-core/src/urls.rs b/crates/piqueld-core/src/urls.rs deleted file mode 100644 index 4302f3531..000000000 --- a/crates/piqueld-core/src/urls.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! The URLs of an environment's rendered routes and whether each is ready, -//! derived only from state the daemon already observes. Clients read the -//! result; none probes a URL or computes readiness itself. -use crate::api::{DnsRecordState, IngressStatus, ObservedServiceView, PublicIngressStatus}; -use crate::manifest::{RouteTarget, ValidatedRoute, Visibility}; -use crate::names::string_enum; -use crate::{Convergence, RouteName, ServiceName}; -use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; - -string_enum! { - #[serde] - /// Whether a URL is reachable. A known URL is not a ready one. - pub enum UrlState { - /// At least one condition in `pending` holds. - Pending => "pending", - /// Served by the gateway over verified HTTPS, with its DNS records in - /// place and its service healthy. - Ready => "ready", - } -} - -/// A condition that keeps a URL pending. -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] -#[serde(tag = "condition", rename_all = "snake_case")] -pub enum UrlCondition { - /// The gateway has not acknowledged this exact route yet. - Ingress, - /// HTTPS, with the route's certificate, is not verified for this route: - /// its listener is unhealthy now, or the daemon's latest route check - /// failed or has not run since the route changed. - Https { - /// Why, from the route's status. - message: String, - }, - /// The hostname's managed DNS records are not in place. - Dns { - /// `pending` or `dns_conflict`. - state: DnsRecordState, - }, - /// The route's service is not observed healthy. - Service { - /// The route's service. - service: ServiceName, - }, -} - -/// What the condition waits for: `ingress`, `HTTPS ()`, -/// `DNS pending`, or `service web`. -impl std::fmt::Display for UrlCondition { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Ingress => formatter.write_str("ingress"), - Self::Https { message } => write!(formatter, "HTTPS ({message})"), - Self::Dns { state } => write!(formatter, "DNS {state}"), - Self::Service { service } => write!(formatter, "service {service}"), - } - } -} - -/// One URL of a rendered route, and whether it is ready. -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] -pub struct RouteUrl { - /// The route's name, when it has one. - #[serde(default)] - pub name: Option, - /// `https://` and the rendered hostname. - pub url: String, - /// Effective visibility: `private` URLs are reachable only from the tailnet. - pub visibility: Visibility, - /// Backend service or redirect. - #[serde(flatten)] - pub target: RouteTarget, - /// `ready` exactly when `pending` is empty. - pub state: UrlState, - /// Every condition that keeps the URL pending, in the order above. - pub pending: Vec, -} - -impl RouteUrl { - /// Derives a rendered route's URL and state. It is ready when: - /// - /// 1. the gateway acknowledged this exact route (`applied`); - /// 2. the listener serving its visibility is enabled and healthy now - /// (`ingress`), and - /// the daemon's latest check of this route (same hostname, visibility, - /// and target in `ingress.routes`) found it `ready`: DNS resolves to - /// that listener, which serves it with a trusted certificate; - /// 3. its DNS records are not `pending` or `dns_conflict`; - /// 4. its service, unless it redirects, is observed healthy. - #[must_use] - pub fn derive( - route: &ValidatedRoute, - applied: &[ValidatedRoute], - ingress: &IngressStatus, - services: &[ObservedServiceView], - ) -> Self { - let status = ingress.routes.iter().find(|status| { - status.hostname == route.hostname.as_str() - && status.visibility == route.visibility - && status.target == route.target - }); - let mut pending = Vec::new(); - if !applied.contains(route) { - pending.push(UrlCondition::Ingress); - } - // A disabled listener never serves the route, checked or not. A - // listener failure observed since the route's check outdates it; - // other applications' network failures do not. - let listener = match (route.visibility, &ingress.public) { - _ if !ingress.enabled => Some("Ingress is disabled in daemon configuration"), - (Visibility::Private, _) if !ingress.private.enabled => { - Some("Private ingress is disabled in daemon configuration") - } - (Visibility::Public, _) if !ingress.gateway => Some(ingress.message.as_str()), - ( - Visibility::Public, - PublicIngressStatus::Tunnel { - connected: false, - message, - .. - }, - ) => Some(message.as_str()), - (Visibility::Public, _) => None, - (Visibility::Private, _) => { - (!ingress.private.healthy).then_some(ingress.private.message.as_str()) - } - }; - let https = match status { - _ if listener.is_some_and(str::is_empty) => Some("Its listener is unavailable".into()), - _ if let Some(message) = listener => Some(message.to_owned()), - Some(status) if status.state == "ready" => None, - Some(status) => Some(status.message.clone()), - None => Some( - "Not checked yet: the daemon verifies HTTPS once the gateway serves the route" - .into(), - ), - }; - if let Some(message) = https { - pending.push(UrlCondition::Https { message }); - } - if let Some(status) = status - && matches!( - status.dns_state, - DnsRecordState::Pending | DnsRecordState::DnsConflict - ) - { - pending.push(UrlCondition::Dns { - state: status.dns_state, - }); - } - if let Some(service) = route.target.service() - && !services - .iter() - .any(|observed| observed.name == service.as_str() && observed.healthy()) - { - pending.push(UrlCondition::Service { - service: service.clone(), - }); - } - Self { - name: route.name.clone(), - url: format!("https://{}", route.hostname), - visibility: route.visibility, - target: route.target.clone(), - state: if pending.is_empty() { - UrlState::Ready - } else { - UrlState::Pending - }, - pending, - } - } - - /// What keeps it pending, e.g. `ingress, DNS pending`; empty once ready. - #[must_use] - pub fn waiting_for(&self) -> String { - self.pending - .iter() - .map(ToString::to_string) - .collect::>() - .join(", ") - } -} - -impl ObservedServiceView { - /// Whether the runtime reports every desired replica running and healthy. - #[must_use] - pub fn healthy(&self) -> bool { - self.convergence == Convergence::Converged && self.healthy_replicas >= self.desired_replicas - } -} - -#[cfg(test)] -mod tests { - use super::{RouteUrl, UrlCondition, UrlState}; - use crate::api::{ - DnsRecordState, DnsRecords, IngressStatus, ObservedServiceView, PublicIngressStatus, - RouteStatus, - }; - use crate::manifest::{RouteTarget, ValidatedRoute, Visibility}; - use crate::{Convergence, RouteName, ServiceName}; - - fn route() -> ValidatedRoute { - ValidatedRoute { - hostname: crate::manifest::RouteHostname::parse("notes.example.com").unwrap(), - name: Some(RouteName::parse("web").unwrap()), - visibility: Visibility::Public, - target: RouteTarget::Service { - service: ServiceName::parse("web").unwrap(), - port: 3000.try_into().unwrap(), - }, - } - } - - fn status(route: &ValidatedRoute) -> RouteStatus { - RouteStatus { - environment_id: "app-notes-01".into(), - name: route.name.clone(), - hostname: route.hostname.to_string(), - visibility: route.visibility, - dns: DnsRecords::ServerAddresses { - addresses: Vec::new(), - }, - dns_state: DnsRecordState::Managed, - target: route.target.clone(), - state: "ready".into(), - message: "verified".into(), - } - } - - fn service(convergence: Convergence, healthy_replicas: u16) -> ObservedServiceView { - ObservedServiceView { - name: "web".into(), - image: None, - desired_replicas: 2, - observed_replicas: 2, - healthy_replicas, - convergence, - diagnostics: Vec::new(), - } - } - - /// Derives the URL with one input changed from a ready baseline. - fn derive( - change: impl FnOnce(&mut Vec, &mut IngressStatus, &mut Vec), - ) -> RouteUrl { - let route = route(); - let (mut applied, mut ingress, mut services) = ( - vec![route.clone()], - ingress(status(&route)), - vec![service(Convergence::Converged, 2)], - ); - change(&mut applied, &mut ingress, &mut services); - RouteUrl::derive(&route, &applied, &ingress, &services) - } - - /// Healthy listeners with one route status. - fn ingress(status: RouteStatus) -> IngressStatus { - let mut ingress = IngressStatus { - enabled: true, - healthy: true, - gateway: true, - routes: vec![status], - ..IngressStatus::default() - }; - ingress.private.healthy = true; - ingress - } - - #[test] - fn a_url_is_ready_only_when_every_condition_holds() { - let ready = derive(|_, _, _| {}); - assert_eq!(ready.state, UrlState::Ready); - assert_eq!(ready.url, "https://notes.example.com"); - assert_eq!(ready.name.unwrap().as_str(), "web"); - assert_eq!(ready.pending, []); - } - - fn https(message: &str) -> UrlCondition { - UrlCondition::Https { - message: message.into(), - } - } - - /// Asserts each case's URL waits for exactly its conditions. - fn assert_pending(cases: [(&str, RouteUrl, Vec); N]) { - for (case, url, pending) in cases { - let state = if pending.is_empty() { - UrlState::Ready - } else { - UrlState::Pending - }; - assert_eq!(url.state, state, "{case}"); - assert_eq!(url.pending, pending, "{case}"); - } - } - - #[test] - fn listener_problems_outdate_route_checks() { - assert_pending([ - ( - "gateway failed since the route was checked", - derive(|_, ingress, _| { - ingress.gateway = false; - ingress.message = "gateway down".into(); - }), - vec![https("gateway down")], - ), - ( - "tunnel disconnected since the route was checked", - derive(|_, ingress, _| { - ingress.public = PublicIngressStatus::Tunnel { - id: "tunnel".into(), - connected: false, - message: "tunnel disconnected".into(), - }; - }), - vec![https("tunnel disconnected")], - ), - ( - "ingress disabled, before the route was checked", - derive(|_, ingress, _| { - ingress.enabled = false; - ingress.routes.clear(); - }), - vec![https("Ingress is disabled in daemon configuration")], - ), - ( - "another application's network failed", - derive(|_, ingress, _| ingress.healthy = false), - vec![], - ), - ]); - } - - #[test] - fn each_condition_keeps_a_url_pending() { - let unchecked = - https("Not checked yet: the daemon verifies HTTPS once the gateway serves the route"); - let web = UrlCondition::Service { - service: ServiceName::parse("web").unwrap(), - }; - let cases: [(&str, RouteUrl, Vec); 9] = [ - ( - "not applied by the gateway", - derive(|applied, _, _| applied.clear()), - vec![UrlCondition::Ingress], - ), - ( - "a different route was applied under the hostname", - derive(|applied, _, _| applied[0].visibility = Visibility::Private), - vec![UrlCondition::Ingress], - ), - ( - "HTTPS not verified", - derive(|_, ingress, _| { - ingress.routes[0].state = "pending".into(); - ingress.routes[0].message = "no certificate".into(); - }), - vec![https("no certificate")], - ), - ( - "never checked", - derive(|_, ingress, _| ingress.routes.clear()), - vec![unchecked.clone()], - ), - ( - "checked before its target changed", - derive(|_, ingress, _| { - ingress.routes[0].target = RouteTarget::Service { - service: ServiceName::parse("api").unwrap(), - port: 80.try_into().unwrap(), - }; - }), - vec![unchecked], - ), - ( - "DNS records pending", - derive(|_, ingress, _| ingress.routes[0].dns_state = DnsRecordState::Pending), - vec![UrlCondition::Dns { - state: DnsRecordState::Pending, - }], - ), - ( - "DNS conflict", - derive(|_, ingress, _| ingress.routes[0].dns_state = DnsRecordState::DnsConflict), - vec![UrlCondition::Dns { - state: DnsRecordState::DnsConflict, - }], - ), - ( - "service degraded", - derive(|_, _, services| services[0] = service(Convergence::Degraded, 1)), - vec![web.clone()], - ), - ( - "service not observed", - derive(|_, _, services| services.clear()), - vec![web], - ), - ]; - assert_pending(cases); - } - - #[test] - fn redirects_need_no_service_and_manual_dns_is_not_pending() { - let mut redirect = route(); - redirect.target = RouteTarget::Redirect { - redirect: serde_json::from_value( - serde_json::json!({"to": "https://example.com", "status": 308, "preserve_path": true}), - ) - .unwrap(), - }; - let mut status = status(&redirect); - status.dns_state = DnsRecordState::Manual; - let url = RouteUrl::derive( - &redirect, - std::slice::from_ref(&redirect), - &ingress(status), - &[], - ); - assert_eq!(url.state, UrlState::Ready); - } -} diff --git a/crates/piqueld-core/src/urls/mod.rs b/crates/piqueld-core/src/urls/mod.rs new file mode 100644 index 000000000..fec966a36 --- /dev/null +++ b/crates/piqueld-core/src/urls/mod.rs @@ -0,0 +1,195 @@ +//! The URLs of an environment's rendered routes and whether each is ready, +//! derived only from state the daemon already observes. Clients read the +//! result; none probes a URL or computes readiness itself. +use crate::api::{DnsRecordState, IngressStatus, ObservedServiceView, PublicIngressStatus}; +use crate::manifest::{RouteTarget, ValidatedRoute, Visibility}; +use crate::names::string_enum; +use crate::{Convergence, RouteName, ServiceName}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +string_enum! { + #[serde] + /// Whether a URL is reachable. A known URL is not a ready one. + pub enum UrlState { + /// At least one condition in `pending` holds. + Pending => "pending", + /// Served by the gateway over verified HTTPS, with its DNS records in + /// place and its service healthy. + Ready => "ready", + } +} + +/// A condition that keeps a URL pending. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] +#[serde(tag = "condition", rename_all = "snake_case")] +pub enum UrlCondition { + /// The gateway has not acknowledged this exact route yet. + Ingress, + /// HTTPS, with the route's certificate, is not verified for this route: + /// its listener is unhealthy now, or the daemon's latest route check + /// failed or has not run since the route changed. + Https { + /// Why, from the route's status. + message: String, + }, + /// The hostname's managed DNS records are not in place. + Dns { + /// `pending` or `dns_conflict`. + state: DnsRecordState, + }, + /// The route's service is not observed healthy. + Service { + /// The route's service. + service: ServiceName, + }, +} + +/// What the condition waits for: `ingress`, `HTTPS ()`, +/// `DNS pending`, or `service web`. +impl std::fmt::Display for UrlCondition { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Ingress => formatter.write_str("ingress"), + Self::Https { message } => write!(formatter, "HTTPS ({message})"), + Self::Dns { state } => write!(formatter, "DNS {state}"), + Self::Service { service } => write!(formatter, "service {service}"), + } + } +} + +/// One URL of a rendered route, and whether it is ready. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] +pub struct RouteUrl { + /// The route's name, when it has one. + #[serde(default)] + pub name: Option, + /// `https://` and the rendered hostname. + pub url: String, + /// Effective visibility: `private` URLs are reachable only from the tailnet. + pub visibility: Visibility, + /// Backend service or redirect. + #[serde(flatten)] + pub target: RouteTarget, + /// `ready` exactly when `pending` is empty. + pub state: UrlState, + /// Every condition that keeps the URL pending, in the order above. + pub pending: Vec, +} + +impl RouteUrl { + /// Derives a rendered route's URL and state. It is ready when: + /// + /// 1. the gateway acknowledged this exact route (`applied`); + /// 2. the listener serving its visibility is enabled and healthy now + /// (`ingress`), and + /// the daemon's latest check of this route (same hostname, visibility, + /// and target in `ingress.routes`) found it `ready`: DNS resolves to + /// that listener, which serves it with a trusted certificate; + /// 3. its DNS records are not `pending` or `dns_conflict`; + /// 4. its service, unless it redirects, is observed healthy. + #[must_use] + pub fn derive( + route: &ValidatedRoute, + applied: &[ValidatedRoute], + ingress: &IngressStatus, + services: &[ObservedServiceView], + ) -> Self { + let status = ingress.routes.iter().find(|status| { + status.hostname == route.hostname.as_str() + && status.visibility == route.visibility + && status.target == route.target + }); + let mut pending = Vec::new(); + if !applied.contains(route) { + pending.push(UrlCondition::Ingress); + } + // A disabled listener never serves the route, checked or not. A + // listener failure observed since the route's check outdates it; + // other applications' network failures do not. + let listener = match (route.visibility, &ingress.public) { + _ if !ingress.enabled => Some("Ingress is disabled in daemon configuration"), + (Visibility::Private, _) if !ingress.private.enabled => { + Some("Private ingress is disabled in daemon configuration") + } + (Visibility::Public, _) if !ingress.gateway => Some(ingress.message.as_str()), + ( + Visibility::Public, + PublicIngressStatus::Tunnel { + connected: false, + message, + .. + }, + ) => Some(message.as_str()), + (Visibility::Public, _) => None, + (Visibility::Private, _) => { + (!ingress.private.healthy).then_some(ingress.private.message.as_str()) + } + }; + let https = match status { + _ if listener.is_some_and(str::is_empty) => Some("Its listener is unavailable".into()), + _ if let Some(message) = listener => Some(message.to_owned()), + Some(status) if status.state == "ready" => None, + Some(status) => Some(status.message.clone()), + None => Some( + "Not checked yet: the daemon verifies HTTPS once the gateway serves the route" + .into(), + ), + }; + if let Some(message) = https { + pending.push(UrlCondition::Https { message }); + } + if let Some(status) = status + && matches!( + status.dns_state, + DnsRecordState::Pending | DnsRecordState::DnsConflict + ) + { + pending.push(UrlCondition::Dns { + state: status.dns_state, + }); + } + if let Some(service) = route.target.service() + && !services + .iter() + .any(|observed| observed.name == service.as_str() && observed.healthy()) + { + pending.push(UrlCondition::Service { + service: service.clone(), + }); + } + Self { + name: route.name.clone(), + url: format!("https://{}", route.hostname), + visibility: route.visibility, + target: route.target.clone(), + state: if pending.is_empty() { + UrlState::Ready + } else { + UrlState::Pending + }, + pending, + } + } + + /// What keeps it pending, e.g. `ingress, DNS pending`; empty once ready. + #[must_use] + pub fn waiting_for(&self) -> String { + self.pending + .iter() + .map(ToString::to_string) + .collect::>() + .join(", ") + } +} + +impl ObservedServiceView { + /// Whether the runtime reports every desired replica running and healthy. + #[must_use] + pub fn healthy(&self) -> bool { + self.convergence == Convergence::Converged && self.healthy_replicas >= self.desired_replicas + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/piqueld-core/src/urls/tests.rs b/crates/piqueld-core/src/urls/tests.rs new file mode 100644 index 000000000..c93270d37 --- /dev/null +++ b/crates/piqueld-core/src/urls/tests.rs @@ -0,0 +1,229 @@ +use super::{RouteUrl, UrlCondition, UrlState}; +use crate::api::{ + DnsRecordState, DnsRecords, IngressStatus, ObservedServiceView, PublicIngressStatus, + RouteStatus, +}; +use crate::manifest::{RouteTarget, ValidatedRoute, Visibility}; +use crate::{Convergence, RouteName, ServiceName}; + +fn route() -> ValidatedRoute { + ValidatedRoute { + hostname: crate::manifest::RouteHostname::parse("notes.example.com").unwrap(), + name: Some(RouteName::parse("web").unwrap()), + visibility: Visibility::Public, + target: RouteTarget::Service { + service: ServiceName::parse("web").unwrap(), + port: 3000.try_into().unwrap(), + }, + } +} + +fn status(route: &ValidatedRoute) -> RouteStatus { + RouteStatus { + environment_id: "app-notes-01".into(), + name: route.name.clone(), + hostname: route.hostname.to_string(), + visibility: route.visibility, + dns: DnsRecords::ServerAddresses { + addresses: Vec::new(), + }, + dns_state: DnsRecordState::Managed, + target: route.target.clone(), + state: "ready".into(), + message: "verified".into(), + } +} + +fn service(convergence: Convergence, healthy_replicas: u16) -> ObservedServiceView { + ObservedServiceView { + name: "web".into(), + image: None, + desired_replicas: 2, + observed_replicas: 2, + healthy_replicas, + convergence, + diagnostics: Vec::new(), + } +} + +/// Derives the URL with one input changed from a ready baseline. +fn derive( + change: impl FnOnce(&mut Vec, &mut IngressStatus, &mut Vec), +) -> RouteUrl { + let route = route(); + let (mut applied, mut ingress, mut services) = ( + vec![route.clone()], + ingress(status(&route)), + vec![service(Convergence::Converged, 2)], + ); + change(&mut applied, &mut ingress, &mut services); + RouteUrl::derive(&route, &applied, &ingress, &services) +} + +/// Healthy listeners with one route status. +fn ingress(status: RouteStatus) -> IngressStatus { + let mut ingress = IngressStatus { + enabled: true, + healthy: true, + gateway: true, + routes: vec![status], + ..IngressStatus::default() + }; + ingress.private.healthy = true; + ingress +} + +#[test] +fn a_url_is_ready_only_when_every_condition_holds() { + let ready = derive(|_, _, _| {}); + assert_eq!(ready.state, UrlState::Ready); + assert_eq!(ready.url, "https://notes.example.com"); + assert_eq!(ready.name.unwrap().as_str(), "web"); + assert_eq!(ready.pending, []); +} + +fn https(message: &str) -> UrlCondition { + UrlCondition::Https { + message: message.into(), + } +} + +/// Asserts each case's URL waits for exactly its conditions. +fn assert_pending(cases: [(&str, RouteUrl, Vec); N]) { + for (case, url, pending) in cases { + let state = if pending.is_empty() { + UrlState::Ready + } else { + UrlState::Pending + }; + assert_eq!(url.state, state, "{case}"); + assert_eq!(url.pending, pending, "{case}"); + } +} + +#[test] +fn listener_problems_outdate_route_checks() { + assert_pending([ + ( + "gateway failed since the route was checked", + derive(|_, ingress, _| { + ingress.gateway = false; + ingress.message = "gateway down".into(); + }), + vec![https("gateway down")], + ), + ( + "tunnel disconnected since the route was checked", + derive(|_, ingress, _| { + ingress.public = PublicIngressStatus::Tunnel { + id: "tunnel".into(), + connected: false, + message: "tunnel disconnected".into(), + }; + }), + vec![https("tunnel disconnected")], + ), + ( + "ingress disabled, before the route was checked", + derive(|_, ingress, _| { + ingress.enabled = false; + ingress.routes.clear(); + }), + vec![https("Ingress is disabled in daemon configuration")], + ), + ( + "another application's network failed", + derive(|_, ingress, _| ingress.healthy = false), + vec![], + ), + ]); +} + +#[test] +fn each_condition_keeps_a_url_pending() { + let unchecked = + https("Not checked yet: the daemon verifies HTTPS once the gateway serves the route"); + let web = UrlCondition::Service { + service: ServiceName::parse("web").unwrap(), + }; + let cases: [(&str, RouteUrl, Vec); 9] = [ + ( + "not applied by the gateway", + derive(|applied, _, _| applied.clear()), + vec![UrlCondition::Ingress], + ), + ( + "a different route was applied under the hostname", + derive(|applied, _, _| applied[0].visibility = Visibility::Private), + vec![UrlCondition::Ingress], + ), + ( + "HTTPS not verified", + derive(|_, ingress, _| { + ingress.routes[0].state = "pending".into(); + ingress.routes[0].message = "no certificate".into(); + }), + vec![https("no certificate")], + ), + ( + "never checked", + derive(|_, ingress, _| ingress.routes.clear()), + vec![unchecked.clone()], + ), + ( + "checked before its target changed", + derive(|_, ingress, _| { + ingress.routes[0].target = RouteTarget::Service { + service: ServiceName::parse("api").unwrap(), + port: 80.try_into().unwrap(), + }; + }), + vec![unchecked], + ), + ( + "DNS records pending", + derive(|_, ingress, _| ingress.routes[0].dns_state = DnsRecordState::Pending), + vec![UrlCondition::Dns { + state: DnsRecordState::Pending, + }], + ), + ( + "DNS conflict", + derive(|_, ingress, _| ingress.routes[0].dns_state = DnsRecordState::DnsConflict), + vec![UrlCondition::Dns { + state: DnsRecordState::DnsConflict, + }], + ), + ( + "service degraded", + derive(|_, _, services| services[0] = service(Convergence::Degraded, 1)), + vec![web.clone()], + ), + ( + "service not observed", + derive(|_, _, services| services.clear()), + vec![web], + ), + ]; + assert_pending(cases); +} + +#[test] +fn redirects_need_no_service_and_manual_dns_is_not_pending() { + let mut redirect = route(); + redirect.target = RouteTarget::Redirect { + redirect: serde_json::from_value( + serde_json::json!({"to": "https://example.com", "status": 308, "preserve_path": true}), + ) + .unwrap(), + }; + let mut status = status(&redirect); + status.dns_state = DnsRecordState::Manual; + let url = RouteUrl::derive( + &redirect, + std::slice::from_ref(&redirect), + &ingress(status), + &[], + ); + assert_eq!(url.state, UrlState::Ready); +}