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 get_dependencies(&self) -> Vec<ResourceRef> {
119        self.encryption_key.iter().cloned().collect()
120    }
121
122    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
123        // Downcast to Storage type to use the existing validate_update method
124        let new_storage = new_config
125            .as_any()
126            .downcast_ref::<Storage>()
127            .ok_or_else(|| {
128                AlienError::new(ErrorData::UnexpectedResourceType {
129                    resource_id: self.id.clone(),
130                    expected: Self::RESOURCE_TYPE,
131                    actual: new_config.get_resource_type(),
132                })
133            })?;
134
135        if self.id != new_storage.id {
136            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
137                resource_id: self.id.clone(),
138                reason: "the 'id' field is immutable".to_string(),
139            }));
140        }
141        // Add other validation rules here if needed
142        Ok(())
143    }
144
145    fn as_any(&self) -> &dyn Any {
146        self
147    }
148
149    fn as_any_mut(&mut self) -> &mut dyn Any {
150        self
151    }
152
153    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
154        Box::new(self.clone())
155    }
156
157    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
158        other.as_any().downcast_ref::<Storage>() == Some(self)
159    }
160
161    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
162        serde_json::to_value(self)
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn encryption_key_is_an_implicit_dependency() {
172        let key = ResourceRef::new(crate::Key::RESOURCE_TYPE, "customer-key");
173        let storage = Storage::new("customer-data".to_string())
174            .encryption_key(key.clone())
175            .build();
176
177        assert_eq!(storage.get_dependencies(), vec![key]);
178    }
179}