Skip to main content

alien_core/resources/
aws_open_search.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/// An Amazon OpenSearch Serverless collection (next generation).
11///
12/// # Experimental namespace
13///
14/// This is the first resource under the `experimental/` resource-type
15/// namespace. Experimental resources are provider-specific (they do not
16/// abstract over clouds), may change or be promoted to a portable resource
17/// in a breaking way, and are only registered for the platforms they
18/// support. `AwsOpenSearch` registers an AWS CloudFormation emitter only;
19/// deploying it to any other platform fails with a typed
20/// `ImportRegistrationMissing` error at generation time.
21///
22/// # What gets provisioned
23///
24/// The AWS emitter provisions next-generation OpenSearch Serverless:
25/// a collection group (`Generation: NEXTGEN`, compute/storage decoupled)
26/// plus a collection inside it, an AWS-owned-key encryption configuration,
27/// a public network policy, and a data-access policy for service-account
28/// roles granted `experimental/aws-opensearch/data-access`. Collection groups
29/// scale to zero by default; configure a non-zero minimum capacity when the
30/// workload requires predictable interactive latency.
31/// The collection endpoint is public but every request must be SigV4-signed
32/// and pass both IAM (`aoss:APIAccessAll`) and the data-access policy.
33///
34/// # Naming
35///
36/// The physical collection (and collection group) name is
37/// `{id}-{stack-suffix}` and must satisfy the AOSS name grammar, so `id`
38/// must match `[a-z][a-z0-9-]*` and be at most 23 characters. The emitter
39/// rejects ids that don't fit.
40///
41/// # Runtime access
42///
43/// Workers reach the collection over HTTPS with SigV4. The SigV4 signing
44/// service name for OpenSearch Serverless is `aoss` (not `es`); the runtime
45/// binding payload carries `"service": "aoss"` so clients sign correctly.
46/// Requests with a body must also send an `x-amz-content-sha256` header
47/// (the AOSS gateway rejects body-carrying requests without it with an
48/// empty 403); official OpenSearch clients with an `aoss` signer handle
49/// this automatically.
50#[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    /// Identifier for the collection. Becomes part of the physical collection
56    /// name, so it must match `[a-z][a-z0-9-]*` and be at most 23 characters.
57    #[builder(start_fn)]
58    pub id: String,
59    /// Workload type of the collection. Immutable once the resource exists
60    /// (AWS only allows the type at collection creation). Default `Search`.
61    #[builder(default)]
62    #[serde(default)]
63    pub collection_type: AwsOpenSearchCollectionType,
64    /// Optional indexing and search OCU limits for the collection group.
65    ///
66    /// When omitted, AWS uses zero minimum capacity for both components, so
67    /// an idle next-generation collection can scale to zero.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub capacity: Option<AwsOpenSearchCapacity>,
70}
71
72/// Indexing and search capacity limits for an OpenSearch collection group.
73#[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    /// Indexing OCU bounds.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub indexing: Option<AwsOpenSearchCapacityRange>,
80    /// Search OCU bounds.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub search: Option<AwsOpenSearchCapacityRange>,
83}
84
85/// Minimum and maximum OCU bounds for one OpenSearch compute component.
86#[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    /// Minimum OCUs kept available. Zero enables scale-to-zero.
91    #[cfg_attr(feature = "openapi", schema(minimum = 0, maximum = 1696))]
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub min_ocu: Option<u16>,
94    /// Maximum OCUs the component may scale to.
95    #[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/// Workload type for an OpenSearch Serverless collection.
101///
102/// `TIMESERIES` is intentionally not exposed: next-generation serverless
103/// scale-to-zero targets search and vector workloads.
104#[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    /// Full-text search collections (`SEARCH`).
109    #[default]
110    Search,
111    /// Vector similarity search collections (`VECTORSEARCH`).
112    VectorSearch,
113}
114
115impl AwsOpenSearch {
116    /// The resource type identifier for AwsOpenSearch.
117    ///
118    /// The `experimental/` prefix marks the experimental namespace; see the
119    /// struct-level docs for the convention.
120    pub const RESOURCE_TYPE: ResourceType =
121        ResourceType::from_static("experimental/aws-opensearch");
122
123    /// Returns the collection's unique identifier.
124    pub fn id(&self) -> &str {
125        &self.id
126    }
127
128    /// Validates collection-group capacity values against AWS's supported OCU
129    /// increments and min/max ordering.
130    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/// Outputs generated by a successfully provisioned AwsOpenSearch collection.
191///
192/// Next-generation collections expose no OpenSearch Dashboards endpoint
193/// (the `DashboardEndpoint` attribute exists only for classic collections),
194/// so only the data-plane endpoint and ARN are surfaced.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
197#[serde(rename_all = "camelCase")]
198pub struct AwsOpenSearchOutputs {
199    /// Collection endpoint (`https://<collectionId>.aoss.<region>.on.aws`).
200    /// Requests must be SigV4-signed with service name `aoss`.
201    pub endpoint: String,
202    /// ARN of the collection.
203    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        // AWS only accepts the collection type at creation; changing it would
261        // silently require replacing the collection and dropping every index.
262        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        // A no-op update is allowed.
340        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}