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 replace_after_failed_create_is_safe(&self) -> bool {
238 false
240 }
241
242 fn get_dependencies(&self) -> Vec<ResourceRef> {
243 Vec::new()
244 }
245
246 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
247 let new_search = new_config
248 .as_any()
249 .downcast_ref::<AwsOpenSearch>()
250 .ok_or_else(|| {
251 AlienError::new(ErrorData::UnexpectedResourceType {
252 resource_id: self.id.clone(),
253 expected: Self::RESOURCE_TYPE,
254 actual: new_config.get_resource_type(),
255 })
256 })?;
257
258 if self.id != new_search.id {
259 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
260 resource_id: self.id.clone(),
261 reason: "the 'id' field is immutable".to_string(),
262 }));
263 }
264
265 if self.collection_type != new_search.collection_type {
268 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
269 resource_id: self.id.clone(),
270 reason: "the 'collectionType' field is immutable once the resource exists"
271 .to_string(),
272 }));
273 }
274
275 new_search.validate_capacity()?;
276
277 Ok(())
278 }
279
280 fn as_any(&self) -> &dyn Any {
281 self
282 }
283
284 fn as_any_mut(&mut self) -> &mut dyn Any {
285 self
286 }
287
288 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
289 Box::new(self.clone())
290 }
291
292 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
293 other.as_any().downcast_ref::<AwsOpenSearch>() == Some(self)
294 }
295
296 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
297 serde_json::to_value(self)
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 #[test]
306 fn builder_defaults_to_search() {
307 let search = AwsOpenSearch::new("search".to_string()).build();
308 assert_eq!(search.id, "search");
309 assert_eq!(search.collection_type, AwsOpenSearchCollectionType::Search);
310 assert!(search.capacity.is_none());
311 }
312
313 #[test]
314 fn resource_type_uses_experimental_namespace() {
315 assert_eq!(
316 AwsOpenSearch::RESOURCE_TYPE.as_ref(),
317 "experimental/aws-opensearch"
318 );
319 }
320
321 #[test]
322 fn validate_update_rejects_id_change() {
323 let original = AwsOpenSearch::new("search".to_string()).build();
324 let renamed = AwsOpenSearch::new("other".to_string()).build();
325 let err = original
326 .validate_update(&renamed)
327 .expect_err("changing the id must be rejected");
328 assert!(err.to_string().contains("'id' field is immutable"));
329 }
330
331 #[test]
332 fn validate_update_rejects_collection_type_change() {
333 let search = AwsOpenSearch::new("search".to_string()).build();
334 let vector = AwsOpenSearch::new("search".to_string())
335 .collection_type(AwsOpenSearchCollectionType::VectorSearch)
336 .build();
337
338 let err = search
339 .validate_update(&vector)
340 .expect_err("changing the collection type must be rejected");
341 assert!(err
342 .to_string()
343 .contains("'collectionType' field is immutable"));
344 assert!(vector.validate_update(&vector).is_ok());
346 }
347
348 #[test]
349 fn serializes_with_camel_case_and_roundtrips() {
350 let search = AwsOpenSearch::new("vectors".to_string())
351 .collection_type(AwsOpenSearchCollectionType::VectorSearch)
352 .build();
353 let json = serde_json::to_value(&search).unwrap();
354 assert_eq!(json["collectionType"], "vectorSearch");
355
356 let roundtrip: AwsOpenSearch = serde_json::from_value(json).unwrap();
357 assert_eq!(search, roundtrip);
358 }
359
360 #[test]
361 fn capacity_accepts_scale_to_zero_and_supported_nonzero_values() {
362 let search = AwsOpenSearch::new("search".to_string())
363 .capacity(AwsOpenSearchCapacity {
364 indexing: Some(AwsOpenSearchCapacityRange {
365 min_ocu: Some(0),
366 max_ocu: Some(1696),
367 }),
368 search: Some(AwsOpenSearchCapacityRange {
369 min_ocu: Some(2),
370 max_ocu: Some(32),
371 }),
372 })
373 .build();
374
375 search
376 .validate_capacity()
377 .expect("capacity should be valid");
378 let json = serde_json::to_value(&search).expect("capacity should serialize");
379 assert_eq!(json["capacity"]["indexing"]["minOcu"], 0);
380 assert_eq!(json["capacity"]["search"]["maxOcu"], 32);
381 }
382
383 #[test]
384 fn capacity_rejects_empty_unsupported_and_inverted_ranges() {
385 let cases = [
386 AwsOpenSearchCapacity {
387 indexing: None,
388 search: None,
389 },
390 AwsOpenSearchCapacity {
391 indexing: Some(AwsOpenSearchCapacityRange {
392 min_ocu: Some(3),
393 max_ocu: None,
394 }),
395 search: None,
396 },
397 AwsOpenSearchCapacity {
398 indexing: Some(AwsOpenSearchCapacityRange {
399 min_ocu: Some(0),
400 max_ocu: Some(1),
401 }),
402 search: None,
403 },
404 AwsOpenSearchCapacity {
405 indexing: None,
406 search: Some(AwsOpenSearchCapacityRange {
407 min_ocu: Some(8),
408 max_ocu: Some(4),
409 }),
410 },
411 ];
412
413 for capacity in cases {
414 let search = AwsOpenSearch::new("search".to_string())
415 .capacity(capacity)
416 .build();
417 let error = search
418 .validate_capacity()
419 .expect_err("invalid capacity must fail");
420 assert_eq!(error.code, "GENERIC_ERROR");
421 assert!(error.to_string().contains("capacity is invalid"));
422 }
423 }
424
425 #[test]
426 fn outputs_roundtrip() {
427 let outputs = AwsOpenSearchOutputs {
428 endpoint: "https://abc123.aoss.us-east-1.on.aws".to_string(),
429 collection_arn: "arn:aws:aoss:us-east-1:123456789012:collection/abc123".to_string(),
430 };
431 let json = serde_json::to_string(&outputs).unwrap();
432 let deserialized: AwsOpenSearchOutputs = serde_json::from_str(&json).unwrap();
433 assert_eq!(outputs, deserialized);
434 }
435}