1use crate::{ObservedInventoryBatch, Platform, ResourceHeartbeat, StackState};
4use alien_error::AlienError;
5use bon::Builder;
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10use super::{DeploymentStatus, EnvironmentInfo, ReleaseInfo};
11
12#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub enum InitialSetupAuthority {
17 #[default]
20 ImportedHandoff,
21 DirectSetup,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct SetupUpdateAuthorization {
30 pub nonce: String,
32 pub baseline_frozen_digest: String,
35 pub target_frozen_digest: String,
38 pub release_id: String,
40 pub setup_target: String,
42 pub setup_fingerprint: String,
44 pub setup_fingerprint_version: u32,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
51#[serde(rename_all = "camelCase")]
52pub struct SetupReportRefusal {
53 pub reason: String,
55 pub reported_release_id: String,
57 pub at: chrono::DateTime<chrono::Utc>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
66#[serde(rename_all = "camelCase")]
67pub struct CloudSetupRequired {
68 pub release_id: String,
70 pub reason: String,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
78#[serde(rename_all = "camelCase")]
79pub struct InstalledHelmRelease {
80 pub name: String,
82 pub namespace: String,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
88#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
89#[serde(rename_all = "camelCase")]
90pub struct CredentialRetry {
91 pub started_at: chrono::DateTime<chrono::Utc>,
93 pub status: DeploymentStatus,
95}
96
97#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
100#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
101#[serde(rename_all = "camelCase")]
102pub enum DeletionPolicy {
103 #[default]
104 Retain,
105 Erase,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
111#[serde(rename_all = "camelCase")]
112pub struct AirgappedReportMetadata {
113 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub written_at: Option<chrono::DateTime<chrono::Utc>>,
116 pub received_at: chrono::DateTime<chrono::Utc>,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
124#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
125#[serde(rename_all = "camelCase")]
126pub struct RuntimeMetadata {
127 #[serde(default)]
129 pub deletion_policy: DeletionPolicy,
130
131 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub airgapped_report: Option<AirgappedReportMetadata>,
134
135 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub operator_version: Option<String>,
140
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub credential_retry: Option<CredentialRetry>,
144
145 #[serde(default)]
148 pub initial_setup_authority: InitialSetupAuthority,
149
150 #[serde(default, skip_serializing_if = "super::is_false")]
153 pub automatic_setup: bool,
154
155 #[serde(default, skip_serializing_if = "super::is_false")]
161 pub first_setup_machines_unselected: bool,
162
163 #[serde(skip_serializing_if = "Option::is_none")]
166 pub last_synced_env_vars_hash: Option<String>,
167
168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
172 pub last_synced_secret_names: Vec<String>,
173
174 #[serde(default, skip_serializing_if = "is_false")]
178 pub vault_credentials_revoked: bool,
179
180 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub retained_storage_protection_hash: Option<String>,
186
187 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub retained_storage_protection_confirmed_at: Option<chrono::DateTime<chrono::Utc>>,
191
192 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub retained_data_protection_started_at: Option<chrono::DateTime<chrono::Utc>>,
196
197 #[serde(skip_serializing_if = "Option::is_none")]
201 pub prepared_stack: Option<crate::Stack>,
202
203 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
211 pub persisted_gate_answers: GateAnswers,
212
213 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub pending_prepared_stack: Option<crate::Stack>,
217
218 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub pending_prepared_release_id: Option<String>,
224
225 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub setup_update_authorization: Option<SetupUpdateAuthorization>,
229
230 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub setup_report_refusal: Option<SetupReportRefusal>,
234
235 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub cloud_setup_required: Option<CloudSetupRequired>,
239
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub installed_helm_release: Option<InstalledHelmRelease>,
243
244 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub direct_setup_revision: Option<String>,
249
250 #[serde(default, skip_serializing_if = "is_false")]
255 pub registry_access_granted: bool,
256
257 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub registry_access: Option<RegistryAccess>,
262
263 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
266 pub setup_scaffolding: BTreeMap<String, SetupScaffolding>,
267
268 #[serde(default, skip_serializing_if = "Vec::is_empty")]
272 pub deployer_secrets: Vec<crate::DeployerSecretReport>,
273
274 #[serde(default, skip_serializing_if = "Vec::is_empty")]
278 pub ai_access_checks: Vec<AiAccessCheck>,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub deployer_secrets_checked_at: Option<chrono::DateTime<chrono::Utc>>,
284
285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 pub resources_waiting_for_secrets: Vec<String>,
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
295#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
296#[serde(rename_all = "camelCase")]
297pub struct AiAccessCheck {
298 pub resource_id: String,
300 pub model_id: String,
302 pub result: AiAccessCheckResult,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub detail: Option<String>,
307 pub tested_at: chrono::DateTime<chrono::Utc>,
308}
309
310#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
311#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
312#[serde(rename_all = "kebab-case")]
313pub enum AiAccessCheckResult {
314 Verified,
315 Refused,
316 NotChecked,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
321#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
322#[serde(rename_all = "camelCase", tag = "type")]
323pub enum SetupScaffolding {
324 #[serde(rename_all = "camelCase")]
326 AwsSandbox {
327 build_role_name: String,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 egress: Option<AwsSandboxEgressScaffolding>,
332 #[serde(default, skip_serializing_if = "Option::is_none")]
335 image_arn: Option<String>,
336 },
337}
338
339#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
342#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
343#[serde(rename_all = "camelCase")]
344pub struct AwsSandboxEgressScaffolding {
345 pub operator_role_name: String,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub security_group_id: Option<String>,
350 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub connector_arn: Option<String>,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
356 pub connector_request: Option<String>,
357}
358
359impl SetupScaffolding {
360 pub fn fill_missing(&mut self, found: SetupScaffolding) {
363 match (self, found) {
364 (
365 SetupScaffolding::AwsSandbox {
366 egress, image_arn, ..
367 },
368 SetupScaffolding::AwsSandbox {
369 egress: found_egress,
370 image_arn: found_image_arn,
371 ..
372 },
373 ) => {
374 if image_arn.is_none() {
375 *image_arn = found_image_arn;
376 }
377 match (egress.as_mut(), found_egress) {
378 (None, found_egress) => *egress = found_egress,
379 (Some(recorded), Some(found)) => {
380 if recorded.security_group_id.is_none() {
381 recorded.security_group_id = found.security_group_id;
382 }
383 if recorded.connector_arn.is_none() {
384 recorded.connector_arn = found.connector_arn;
385 }
386 }
387 (Some(_), None) => {}
388 }
389 }
390 }
391 }
392}
393
394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
396#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
397#[serde(rename_all = "camelCase")]
398pub struct RegistryAccess {
399 #[serde(default, skip_serializing_if = "Vec::is_empty")]
401 pub repositories: Vec<String>,
402
403 #[serde(default, skip_serializing_if = "Vec::is_empty")]
406 pub service_types: Vec<String>,
407
408 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub verifier: Option<String>,
412}
413
414#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
422#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
423#[serde(rename_all = "camelCase")]
424pub struct DeploymentState {
425 pub status: DeploymentStatus,
427 pub platform: Platform,
429 #[serde(skip_serializing_if = "Option::is_none")]
431 pub current_release: Option<ReleaseInfo>,
432 #[serde(skip_serializing_if = "Option::is_none")]
434 pub target_release: Option<ReleaseInfo>,
435 #[serde(skip_serializing_if = "Option::is_none")]
437 pub stack_state: Option<StackState>,
438 #[serde(skip_serializing_if = "Option::is_none")]
442 pub error: Option<AlienError>,
443 #[serde(skip_serializing_if = "Option::is_none")]
445 pub environment_info: Option<EnvironmentInfo>,
446 #[serde(skip_serializing_if = "Option::is_none")]
448 pub runtime_metadata: Option<RuntimeMetadata>,
449 #[serde(default, skip_serializing_if = "is_false")]
452 pub retry_requested: bool,
453 pub protocol_version: u32,
458}
459
460impl DeploymentState {
461 pub fn has_desired(&self) -> bool {
464 self.current_release.is_some()
465 || self.target_release.is_some()
466 || self.stack_state.is_some()
467 }
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
475#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
476#[serde(rename_all = "camelCase")]
477pub struct DeploymentStepResult {
478 pub state: DeploymentState,
480
481 #[serde(skip_serializing_if = "Option::is_none")]
485 pub suggested_delay_ms: Option<u64>,
486
487 #[serde(default, skip_serializing_if = "is_false")]
491 pub update_heartbeat: bool,
492
493 #[serde(
495 default,
496 rename = "resourceHeartbeats",
497 skip_serializing_if = "Vec::is_empty"
498 )]
499 pub heartbeats: Vec<ResourceHeartbeat>,
500
501 #[serde(
503 default,
504 rename = "observedInventoryBatches",
505 skip_serializing_if = "Vec::is_empty"
506 )]
507 pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
508}
509
510pub(crate) fn is_false(b: &bool) -> bool {
511 !*b
512}
513
514pub type GateAnswers = IndexMap<String, bool>;
516
517pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
519
520pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
524
525pub const MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
527
528pub const GCP_FEDERATION_DEPLOYMENT_PROTOCOL_VERSION: u32 = 2;
530
531pub fn deployment_protocol_version_for_platform(
532 _platform: crate::Platform,
533 _base_platform: Option<crate::Platform>,
534) -> u32 {
535 CURRENT_DEPLOYMENT_PROTOCOL_VERSION
536}
537
538pub fn accepts_deployment_protocol_report(registered: u32, reported: u32) -> bool {
542 (MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION..=MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION)
543 .contains(®istered)
544 && (reported == registered
545 || (registered < CURRENT_DEPLOYMENT_PROTOCOL_VERSION
546 && reported == CURRENT_DEPLOYMENT_PROTOCOL_VERSION))
547}
548
549pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555 use crate::{Platform, ReleaseInfo, Stack, StackState};
556 use indexmap::IndexMap;
557
558 fn empty_stack() -> Stack {
559 Stack {
560 id: "stack_test".to_string(),
561 resources: IndexMap::new(),
562 inputs: vec![],
563 dynamic_container_repositories: Vec::new(),
564 dynamic_container_image_resources: Vec::new(),
565 operations: None,
566 permissions: crate::PermissionsConfig::default(),
567 supported_platforms: None,
568 }
569 }
570
571 fn release_info(id: &str) -> ReleaseInfo {
572 ReleaseInfo {
573 release_id: Some(id.to_string()),
574 version: None,
575 description: None,
576 stack: empty_stack(),
577 signed: None,
578 signer_lists: Vec::new(),
579 }
580 }
581
582 fn state() -> DeploymentState {
583 DeploymentState {
584 status: DeploymentStatus::Pending,
585 platform: Platform::Kubernetes,
586 current_release: None,
587 target_release: None,
588 stack_state: None,
589 error: None,
590 environment_info: None,
591 runtime_metadata: None,
592 retry_requested: false,
593 protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
594 }
595 }
596
597 #[test]
598 fn deployment_state_has_desired_when_release_or_stack_state_exists() {
599 let observe_only = state();
600 assert!(!observe_only.has_desired());
601
602 let mut current = state();
603 current.current_release = Some(release_info("rel_current"));
604 assert!(current.has_desired());
605
606 let mut target = state();
607 target.target_release = Some(release_info("rel_target"));
608 assert!(target.has_desired());
609
610 let mut imported = state();
611 imported.stack_state = Some(StackState::new(Platform::Kubernetes));
612 assert!(imported.has_desired());
613 }
614
615 #[test]
616 fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
617 let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
618 "lastSyncedEnvVarsHash": "old-hash"
619 }))
620 .expect("old runtime metadata remains readable");
621
622 assert_eq!(
623 metadata.last_synced_env_vars_hash.as_deref(),
624 Some("old-hash")
625 );
626 assert!(metadata.last_synced_secret_names.is_empty());
627 assert!(!metadata.vault_credentials_revoked);
628 assert!(metadata.retained_storage_protection_hash.is_none());
629 assert!(metadata.retained_storage_protection_confirmed_at.is_none());
630 assert!(metadata.pending_prepared_stack.is_none());
631 assert!(metadata.setup_update_authorization.is_none());
632 assert!(metadata.setup_scaffolding.is_empty());
633 }
634
635 #[test]
637 fn setup_scaffolding_round_trips_in_its_persisted_form() {
638 let persisted = serde_json::json!({
639 "initialSetupAuthority": "directSetup",
640 "setupScaffolding": {
641 "agents": { "type": "awsSandbox", "buildRoleName": "acme-agents-build" }
642 }
643 });
644 let metadata: RuntimeMetadata =
645 serde_json::from_value(persisted.clone()).expect("persisted record reads");
646 assert_eq!(
647 metadata.setup_scaffolding["agents"],
648 SetupScaffolding::AwsSandbox {
649 build_role_name: "acme-agents-build".to_string(),
650 egress: None,
651 image_arn: None,
652 }
653 );
654 assert_eq!(metadata.deletion_policy, DeletionPolicy::Retain);
655 let mut expected = persisted;
656 expected["deletionPolicy"] = serde_json::json!("retain");
657 assert_eq!(serde_json::to_value(&metadata).unwrap(), expected);
658 assert!(
659 serde_json::to_value(RuntimeMetadata::default()).unwrap()["setupScaffolding"].is_null(),
660 "state with no scaffolding serializes as it did before the field existed"
661 );
662 }
663
664 #[test]
665 fn filling_a_record_takes_only_what_it_lacks() {
666 let egress = |group: Option<&str>, connector: Option<&str>| AwsSandboxEgressScaffolding {
667 operator_role_name: "acme-agents-egress".to_string(),
668 security_group_id: group.map(str::to_string),
669 connector_arn: connector.map(str::to_string),
670 connector_request: None,
671 };
672 let record = |egress| SetupScaffolding::AwsSandbox {
673 build_role_name: "acme-agents-build".to_string(),
674 egress,
675 image_arn: None,
676 };
677
678 let mut partial = record(Some(egress(Some("sg-recorded"), None)));
679 partial.fill_missing(record(Some(egress(Some("sg-found"), Some("arn:found")))));
680 assert_eq!(
681 partial,
682 record(Some(egress(Some("sg-recorded"), Some("arn:found")))),
683 "a recorded id is the one teardown deletes"
684 );
685
686 let mut role_only = record(None);
687 role_only.fill_missing(record(Some(egress(Some("sg-found"), None))));
688 assert_eq!(role_only, record(Some(egress(Some("sg-found"), None))));
689
690 let image = |arn: Option<&str>| SetupScaffolding::AwsSandbox {
691 build_role_name: "acme-agents-build".to_string(),
692 egress: None,
693 image_arn: arn.map(str::to_string),
694 };
695 let mut without_image = image(None);
696 without_image.fill_missing(image(Some("arn:found")));
697 assert_eq!(without_image, image(Some("arn:found")));
698 let mut with_image = image(Some("arn:recorded"));
699 with_image.fill_missing(image(Some("arn:found")));
700 assert_eq!(with_image, image(Some("arn:recorded")));
701 }
702
703 #[test]
705 fn a_partial_egress_record_round_trips_in_its_persisted_form() {
706 let persisted = serde_json::json!({
707 "type": "awsSandbox",
708 "buildRoleName": "acme-agents-build",
709 "egress": {
710 "operatorRoleName": "acme-agents-egress",
711 "securityGroupId": "sg-0123"
712 }
713 });
714 let record: SetupScaffolding =
715 serde_json::from_value(persisted.clone()).expect("persisted record reads");
716 assert_eq!(
717 record,
718 SetupScaffolding::AwsSandbox {
719 build_role_name: "acme-agents-build".to_string(),
720 egress: Some(AwsSandboxEgressScaffolding {
721 operator_role_name: "acme-agents-egress".to_string(),
722 security_group_id: Some("sg-0123".to_string()),
723 connector_arn: None,
724 connector_request: None,
725 }),
726 image_arn: None,
727 }
728 );
729 assert_eq!(serde_json::to_value(&record).unwrap(), persisted);
730 }
731}