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(skip_serializing_if = "Option::is_none")]
158 pub last_synced_env_vars_hash: Option<String>,
159
160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
164 pub last_synced_secret_names: Vec<String>,
165
166 #[serde(default, skip_serializing_if = "is_false")]
170 pub vault_credentials_revoked: bool,
171
172 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub retained_storage_protection_hash: Option<String>,
178
179 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub retained_storage_protection_confirmed_at: Option<chrono::DateTime<chrono::Utc>>,
183
184 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub retained_data_protection_started_at: Option<chrono::DateTime<chrono::Utc>>,
188
189 #[serde(skip_serializing_if = "Option::is_none")]
193 pub prepared_stack: Option<crate::Stack>,
194
195 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
203 pub persisted_gate_answers: GateAnswers,
204
205 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub pending_prepared_stack: Option<crate::Stack>,
209
210 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub pending_prepared_release_id: Option<String>,
216
217 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub setup_update_authorization: Option<SetupUpdateAuthorization>,
221
222 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub setup_report_refusal: Option<SetupReportRefusal>,
226
227 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub cloud_setup_required: Option<CloudSetupRequired>,
231
232 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub installed_helm_release: Option<InstalledHelmRelease>,
235
236 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub direct_setup_revision: Option<String>,
241
242 #[serde(default, skip_serializing_if = "is_false")]
247 pub registry_access_granted: bool,
248
249 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub registry_access: Option<RegistryAccess>,
254
255 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
258 pub setup_scaffolding: BTreeMap<String, SetupScaffolding>,
259
260 #[serde(default, skip_serializing_if = "Vec::is_empty")]
264 pub deployer_secrets: Vec<crate::DeployerSecretReport>,
265
266 #[serde(default, skip_serializing_if = "Vec::is_empty")]
270 pub ai_access_checks: Vec<AiAccessCheck>,
271 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub deployer_secrets_checked_at: Option<chrono::DateTime<chrono::Utc>>,
276
277 #[serde(default, skip_serializing_if = "Vec::is_empty")]
282 pub resources_waiting_for_secrets: Vec<String>,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
287#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
288#[serde(rename_all = "camelCase")]
289pub struct AiAccessCheck {
290 pub resource_id: String,
292 pub model_id: String,
294 pub result: AiAccessCheckResult,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub detail: Option<String>,
299 pub tested_at: chrono::DateTime<chrono::Utc>,
300}
301
302#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
303#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
304#[serde(rename_all = "kebab-case")]
305pub enum AiAccessCheckResult {
306 Verified,
307 Refused,
308 NotChecked,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
314#[serde(rename_all = "camelCase", tag = "type")]
315pub enum SetupScaffolding {
316 #[serde(rename_all = "camelCase")]
318 AwsSandbox {
319 build_role_name: String,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
323 egress: Option<AwsSandboxEgressScaffolding>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
327 image_arn: Option<String>,
328 },
329}
330
331#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
335#[serde(rename_all = "camelCase")]
336pub struct AwsSandboxEgressScaffolding {
337 pub operator_role_name: String,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub security_group_id: Option<String>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub connector_arn: Option<String>,
345 #[serde(default, skip_serializing_if = "Option::is_none")]
348 pub connector_request: Option<String>,
349}
350
351impl SetupScaffolding {
352 pub fn fill_missing(&mut self, found: SetupScaffolding) {
355 match (self, found) {
356 (
357 SetupScaffolding::AwsSandbox {
358 egress, image_arn, ..
359 },
360 SetupScaffolding::AwsSandbox {
361 egress: found_egress,
362 image_arn: found_image_arn,
363 ..
364 },
365 ) => {
366 if image_arn.is_none() {
367 *image_arn = found_image_arn;
368 }
369 match (egress.as_mut(), found_egress) {
370 (None, found_egress) => *egress = found_egress,
371 (Some(recorded), Some(found)) => {
372 if recorded.security_group_id.is_none() {
373 recorded.security_group_id = found.security_group_id;
374 }
375 if recorded.connector_arn.is_none() {
376 recorded.connector_arn = found.connector_arn;
377 }
378 }
379 (Some(_), None) => {}
380 }
381 }
382 }
383 }
384}
385
386#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
388#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
389#[serde(rename_all = "camelCase")]
390pub struct RegistryAccess {
391 #[serde(default, skip_serializing_if = "Vec::is_empty")]
393 pub repositories: Vec<String>,
394
395 #[serde(default, skip_serializing_if = "Vec::is_empty")]
398 pub service_types: Vec<String>,
399}
400
401#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
409#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
410#[serde(rename_all = "camelCase")]
411pub struct DeploymentState {
412 pub status: DeploymentStatus,
414 pub platform: Platform,
416 #[serde(skip_serializing_if = "Option::is_none")]
418 pub current_release: Option<ReleaseInfo>,
419 #[serde(skip_serializing_if = "Option::is_none")]
421 pub target_release: Option<ReleaseInfo>,
422 #[serde(skip_serializing_if = "Option::is_none")]
424 pub stack_state: Option<StackState>,
425 #[serde(skip_serializing_if = "Option::is_none")]
429 pub error: Option<AlienError>,
430 #[serde(skip_serializing_if = "Option::is_none")]
432 pub environment_info: Option<EnvironmentInfo>,
433 #[serde(skip_serializing_if = "Option::is_none")]
435 pub runtime_metadata: Option<RuntimeMetadata>,
436 #[serde(default, skip_serializing_if = "is_false")]
439 pub retry_requested: bool,
440 pub protocol_version: u32,
445}
446
447impl DeploymentState {
448 pub fn has_desired(&self) -> bool {
451 self.current_release.is_some()
452 || self.target_release.is_some()
453 || self.stack_state.is_some()
454 }
455}
456
457#[derive(Debug, Clone, Serialize, Deserialize)]
462#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
463#[serde(rename_all = "camelCase")]
464pub struct DeploymentStepResult {
465 pub state: DeploymentState,
467
468 #[serde(skip_serializing_if = "Option::is_none")]
472 pub suggested_delay_ms: Option<u64>,
473
474 #[serde(default, skip_serializing_if = "is_false")]
478 pub update_heartbeat: bool,
479
480 #[serde(
482 default,
483 rename = "resourceHeartbeats",
484 skip_serializing_if = "Vec::is_empty"
485 )]
486 pub heartbeats: Vec<ResourceHeartbeat>,
487
488 #[serde(
490 default,
491 rename = "observedInventoryBatches",
492 skip_serializing_if = "Vec::is_empty"
493 )]
494 pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
495}
496
497pub(crate) fn is_false(b: &bool) -> bool {
498 !*b
499}
500
501pub type GateAnswers = IndexMap<String, bool>;
503
504pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
506
507pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
511
512pub const MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
514
515pub const GCP_FEDERATION_DEPLOYMENT_PROTOCOL_VERSION: u32 = 2;
517
518pub fn deployment_protocol_version_for_platform(
519 _platform: crate::Platform,
520 _base_platform: Option<crate::Platform>,
521) -> u32 {
522 CURRENT_DEPLOYMENT_PROTOCOL_VERSION
523}
524
525pub fn accepts_deployment_protocol_report(registered: u32, reported: u32) -> bool {
529 (MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION..=MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION)
530 .contains(®istered)
531 && (reported == registered
532 || (registered < CURRENT_DEPLOYMENT_PROTOCOL_VERSION
533 && reported == CURRENT_DEPLOYMENT_PROTOCOL_VERSION))
534}
535
536pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542 use crate::{Platform, ReleaseInfo, Stack, StackState};
543 use indexmap::IndexMap;
544
545 fn empty_stack() -> Stack {
546 Stack {
547 id: "stack_test".to_string(),
548 resources: IndexMap::new(),
549 inputs: vec![],
550 dynamic_container_repositories: Vec::new(),
551 dynamic_container_image_resources: Vec::new(),
552 operations: None,
553 permissions: crate::PermissionsConfig::default(),
554 supported_platforms: None,
555 }
556 }
557
558 fn release_info(id: &str) -> ReleaseInfo {
559 ReleaseInfo {
560 release_id: Some(id.to_string()),
561 version: None,
562 description: None,
563 stack: empty_stack(),
564 }
565 }
566
567 fn state() -> DeploymentState {
568 DeploymentState {
569 status: DeploymentStatus::Pending,
570 platform: Platform::Kubernetes,
571 current_release: None,
572 target_release: None,
573 stack_state: None,
574 error: None,
575 environment_info: None,
576 runtime_metadata: None,
577 retry_requested: false,
578 protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
579 }
580 }
581
582 #[test]
583 fn deployment_state_has_desired_when_release_or_stack_state_exists() {
584 let observe_only = state();
585 assert!(!observe_only.has_desired());
586
587 let mut current = state();
588 current.current_release = Some(release_info("rel_current"));
589 assert!(current.has_desired());
590
591 let mut target = state();
592 target.target_release = Some(release_info("rel_target"));
593 assert!(target.has_desired());
594
595 let mut imported = state();
596 imported.stack_state = Some(StackState::new(Platform::Kubernetes));
597 assert!(imported.has_desired());
598 }
599
600 #[test]
601 fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
602 let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
603 "lastSyncedEnvVarsHash": "old-hash"
604 }))
605 .expect("old runtime metadata remains readable");
606
607 assert_eq!(
608 metadata.last_synced_env_vars_hash.as_deref(),
609 Some("old-hash")
610 );
611 assert!(metadata.last_synced_secret_names.is_empty());
612 assert!(!metadata.vault_credentials_revoked);
613 assert!(metadata.retained_storage_protection_hash.is_none());
614 assert!(metadata.retained_storage_protection_confirmed_at.is_none());
615 assert!(metadata.pending_prepared_stack.is_none());
616 assert!(metadata.setup_update_authorization.is_none());
617 assert!(metadata.setup_scaffolding.is_empty());
618 }
619
620 #[test]
622 fn setup_scaffolding_round_trips_in_its_persisted_form() {
623 let persisted = serde_json::json!({
624 "initialSetupAuthority": "directSetup",
625 "setupScaffolding": {
626 "agents": { "type": "awsSandbox", "buildRoleName": "acme-agents-build" }
627 }
628 });
629 let metadata: RuntimeMetadata =
630 serde_json::from_value(persisted.clone()).expect("persisted record reads");
631 assert_eq!(
632 metadata.setup_scaffolding["agents"],
633 SetupScaffolding::AwsSandbox {
634 build_role_name: "acme-agents-build".to_string(),
635 egress: None,
636 image_arn: None,
637 }
638 );
639 assert_eq!(metadata.deletion_policy, DeletionPolicy::Retain);
640 let mut expected = persisted;
641 expected["deletionPolicy"] = serde_json::json!("retain");
642 assert_eq!(serde_json::to_value(&metadata).unwrap(), expected);
643 assert!(
644 serde_json::to_value(RuntimeMetadata::default()).unwrap()["setupScaffolding"].is_null(),
645 "state with no scaffolding serializes as it did before the field existed"
646 );
647 }
648
649 #[test]
650 fn filling_a_record_takes_only_what_it_lacks() {
651 let egress = |group: Option<&str>, connector: Option<&str>| AwsSandboxEgressScaffolding {
652 operator_role_name: "acme-agents-egress".to_string(),
653 security_group_id: group.map(str::to_string),
654 connector_arn: connector.map(str::to_string),
655 connector_request: None,
656 };
657 let record = |egress| SetupScaffolding::AwsSandbox {
658 build_role_name: "acme-agents-build".to_string(),
659 egress,
660 image_arn: None,
661 };
662
663 let mut partial = record(Some(egress(Some("sg-recorded"), None)));
664 partial.fill_missing(record(Some(egress(Some("sg-found"), Some("arn:found")))));
665 assert_eq!(
666 partial,
667 record(Some(egress(Some("sg-recorded"), Some("arn:found")))),
668 "a recorded id is the one teardown deletes"
669 );
670
671 let mut role_only = record(None);
672 role_only.fill_missing(record(Some(egress(Some("sg-found"), None))));
673 assert_eq!(role_only, record(Some(egress(Some("sg-found"), None))));
674
675 let image = |arn: Option<&str>| SetupScaffolding::AwsSandbox {
676 build_role_name: "acme-agents-build".to_string(),
677 egress: None,
678 image_arn: arn.map(str::to_string),
679 };
680 let mut without_image = image(None);
681 without_image.fill_missing(image(Some("arn:found")));
682 assert_eq!(without_image, image(Some("arn:found")));
683 let mut with_image = image(Some("arn:recorded"));
684 with_image.fill_missing(image(Some("arn:found")));
685 assert_eq!(with_image, image(Some("arn:recorded")));
686 }
687
688 #[test]
690 fn a_partial_egress_record_round_trips_in_its_persisted_form() {
691 let persisted = serde_json::json!({
692 "type": "awsSandbox",
693 "buildRoleName": "acme-agents-build",
694 "egress": {
695 "operatorRoleName": "acme-agents-egress",
696 "securityGroupId": "sg-0123"
697 }
698 });
699 let record: SetupScaffolding =
700 serde_json::from_value(persisted.clone()).expect("persisted record reads");
701 assert_eq!(
702 record,
703 SetupScaffolding::AwsSandbox {
704 build_role_name: "acme-agents-build".to_string(),
705 egress: Some(AwsSandboxEgressScaffolding {
706 operator_role_name: "acme-agents-egress".to_string(),
707 security_group_id: Some("sg-0123".to_string()),
708 connector_arn: None,
709 connector_request: None,
710 }),
711 image_arn: None,
712 }
713 );
714 assert_eq!(serde_json::to_value(&record).unwrap(), persisted);
715 }
716}