alien-core 3.3.56

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 crate::{LifecycleRule, ResourceLifecycle, Stack, Storage};
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Debug;

/// Represents an Azure Storage Account for blob, file, table, and queue storage.
#[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 AzureStorageAccount {
    /// Identifier for the storage account. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,
}

impl AzureStorageAccount {
    /// The resource type identifier for Azure Storage Accounts
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("azure_storage_account");

    /// Fingerprint shared settings derived from all container declarations.
    /// Setup authorization must include Live contributors to this Frozen parent.
    /// An empty projection preserves digests from installations without settings.
    pub fn setup_settings_digest(stack: &Stack) -> Option<String> {
        let settings = azure_storage_settings(stack);
        (settings != AzureStorageSettings::default()).then(|| {
            let encoded = serde_json::to_vec(&settings)
                .expect("Azure storage settings contain only serializable values");
            format!("{:x}", Sha256::digest(encoded))
        })
    }

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

/// Outputs generated by a successfully provisioned Azure Storage Account.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AzureStorageAccountOutputs {
    /// The name of the storage account.
    pub account_name: String,
    /// The resource ID of the storage account.
    pub resource_id: String,
    /// The primary endpoint for blob storage.
    pub primary_blob_endpoint: String,
    /// The primary endpoint for file storage.
    pub primary_file_endpoint: String,
    /// The primary endpoint for queue storage.
    pub primary_queue_endpoint: String,
    /// The primary endpoint for table storage.
    pub primary_table_endpoint: String,
}

impl ResourceOutputsDefinition for AzureStorageAccountOutputs {
    fn get_resource_type(&self) -> ResourceType {
        AzureStorageAccount::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::<AzureStorageAccountOutputs>() == Some(self)
    }

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

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

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

    fn replace_after_failed_create_is_safe(&self) -> bool {
        // Deleting it destroys the blobs, tables and queues in the account.
        false
    }

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

    fn validate_update(&self, _new_config: &dyn ResourceDefinition) -> Result<()> {
        Err(AlienError::new(ErrorData::InvalidResourceUpdate {
            resource_id: self.id.clone(),
            reason: "Azure storage accounts cannot be updated once created".to_string(),
        }))
    }

    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::<AzureStorageAccount>() == Some(self)
    }

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

/// Settings written by setup to the shared account, including Live contributors.
/// Compare the derived settings so ordinary Live updates cannot bypass setup.
#[derive(Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
struct AzureStorageSettings {
    public: BTreeSet<Option<String>>,
    versioning: BTreeSet<Option<String>>,
    cors: BTreeMap<String, BTreeSet<Option<String>>>,
    expiry: BTreeMap<String, (ResourceLifecycle, Option<String>, Vec<LifecycleRule>)>,
}

fn azure_storage_settings(stack: &Stack) -> AzureStorageSettings {
    let mut settings = AzureStorageSettings::default();
    for (id, entry) in stack.resources() {
        let Some(storage) = entry.config.downcast_ref::<Storage>() else {
            continue;
        };
        if storage.public_read {
            settings.public.insert(entry.enabled_when.clone());
        }
        if storage.versioning {
            settings.versioning.insert(entry.enabled_when.clone());
        }
        for origin in &storage.cors_allowed_origins {
            settings
                .cors
                .entry(origin.clone())
                .or_default()
                .insert(entry.enabled_when.clone());
        }
        if !storage.lifecycle_rules.is_empty() {
            settings.expiry.insert(
                id.clone(),
                (
                    entry.lifecycle,
                    entry.enabled_when.clone(),
                    storage.lifecycle_rules.clone(),
                ),
            );
        }
    }
    // One unconditional contributor makes conditional contributors irrelevant.
    for gates in [&mut settings.public, &mut settings.versioning]
        .into_iter()
        .chain(settings.cors.values_mut())
    {
        if gates.contains(&None) {
            gates.clear();
            gates.insert(None);
        }
    }
    settings
}