alien-core 3.3.1

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

/// Represents an AI Gateway resource that provides a unified interface to
/// managed AI inference services across cloud providers.
///
/// BYO-key external providers (OpenAI/Anthropic) are NOT declared here. Like any
/// other BYO infrastructure (e.g. external Redis for `kv`), an external AI
/// provider is supplied at deploy time as an `ExternalBinding::Ai` in the
/// stack's external-bindings map; the executor then skips the cloud controller.
#[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 Ai {
    /// Identifier for the AI resource. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,
}

impl Ai {
    /// The resource type identifier for AI Gateway
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("ai");

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

/// Outputs generated by a successfully provisioned AI Gateway resource.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AiOutputs {
    /// The AI provider name (e.g., "bedrock", "vertex", "foundry", "external").
    pub provider: String,
    /// The provider endpoint URL, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    /// The provider account or project identifier, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,
}

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

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

impl ResourceDefinition for Ai {
    fn get_resource_type(&self) -> ResourceType {
        Self::RESOURCE_TYPE
    }

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

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

    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
        let new_ai = new_config.as_any().downcast_ref::<Ai>().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_ai.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::<Ai>() == 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_ai_builder() {
        let ai = Ai::new("llm".to_string()).build();
        assert_eq!(ai.id, "llm");
    }

    #[test]
    fn test_ai_resource_type() {
        assert_eq!(Ai::RESOURCE_TYPE.as_ref(), "ai");
    }

    #[test]
    fn test_ai_resource_definition() {
        let ai = Ai::new("test-ai".to_string()).build();
        assert_eq!(ai.get_resource_type(), Ai::RESOURCE_TYPE);
        assert_eq!(ResourceDefinition::id(&ai), "test-ai");
        assert!(ai.get_dependencies().is_empty());
    }

    #[test]
    fn test_ai_validate_update() {
        let original = Ai::new("test-ai".to_string()).build();
        let valid_update = Ai::new("test-ai".to_string()).build();
        let invalid_update = Ai::new("different-ai".to_string()).build();

        assert!(original.validate_update(&valid_update).is_ok());
        assert!(original.validate_update(&invalid_update).is_err());
    }

    #[test]
    fn test_ai_outputs_serialization() {
        let outputs = AiOutputs {
            provider: "bedrock".to_string(),
            endpoint: Some("https://bedrock-runtime.us-east-1.amazonaws.com".to_string()),
            account: None,
        };

        let json = serde_json::to_string(&outputs).unwrap();
        let deserialized: AiOutputs = serde_json::from_str(&json).unwrap();
        assert_eq!(outputs, deserialized);
    }
}