alien-core 3.3.70

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::Debug;

/// Represents an artifact registry for storing container images and other build artifacts.
/// This is a high-level wrapper resource that provides a cloud-agnostic interface over
/// AWS ECR, GCP Artifact Registry, and Azure Container Registry.
///
/// # Platform Mapping
/// - **AWS**: Implicitly exists as the AWS account and region
/// - **GCP**: Explicitly configured per project and location (Artifact Registry API enabled)
/// - **Azure**: Explicitly provisioned Azure Container Registry instance
///
/// The actual repository management and permissions are handled through the bindings API.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct ArtifactRegistry {
    /// Identifier for the artifact registry. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,

    /// AWS-only: regions to replicate container images to.
    /// ECR private image replication ensures images pushed in the registry's home region
    /// are automatically available in these additional regions (required when Lambda or
    /// other compute runs in a different region from the registry).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[builder(default)]
    pub replication_regions: Vec<String>,

    /// AWS-only: id of a deployer-provided string-list stack input that names the
    /// regions to replicate to. CloudFormation reads the list at deploy time, so
    /// the template reserves a fixed number of region slots. Empty answers write
    /// no replication configuration, so existing installs render unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replication_regions_input: Option<String>,
}

impl ArtifactRegistry {
    /// The resource type identifier for ArtifactRegistry
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("artifact-registry");

    /// Account-wide ECR configuration must have one infrastructure owner. A deployment
    /// cannot safely merge its rules with other deployments or external account writers.
    pub fn validate_aws_replication(&self) -> Result<()> {
        if !self.replication_regions.is_empty() {
            tracing::warn!(resource_id = %self.id, "Per-deployment ECR replicationRegions is ignored; configure replication through the registry account's infrastructure. Existing account replication rules remain unchanged.");
        }
        Ok(())
    }

    /// Returns the artifact registry's unique identifier.
    pub fn id(&self) -> &str {
        &self.id
    }
}

// Implementation of ResourceDefinition trait for ArtifactRegistry
impl ResourceDefinition for ArtifactRegistry {
    fn get_resource_type(&self) -> ResourceType {
        Self::RESOURCE_TYPE
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn replace_after_failed_create_is_safe(&self) -> bool {
        // A create adopts an existing repository with the same name, and deleting it deletes every
        // image in it, including images this deployment never pushed.
        false
    }

    fn get_dependencies(&self) -> Vec<ResourceRef> {
        Vec::new()
    }

    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
        // Downcast to ArtifactRegistry type to use the existing validate_update method
        let new_registry = new_config
            .as_any()
            .downcast_ref::<ArtifactRegistry>()
            .ok_or_else(|| {
                AlienError::new(ErrorData::UnexpectedResourceType {
                    resource_id: self.id.clone(),
                    expected: Self::RESOURCE_TYPE,
                    actual: new_config.get_resource_type(),
                })
            })?;

        if self.id != new_registry.id {
            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
                resource_id: self.id.clone(),
                reason: "the 'id' field is immutable".to_string(),
            }));
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
        Box::new(self.clone())
    }

    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
        other.as_any().downcast_ref::<ArtifactRegistry>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }

    fn with_empty_input_references_removed(
        &self,
        inputs: &crate::InputAnswers<'_>,
    ) -> Option<Box<dyn ResourceDefinition>> {
        // Only a declared input answered with no regions resolves to nothing. An undeclared
        // input or a listed region is a real difference from a config without the reference.
        let input = self.replication_regions_input.as_deref()?;
        if !inputs.string_list(input)?.is_empty() {
            return None;
        }
        let mut config = self.clone();
        config.replication_regions_input = None;
        Some(Box::new(config))
    }

    fn input_references(&self) -> Vec<(&'static str, String)> {
        self.replication_regions_input
            .iter()
            .map(|input| ("replicationRegionsInput", input.clone()))
            .collect()
    }
}

/// Outputs generated by a successfully provisioned ArtifactRegistry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ArtifactRegistryOutputs {
    /// The platform-specific registry identifier.
    /// - AWS: Account and region (e.g., "123456789012:us-west-2")
    /// - GCP: Full registry name (e.g., "projects/my-project/locations/us-central1")
    /// - Azure: Registry resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ContainerRegistry/registries/myregistry")
    pub registry_id: String,

    /// The registry endpoint for docker operations.
    /// - AWS: ECR registry URL (e.g., "123456789012.dkr.ecr.us-west-2.amazonaws.com")
    /// - GCP: Artifact Registry URL (e.g., "us-central1-docker.pkg.dev/my-project")
    /// - Azure: Container registry login server (e.g., "myregistry.azurecr.io")
    pub registry_endpoint: String,

    /// Role/principal identifier for pull-only access.
    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-pull")
    /// - GCP: Service account email (e.g., "my-stack-my-registry-pull@my-project.iam.gserviceaccount.com")
    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-pull")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pull_role: Option<String>,

    /// Role/principal identifier for push and pull access.
    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-push")
    /// - GCP: Service account email (e.g., "my-stack-my-registry-push@my-project.iam.gserviceaccount.com")
    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-push")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub push_role: Option<String>,
}

/// Whose rules the registry's replication configuration holds. The configuration is one
/// per account and region, and writing it replaces every rule. The setup that writes ours
/// reads the rules when it writes and keeps every rule that is not ours unchanged, so this
/// report is informational: it tells the operator which other rules the account has.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum RegistryReplicationOwner {
    /// No rules.
    None,
    /// Exactly the one rule this registry's setup writes.
    Ours,
    /// At least one rule this registry did not write; setup keeps it unchanged.
    Foreign,
}

/// The replication rules a registry reported, without anything beyond rule shapes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct RegistryReplicationReport {
    pub owner: RegistryReplicationOwner,
    /// One short line per rule that is not ours: destination regions and repository filters.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub foreign_rules: Vec<String>,
}

impl ResourceOutputsDefinition for ArtifactRegistryOutputs {
    fn get_resource_type(&self) -> ResourceType {
        ArtifactRegistry::RESOURCE_TYPE.clone()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
        Box::new(self.clone())
    }

    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
        other.as_any().downcast_ref::<ArtifactRegistryOutputs>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_artifact_registry_creation() {
        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
        assert_eq!(registry.id, "my-registry");
    }

    #[test]
    fn aws_registry_does_not_promise_per_deployment_replication() {
        let mut registry = ArtifactRegistry::new("images".to_string()).build();
        assert!(registry.validate_aws_replication().is_ok());
        registry.replication_regions = vec!["us-west-2".to_string()];
        assert!(registry.validate_aws_replication().is_ok());
    }

    #[test]
    fn test_artifact_registry_dependencies() {
        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
        let dependencies = registry.get_dependencies();
        assert!(dependencies.is_empty());
    }
}