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
62impl Storage {
63    /// The resource type identifier for Storage
64    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("storage");
65
66    /// Returns the storage's unique identifier.
67    pub fn id(&self) -> &str {
68        &self.id
69    }
70}
71
72/// Outputs generated by a successfully provisioned Storage bucket.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
75#[serde(rename_all = "camelCase")]
76pub struct StorageOutputs {
77    /// The globally unique name of the bucket.
78    pub bucket_name: String,
79    // Add other outputs like region or URL if needed later
80}
81
82impl ResourceOutputsDefinition for StorageOutputs {
83    fn get_resource_type(&self) -> ResourceType {
84        Storage::RESOURCE_TYPE.clone()
85    }
86
87    fn as_any(&self) -> &dyn Any {
88        self
89    }
90
91    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
92        Box::new(self.clone())
93    }
94
95    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
96        other.as_any().downcast_ref::<StorageOutputs>() == Some(self)
97    }
98
99    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
100        serde_json::to_value(self)
101    }
102}
103
104// Implementation of ResourceDefinition trait for Storage
105impl ResourceDefinition for Storage {
106    fn get_resource_type(&self) -> ResourceType {
107        Self::RESOURCE_TYPE
108    }
109
110    fn id(&self) -> &str {
111        &self.id
112    }
113
114    fn get_dependencies(&self) -> Vec<ResourceRef> {
115        Vec::new()
116    }
117
118    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
119        // Downcast to Storage type to use the existing validate_update method
120        let new_storage = new_config
121            .as_any()
122            .downcast_ref::<Storage>()
123            .ok_or_else(|| {
124                AlienError::new(ErrorData::UnexpectedResourceType {
125                    resource_id: self.id.clone(),
126                    expected: Self::RESOURCE_TYPE,
127                    actual: new_config.get_resource_type(),
128                })
129            })?;
130
131        if self.id != new_storage.id {
132            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
133                resource_id: self.id.clone(),
134                reason: "the 'id' field is immutable".to_string(),
135            }));
136        }
137        // Add other validation rules here if needed
138        Ok(())
139    }
140
141    fn as_any(&self) -> &dyn Any {
142        self
143    }
144
145    fn as_any_mut(&mut self) -> &mut dyn Any {
146        self
147    }
148
149    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
150        Box::new(self.clone())
151    }
152
153    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
154        other.as_any().downcast_ref::<Storage>() == Some(self)
155    }
156
157    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
158        serde_json::to_value(self)
159    }
160}