Skip to main content

alien_core/resources/
artifact_registry.rs

1use crate::error::{ErrorData, Result};
2use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
3use alien_error::AlienError;
4use bon::Builder;
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7use std::fmt::Debug;
8
9/// Represents an artifact registry for storing container images and other build artifacts.
10/// This is a high-level wrapper resource that provides a cloud-agnostic interface over
11/// AWS ECR, GCP Artifact Registry, and Azure Container Registry.
12///
13/// # Platform Mapping
14/// - **AWS**: Implicitly exists as the AWS account and region
15/// - **GCP**: Explicitly configured per project and location (Artifact Registry API enabled)
16/// - **Azure**: Explicitly provisioned Azure Container Registry instance
17///
18/// The actual repository management and permissions are handled through the bindings API.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
20#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
21#[serde(rename_all = "camelCase", deny_unknown_fields)]
22#[builder(start_fn = new)]
23pub struct ArtifactRegistry {
24    /// Identifier for the artifact registry. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
25    /// Maximum 64 characters.
26    #[builder(start_fn)]
27    pub id: String,
28
29    /// AWS-only: regions to replicate container images to.
30    /// ECR private image replication ensures images pushed in the registry's home region
31    /// are automatically available in these additional regions (required when Lambda or
32    /// other compute runs in a different region from the registry).
33    #[serde(default, skip_serializing_if = "Vec::is_empty")]
34    #[builder(default)]
35    pub replication_regions: Vec<String>,
36}
37
38impl ArtifactRegistry {
39    /// The resource type identifier for ArtifactRegistry
40    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("artifact-registry");
41
42    /// Account-wide ECR configuration must have one infrastructure owner. A deployment
43    /// cannot safely merge its rules with other deployments or external account writers.
44    pub fn validate_aws_replication(&self) -> Result<()> {
45        if !self.replication_regions.is_empty() {
46            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.");
47        }
48        Ok(())
49    }
50
51    /// Returns the artifact registry's unique identifier.
52    pub fn id(&self) -> &str {
53        &self.id
54    }
55}
56
57// Implementation of ResourceDefinition trait for ArtifactRegistry
58impl ResourceDefinition for ArtifactRegistry {
59    fn get_resource_type(&self) -> ResourceType {
60        Self::RESOURCE_TYPE
61    }
62
63    fn id(&self) -> &str {
64        &self.id
65    }
66
67    fn replace_after_failed_create_is_safe(&self) -> bool {
68        // A create adopts an existing repository with the same name, and deleting it deletes every
69        // image in it, including images this deployment never pushed.
70        false
71    }
72
73    fn get_dependencies(&self) -> Vec<ResourceRef> {
74        Vec::new()
75    }
76
77    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
78        // Downcast to ArtifactRegistry type to use the existing validate_update method
79        let new_registry = new_config
80            .as_any()
81            .downcast_ref::<ArtifactRegistry>()
82            .ok_or_else(|| {
83                AlienError::new(ErrorData::UnexpectedResourceType {
84                    resource_id: self.id.clone(),
85                    expected: Self::RESOURCE_TYPE,
86                    actual: new_config.get_resource_type(),
87                })
88            })?;
89
90        if self.id != new_registry.id {
91            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
92                resource_id: self.id.clone(),
93                reason: "the 'id' field is immutable".to_string(),
94            }));
95        }
96        Ok(())
97    }
98
99    fn as_any(&self) -> &dyn Any {
100        self
101    }
102
103    fn as_any_mut(&mut self) -> &mut dyn Any {
104        self
105    }
106
107    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
108        Box::new(self.clone())
109    }
110
111    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
112        other.as_any().downcast_ref::<ArtifactRegistry>() == Some(self)
113    }
114
115    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
116        serde_json::to_value(self)
117    }
118}
119
120/// Outputs generated by a successfully provisioned ArtifactRegistry.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
123#[serde(rename_all = "camelCase")]
124pub struct ArtifactRegistryOutputs {
125    /// The platform-specific registry identifier.
126    /// - AWS: Account and region (e.g., "123456789012:us-west-2")
127    /// - GCP: Full registry name (e.g., "projects/my-project/locations/us-central1")
128    /// - Azure: Registry resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ContainerRegistry/registries/myregistry")
129    pub registry_id: String,
130
131    /// The registry endpoint for docker operations.
132    /// - AWS: ECR registry URL (e.g., "123456789012.dkr.ecr.us-west-2.amazonaws.com")
133    /// - GCP: Artifact Registry URL (e.g., "us-central1-docker.pkg.dev/my-project")
134    /// - Azure: Container registry login server (e.g., "myregistry.azurecr.io")
135    pub registry_endpoint: String,
136
137    /// Role/principal identifier for pull-only access.
138    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-pull")
139    /// - GCP: Service account email (e.g., "my-stack-my-registry-pull@my-project.iam.gserviceaccount.com")
140    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-pull")
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub pull_role: Option<String>,
143
144    /// Role/principal identifier for push and pull access.
145    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-push")
146    /// - GCP: Service account email (e.g., "my-stack-my-registry-push@my-project.iam.gserviceaccount.com")
147    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-push")
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub push_role: Option<String>,
150}
151
152impl ResourceOutputsDefinition for ArtifactRegistryOutputs {
153    fn get_resource_type(&self) -> ResourceType {
154        ArtifactRegistry::RESOURCE_TYPE.clone()
155    }
156
157    fn as_any(&self) -> &dyn Any {
158        self
159    }
160
161    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
162        Box::new(self.clone())
163    }
164
165    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
166        other.as_any().downcast_ref::<ArtifactRegistryOutputs>() == Some(self)
167    }
168
169    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
170        serde_json::to_value(self)
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn test_artifact_registry_creation() {
180        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
181        assert_eq!(registry.id, "my-registry");
182    }
183
184    #[test]
185    fn aws_registry_does_not_promise_per_deployment_replication() {
186        let mut registry = ArtifactRegistry::new("images".to_string()).build();
187        assert!(registry.validate_aws_replication().is_ok());
188        registry.replication_regions = vec!["us-west-2".to_string()];
189        assert!(registry.validate_aws_replication().is_ok());
190    }
191
192    #[test]
193    fn test_artifact_registry_dependencies() {
194        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
195        let dependencies = registry.get_dependencies();
196        assert!(dependencies.is_empty());
197    }
198}