alien_core/resources/
ai.rs1use 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#[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 #[builder(start_fn)]
25 pub id: String,
26 #[builder(default)]
29 #[serde(default, skip_serializing_if = "Vec::is_empty")]
30 pub models: Vec<AiModel>,
31}
32
33#[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 pub id: String,
40 #[serde(default)]
43 pub required: bool,
44}
45
46impl Ai {
47 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("ai");
49
50 pub fn id(&self) -> &str {
52 &self.id
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
59#[serde(rename_all = "camelCase")]
60pub struct AiOutputs {
61 pub provider: String,
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub endpoint: Option<String>,
66 #[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!(serde_json::to_value(&plain).unwrap(), serde_json::json!({"id": "llm"}));
159
160 let with_models = Ai::new("llm".to_string())
161 .models(vec![
162 AiModel { id: "claude-sonnet-4-6".to_string(), required: true },
163 AiModel { id: "claude-haiku-4-5".to_string(), required: false },
164 ])
165 .build();
166 let json = serde_json::to_value(&with_models).unwrap();
167 assert_eq!(
168 json,
169 serde_json::json!({"id": "llm", "models": [
170 {"id": "claude-sonnet-4-6", "required": true},
171 {"id": "claude-haiku-4-5", "required": false},
172 ]})
173 );
174 assert_eq!(serde_json::from_value::<Ai>(json).unwrap(), with_models);
175 let parsed: Ai =
177 serde_json::from_value(serde_json::json!({"id": "llm", "models": [{"id": "m"}]})).unwrap();
178 assert!(!parsed.models[0].required);
179 assert!(serde_json::from_value::<Ai>(
180 serde_json::json!({"id": "llm", "models": [{"id": "m", "minRpm": 1}]})
181 )
182 .is_err());
183 }
184
185 #[test]
186 fn test_ai_resource_type() {
187 assert_eq!(Ai::RESOURCE_TYPE.as_ref(), "ai");
188 }
189
190 #[test]
191 fn test_ai_resource_definition() {
192 let ai = Ai::new("test-ai".to_string()).build();
193 assert_eq!(ai.get_resource_type(), Ai::RESOURCE_TYPE);
194 assert_eq!(ResourceDefinition::id(&ai), "test-ai");
195 assert!(ai.get_dependencies().is_empty());
196 }
197
198 #[test]
199 fn test_ai_validate_update() {
200 let original = Ai::new("test-ai".to_string()).build();
201 let valid_update = Ai::new("test-ai".to_string()).build();
202 let invalid_update = Ai::new("different-ai".to_string()).build();
203
204 assert!(original.validate_update(&valid_update).is_ok());
205 assert!(original.validate_update(&invalid_update).is_err());
206 }
207
208 #[test]
209 fn test_ai_outputs_serialization() {
210 let outputs = AiOutputs {
211 provider: "bedrock".to_string(),
212 endpoint: Some("https://bedrock-runtime.us-east-1.amazonaws.com".to_string()),
213 account: None,
214 };
215
216 let json = serde_json::to_string(&outputs).unwrap();
217 let deserialized: AiOutputs = serde_json::from_str(&json).unwrap();
218 assert_eq!(outputs, deserialized);
219 }
220}