Skip to main content

alien_core/resources/
ai.rs

1use crate::error::{ErrorData, Result};
2use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef};
3use crate::ResourceType;
4use alien_error::AlienError;
5use bon::Builder;
6use serde::{Deserialize, Serialize};
7use std::any::Any;
8use std::fmt::Debug;
9
10/// Represents an AI Gateway resource that provides a unified interface to
11/// managed AI inference services across cloud providers.
12///
13/// BYO-key external providers (OpenAI/Anthropic) are NOT declared here. Like any
14/// other BYO infrastructure (e.g. external Redis for `kv`), an external AI
15/// provider is supplied at deploy time as an `ExternalBinding::Ai` in the
16/// stack's external-bindings map; the executor then skips the cloud controller.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
18#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[serde(rename_all = "camelCase", deny_unknown_fields)]
20#[builder(start_fn = new)]
21pub struct Ai {
22    /// Identifier for the AI resource. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
23    /// Maximum 64 characters.
24    #[builder(start_fn)]
25    pub id: String,
26    /// The models the app calls. A deployment checks that the cloud lets it use each one.
27    /// Omitted from the serialized stack when empty, so existing stacks do not change.
28    #[builder(default)]
29    #[serde(default, skip_serializing_if = "Vec::is_empty")]
30    pub models: Vec<AiModel>,
31}
32
33/// A model the app calls through an AI resource.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
36#[serde(rename_all = "camelCase", deny_unknown_fields)]
37pub struct AiModel {
38    /// The model identifier as the app uses it, for example `claude-sonnet-4-6`.
39    pub id: String,
40    /// Whether the app's main feature needs this model. A refused required model is reported
41    /// as needing attention; it never blocks the deployment.
42    #[serde(default)]
43    pub required: bool,
44}
45
46impl Ai {
47    /// The resource type identifier for AI Gateway
48    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("ai");
49
50    /// Returns the AI resource's unique identifier.
51    pub fn id(&self) -> &str {
52        &self.id
53    }
54}
55
56/// Outputs generated by a successfully provisioned AI Gateway resource.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
59#[serde(rename_all = "camelCase")]
60pub struct AiOutputs {
61    /// The AI provider name (e.g., "bedrock", "vertex", "foundry", "external").
62    pub provider: String,
63    /// The provider endpoint URL, if applicable.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub endpoint: Option<String>,
66    /// The provider account or project identifier, if applicable.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub account: Option<String>,
69}
70
71impl ResourceOutputsDefinition for AiOutputs {
72    fn get_resource_type(&self) -> ResourceType {
73        Ai::RESOURCE_TYPE.clone()
74    }
75
76    fn as_any(&self) -> &dyn Any {
77        self
78    }
79
80    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
81        Box::new(self.clone())
82    }
83
84    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
85        other.as_any().downcast_ref::<AiOutputs>() == Some(self)
86    }
87
88    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
89        serde_json::to_value(self)
90    }
91}
92
93impl ResourceDefinition for Ai {
94    fn get_resource_type(&self) -> ResourceType {
95        Self::RESOURCE_TYPE
96    }
97
98    fn id(&self) -> &str {
99        &self.id
100    }
101
102    fn get_dependencies(&self) -> Vec<ResourceRef> {
103        Vec::new()
104    }
105
106    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
107        let new_ai = new_config.as_any().downcast_ref::<Ai>().ok_or_else(|| {
108            AlienError::new(ErrorData::UnexpectedResourceType {
109                resource_id: self.id.clone(),
110                expected: Self::RESOURCE_TYPE,
111                actual: new_config.get_resource_type(),
112            })
113        })?;
114
115        if self.id != new_ai.id {
116            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
117                resource_id: self.id.clone(),
118                reason: "the 'id' field is immutable".to_string(),
119            }));
120        }
121        Ok(())
122    }
123
124    fn as_any(&self) -> &dyn Any {
125        self
126    }
127
128    fn as_any_mut(&mut self) -> &mut dyn Any {
129        self
130    }
131
132    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
133        Box::new(self.clone())
134    }
135
136    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
137        other.as_any().downcast_ref::<Ai>() == Some(self)
138    }
139
140    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
141        serde_json::to_value(self)
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn test_ai_builder() {
151        let ai = Ai::new("llm".to_string()).build();
152        assert_eq!(ai.id, "llm");
153    }
154
155    #[test]
156    fn models_are_omitted_when_empty_and_round_trip_when_set() {
157        let plain = Ai::new("llm".to_string()).build();
158        assert_eq!(
159            serde_json::to_value(&plain).unwrap(),
160            serde_json::json!({"id": "llm"})
161        );
162
163        let with_models = Ai::new("llm".to_string())
164            .models(vec![
165                AiModel {
166                    id: "claude-sonnet-4-6".to_string(),
167                    required: true,
168                },
169                AiModel {
170                    id: "claude-haiku-4-5".to_string(),
171                    required: false,
172                },
173            ])
174            .build();
175        let json = serde_json::to_value(&with_models).unwrap();
176        assert_eq!(
177            json,
178            serde_json::json!({"id": "llm", "models": [
179                {"id": "claude-sonnet-4-6", "required": true},
180                {"id": "claude-haiku-4-5", "required": false},
181            ]})
182        );
183        assert_eq!(serde_json::from_value::<Ai>(json).unwrap(), with_models);
184        // `required` defaults to false; unknown model fields are rejected.
185        let parsed: Ai =
186            serde_json::from_value(serde_json::json!({"id": "llm", "models": [{"id": "m"}]}))
187                .unwrap();
188        assert!(!parsed.models[0].required);
189        assert!(serde_json::from_value::<Ai>(
190            serde_json::json!({"id": "llm", "models": [{"id": "m", "minRpm": 1}]})
191        )
192        .is_err());
193    }
194
195    #[test]
196    fn test_ai_resource_type() {
197        assert_eq!(Ai::RESOURCE_TYPE.as_ref(), "ai");
198    }
199
200    #[test]
201    fn test_ai_resource_definition() {
202        let ai = Ai::new("test-ai".to_string()).build();
203        assert_eq!(ai.get_resource_type(), Ai::RESOURCE_TYPE);
204        assert_eq!(ResourceDefinition::id(&ai), "test-ai");
205        assert!(ai.get_dependencies().is_empty());
206    }
207
208    #[test]
209    fn test_ai_validate_update() {
210        let original = Ai::new("test-ai".to_string()).build();
211        let valid_update = Ai::new("test-ai".to_string()).build();
212        let invalid_update = Ai::new("different-ai".to_string()).build();
213
214        assert!(original.validate_update(&valid_update).is_ok());
215        assert!(original.validate_update(&invalid_update).is_err());
216    }
217
218    #[test]
219    fn test_ai_outputs_serialization() {
220        let outputs = AiOutputs {
221            provider: "bedrock".to_string(),
222            endpoint: Some("https://bedrock-runtime.us-east-1.amazonaws.com".to_string()),
223            account: None,
224        };
225
226        let json = serde_json::to_string(&outputs).unwrap();
227        let deserialized: AiOutputs = serde_json::from_str(&json).unwrap();
228        assert_eq!(outputs, deserialized);
229    }
230}