Skip to main content

alien_core/resources/
storage.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/// Defines a rule for managing the lifecycle of objects within a storage bucket.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[serde(rename_all = "camelCase", deny_unknown_fields)]
14pub struct LifecycleRule {
15    /// Number of days after which objects matching the rule expire.
16    pub days: u32,
17    /// Optional prefix to filter objects the rule applies to. If None, applies to all objects.
18    #[serde(default)]
19    pub prefix: Option<String>,
20}
21
22/// Represents an object storage bucket.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
24#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
25#[serde(rename_all = "camelCase", deny_unknown_fields)]
26#[builder(start_fn = new)]
27pub struct Storage {
28    /// Name of the the storage bucket.
29    /// For names with dots, each dot-separated label must be ≤ 63 characters.
30    #[builder(start_fn)]
31    pub id: String,
32
33    /// Allows public read access to objects without authentication.
34    /// Default: `false`
35    #[serde(default)]
36    #[builder(default)]
37    pub public_read: bool,
38
39    /// Enables object versioning.
40    /// Default: `false`
41    #[serde(default)]
42    #[builder(default)]
43    pub versioning: bool,
44
45    /// List of rules for automatic object management (e.g., expiration).
46    /// Default: `[]` (empty list)
47    #[serde(default)]
48    #[builder(default)]
49    pub lifecycle_rules: Vec<LifecycleRule>,
50
51    /// Browser origins allowed to read objects through signed URLs.
52    ///
53    /// When non-empty, providers configure CORS for `GET` and `HEAD` requests.
54    /// An origin of `*` is appropriate for private buckets whose signed URLs
55    /// are bearer credentials and do not use browser cookies.
56    /// Default: `[]` (CORS disabled).
57    #[serde(default)]
58    #[builder(default)]
59    pub cors_allowed_origins: Vec<String>,
60
61    /// Customer-managed Key used by the provider's native storage encryption.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub encryption_key: Option<ResourceRef>,
64}
65
66impl Storage {
67    /// The resource type identifier for Storage
68    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("storage");
69
70    /// Returns the storage's unique identifier.
71    pub fn id(&self) -> &str {
72        &self.id
73    }
74}
75
76/// Outputs generated by a successfully provisioned Storage bucket.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
79#[serde(rename_all = "camelCase")]
80pub struct StorageOutputs {
81    /// The globally unique name of the bucket.
82    pub bucket_name: String,
83    // Add other outputs like region or URL if needed later
84}
85
86impl ResourceOutputsDefinition for StorageOutputs {
87    fn get_resource_type(&self) -> ResourceType {
88        Storage::RESOURCE_TYPE.clone()
89    }
90
91    fn as_any(&self) -> &dyn Any {
92        self
93    }
94
95    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
96        Box::new(self.clone())
97    }
98
99    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
100        other.as_any().downcast_ref::<StorageOutputs>() == Some(self)
101    }
102
103    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
104        serde_json::to_value(self)
105    }
106}
107
108// Implementation of ResourceDefinition trait for Storage
109impl ResourceDefinition for Storage {
110    fn get_resource_type(&self) -> ResourceType {
111        Self::RESOURCE_TYPE
112    }
113
114    fn id(&self) -> &str {
115        &self.id
116    }
117
118    fn replace_after_failed_create_is_safe(&self) -> bool {
119        // Deleting it destroys the objects in the bucket.
120        false
121    }
122
123    fn get_dependencies(&self) -> Vec<ResourceRef> {
124        self.encryption_key.iter().cloned().collect()
125    }
126
127    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
128        // Downcast to Storage type to use the existing validate_update method
129        let new_storage = new_config
130            .as_any()
131            .downcast_ref::<Storage>()
132            .ok_or_else(|| {
133                AlienError::new(ErrorData::UnexpectedResourceType {
134                    resource_id: self.id.clone(),
135                    expected: Self::RESOURCE_TYPE,
136                    actual: new_config.get_resource_type(),
137                })
138            })?;
139
140        if self.id != new_storage.id {
141            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
142                resource_id: self.id.clone(),
143                reason: "the 'id' field is immutable".to_string(),
144            }));
145        }
146        // Add other validation rules here if needed
147        Ok(())
148    }
149
150    fn as_any(&self) -> &dyn Any {
151        self
152    }
153
154    fn as_any_mut(&mut self) -> &mut dyn Any {
155        self
156    }
157
158    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
159        Box::new(self.clone())
160    }
161
162    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
163        other.as_any().downcast_ref::<Storage>() == Some(self)
164    }
165
166    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
167        serde_json::to_value(self)
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn encryption_key_is_an_implicit_dependency() {
177        let key = ResourceRef::new(crate::Key::RESOURCE_TYPE, "customer-key");
178        let storage = Storage::new("customer-data".to_string())
179            .encryption_key(key.clone())
180            .build();
181
182        assert_eq!(storage.get_dependencies(), vec![key]);
183    }
184}