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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
51#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
52#[serde(rename_all = "camelCase", deny_unknown_fields)]
53#[builder(start_fn = new)]
54pub struct AwsOpenSearch {
55 #[builder(start_fn)]
58 pub id: String,
59 #[builder(default)]
62 #[serde(default)]
63 pub collection_type: AwsOpenSearchCollectionType,
64 #[serde(skip_serializing_if = "Option::is_none")]
69 pub capacity: Option<AwsOpenSearchCapacity>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
75#[serde(rename_all = "camelCase", deny_unknown_fields)]
76pub struct AwsOpenSearchCapacity {
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub indexing: Option<AwsOpenSearchCapacityRange>,
80 #[serde(skip_serializing_if = "Option::is_none")]
82 pub search: Option<AwsOpenSearchCapacityRange>,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
88#[serde(rename_all = "camelCase", deny_unknown_fields)]
89pub struct AwsOpenSearchCapacityRange {
90 #[cfg_attr(feature = "openapi", schema(minimum = 0, maximum = 1696))]
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub min_ocu: Option<u16>,
94 #[cfg_attr(feature = "openapi", schema(minimum = 2, maximum = 1696))]
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub max_ocu: Option<u16>,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
105#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
106#[serde(rename_all = "camelCase")]
107pub enum AwsOpenSearchCollectionType {
108 #[default]
110 Search,
111 VectorSearch,
113}
114
115impl AwsOpenSearch {
116 pub const RESOURCE_TYPE: ResourceType =
121 ResourceType::from_static("experimental/aws-opensearch");
122
123 pub fn id(&self) -> &str {
125 &self.id
126 }
127
128 pub fn validate_capacity(&self) -> Result<()> {
131 let Some(capacity) = &self.capacity else {
132 return Ok(());
133 };
134 if capacity.indexing.is_none() && capacity.search.is_none() {
135 return Err(invalid_capacity(
136 "at least one of 'indexing' or 'search' must be configured",
137 ));
138 }
139 if let Some(range) = capacity.indexing {
140 validate_capacity_range("indexing", range)?;
141 }
142 if let Some(range) = capacity.search {
143 validate_capacity_range("search", range)?;
144 }
145 Ok(())
146 }
147}
148
149fn validate_capacity_range(component: &str, range: AwsOpenSearchCapacityRange) -> Result<()> {
150 if range.min_ocu.is_none() && range.max_ocu.is_none() {
151 return Err(invalid_capacity(format!(
152 "'{component}' must configure 'minOcu' or 'maxOcu'"
153 )));
154 }
155 if let Some(min) = range.min_ocu {
156 if min != 0 && !valid_nonzero_ocu(min) {
157 return Err(invalid_capacity(format!(
158 "'{component}.minOcu' value {min} is unsupported"
159 )));
160 }
161 }
162 if let Some(max) = range.max_ocu {
163 if !valid_nonzero_ocu(max) {
164 return Err(invalid_capacity(format!(
165 "'{component}.maxOcu' value {max} is unsupported"
166 )));
167 }
168 }
169 if let (Some(min), Some(max)) = (range.min_ocu, range.max_ocu) {
170 if min > max {
171 return Err(invalid_capacity(format!(
172 "'{component}.minOcu' ({min}) must be less than or equal to \
173 '{component}.maxOcu' ({max})"
174 )));
175 }
176 }
177 Ok(())
178}
179
180fn valid_nonzero_ocu(value: u16) -> bool {
181 matches!(value, 2 | 4 | 8 | 16) || (value >= 32 && value <= 1696 && value % 16 == 0)
182}
183
184fn invalid_capacity(message: impl Into<String>) -> AlienError<ErrorData> {
185 AlienError::new(ErrorData::GenericError {
186 message: format!("AwsOpenSearch capacity is invalid: {}", message.into()),
187 })
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
197#[serde(rename_all = "camelCase")]
198pub struct AwsOpenSearchOutputs {
199 pub endpoint: String,
202 pub collection_arn: String,
204}
205
206impl ResourceOutputsDefinition for AwsOpenSearchOutputs {
207 fn get_resource_type(&self) -> ResourceType {
208 AwsOpenSearch::RESOURCE_TYPE.clone()
209 }
210
211 fn as_any(&self) -> &dyn Any {
212 self
213 }
214
215 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
216 Box::new(self.clone())
217 }
218
219 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
220 other.as_any().downcast_ref::<AwsOpenSearchOutputs>() == Some(self)
221 }
222
223 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
224 serde_json::to_value(self)
225 }
226}
227
228impl ResourceDefinition for AwsOpenSearch {
229 fn get_resource_type(&self) -> ResourceType {
230 Self::RESOURCE_TYPE
231 }
232
233 fn id(&self) -> &str {
234 &self.id
235 }
236
237 fn get_dependencies(&self) -> Vec<ResourceRef> {
238 Vec::new()
239 }
240
241 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
242 let new_search = new_config
243 .as_any()
244 .downcast_ref::<AwsOpenSearch>()
245 .ok_or_else(|| {
246 AlienError::new(ErrorData::UnexpectedResourceType {
247 resource_id: self.id.clone(),
248 expected: Self::RESOURCE_TYPE,
249 actual: new_config.get_resource_type(),
250 })
251 })?;
252
253 if self.id != new_search.id {
254 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
255 resource_id: self.id.clone(),
256 reason: "the 'id' field is immutable".to_string(),
257 }));
258 }
259
260 if self.collection_type != new_search.collection_type {
263 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
264 resource_id: self.id.clone(),
265 reason: "the 'collectionType' field is immutable once the resource exists"
266 .to_string(),
267 }));
268 }
269
270 new_search.validate_capacity()?;
271
272 Ok(())
273 }
274
275 fn as_any(&self) -> &dyn Any {
276 self
277 }
278
279 fn as_any_mut(&mut self) -> &mut dyn Any {
280 self
281 }
282
283 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
284 Box::new(self.clone())
285 }
286
287 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
288 other.as_any().downcast_ref::<AwsOpenSearch>() == Some(self)
289 }
290
291 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
292 serde_json::to_value(self)
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[test]
301 fn builder_defaults_to_search() {
302 let search = AwsOpenSearch::new("search".to_string()).build();
303 assert_eq!(search.id, "search");
304 assert_eq!(search.collection_type, AwsOpenSearchCollectionType::Search);
305 assert!(search.capacity.is_none());
306 }
307
308 #[test]
309 fn resource_type_uses_experimental_namespace() {
310 assert_eq!(
311 AwsOpenSearch::RESOURCE_TYPE.as_ref(),
312 "experimental/aws-opensearch"
313 );
314 }
315
316 #[test]
317 fn validate_update_rejects_id_change() {
318 let original = AwsOpenSearch::new("search".to_string()).build();
319 let renamed = AwsOpenSearch::new("other".to_string()).build();
320 let err = original
321 .validate_update(&renamed)
322 .expect_err("changing the id must be rejected");
323 assert!(err.to_string().contains("'id' field is immutable"));
324 }
325
326 #[test]
327 fn validate_update_rejects_collection_type_change() {
328 let search = AwsOpenSearch::new("search".to_string()).build();
329 let vector = AwsOpenSearch::new("search".to_string())
330 .collection_type(AwsOpenSearchCollectionType::VectorSearch)
331 .build();
332
333 let err = search
334 .validate_update(&vector)
335 .expect_err("changing the collection type must be rejected");
336 assert!(err
337 .to_string()
338 .contains("'collectionType' field is immutable"));
339 assert!(vector.validate_update(&vector).is_ok());
341 }
342
343 #[test]
344 fn serializes_with_camel_case_and_roundtrips() {
345 let search = AwsOpenSearch::new("vectors".to_string())
346 .collection_type(AwsOpenSearchCollectionType::VectorSearch)
347 .build();
348 let json = serde_json::to_value(&search).unwrap();
349 assert_eq!(json["collectionType"], "vectorSearch");
350
351 let roundtrip: AwsOpenSearch = serde_json::from_value(json).unwrap();
352 assert_eq!(search, roundtrip);
353 }
354
355 #[test]
356 fn capacity_accepts_scale_to_zero_and_supported_nonzero_values() {
357 let search = AwsOpenSearch::new("search".to_string())
358 .capacity(AwsOpenSearchCapacity {
359 indexing: Some(AwsOpenSearchCapacityRange {
360 min_ocu: Some(0),
361 max_ocu: Some(1696),
362 }),
363 search: Some(AwsOpenSearchCapacityRange {
364 min_ocu: Some(2),
365 max_ocu: Some(32),
366 }),
367 })
368 .build();
369
370 search
371 .validate_capacity()
372 .expect("capacity should be valid");
373 let json = serde_json::to_value(&search).expect("capacity should serialize");
374 assert_eq!(json["capacity"]["indexing"]["minOcu"], 0);
375 assert_eq!(json["capacity"]["search"]["maxOcu"], 32);
376 }
377
378 #[test]
379 fn capacity_rejects_empty_unsupported_and_inverted_ranges() {
380 let cases = [
381 AwsOpenSearchCapacity {
382 indexing: None,
383 search: None,
384 },
385 AwsOpenSearchCapacity {
386 indexing: Some(AwsOpenSearchCapacityRange {
387 min_ocu: Some(3),
388 max_ocu: None,
389 }),
390 search: None,
391 },
392 AwsOpenSearchCapacity {
393 indexing: Some(AwsOpenSearchCapacityRange {
394 min_ocu: Some(0),
395 max_ocu: Some(1),
396 }),
397 search: None,
398 },
399 AwsOpenSearchCapacity {
400 indexing: None,
401 search: Some(AwsOpenSearchCapacityRange {
402 min_ocu: Some(8),
403 max_ocu: Some(4),
404 }),
405 },
406 ];
407
408 for capacity in cases {
409 let search = AwsOpenSearch::new("search".to_string())
410 .capacity(capacity)
411 .build();
412 let error = search
413 .validate_capacity()
414 .expect_err("invalid capacity must fail");
415 assert_eq!(error.code, "GENERIC_ERROR");
416 assert!(error.to_string().contains("capacity is invalid"));
417 }
418 }
419
420 #[test]
421 fn outputs_roundtrip() {
422 let outputs = AwsOpenSearchOutputs {
423 endpoint: "https://abc123.aoss.us-east-1.on.aws".to_string(),
424 collection_arn: "arn:aws:aoss:us-east-1:123456789012:collection/abc123".to_string(),
425 };
426 let json = serde_json::to_string(&outputs).unwrap();
427 let deserialized: AwsOpenSearchOutputs = serde_json::from_str(&json).unwrap();
428 assert_eq!(outputs, deserialized);
429 }
430}