Skip to main content

alien_core/resources/
kv.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/// Represents a key-value storage resource that provides a minimal, platform-agnostic API
11/// compatible across DynamoDB, Firestore, Redis, and Azure Table Storage.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
13#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
14#[serde(rename_all = "camelCase", deny_unknown_fields)]
15#[builder(start_fn = new)]
16pub struct Kv {
17    /// Identifier for the KV store. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
18    /// Maximum 64 characters.
19    #[builder(start_fn)]
20    pub id: String,
21}
22
23impl Kv {
24    /// The resource type identifier for KV
25    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("kv");
26
27    /// Returns the KV store's unique identifier.
28    pub fn id(&self) -> &str {
29        &self.id
30    }
31}
32
33/// Outputs generated by a successfully provisioned KV store.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
36#[serde(rename_all = "camelCase")]
37pub struct KvOutputs {
38    /// The name of the KV store (may be platform-specific).
39    pub store_name: String,
40    /// Platform-specific identifier (e.g., DynamoDB table ARN, Redis endpoint).
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub identifier: Option<String>,
43    /// Platform-specific endpoint URL for direct access (if applicable).
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub endpoint: Option<String>,
46}
47
48impl ResourceOutputsDefinition for KvOutputs {
49    fn get_resource_type(&self) -> ResourceType {
50        Kv::RESOURCE_TYPE.clone()
51    }
52
53    fn as_any(&self) -> &dyn Any {
54        self
55    }
56
57    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
58        Box::new(self.clone())
59    }
60
61    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
62        other.as_any().downcast_ref::<KvOutputs>() == Some(self)
63    }
64
65    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
66        serde_json::to_value(self)
67    }
68}
69
70// Implementation of ResourceDefinition trait for Kv
71impl ResourceDefinition for Kv {
72    fn get_resource_type(&self) -> ResourceType {
73        Self::RESOURCE_TYPE
74    }
75
76    fn id(&self) -> &str {
77        &self.id
78    }
79
80    fn replace_after_failed_create_is_safe(&self) -> bool {
81        // Deleting it destroys the stored items.
82        false
83    }
84
85    fn get_dependencies(&self) -> Vec<ResourceRef> {
86        Vec::new()
87    }
88
89    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
90        // Downcast to Kv type to use the existing validate_update method
91        let new_kv = new_config.as_any().downcast_ref::<Kv>().ok_or_else(|| {
92            AlienError::new(ErrorData::UnexpectedResourceType {
93                resource_id: self.id.clone(),
94                expected: Self::RESOURCE_TYPE,
95                actual: new_config.get_resource_type(),
96            })
97        })?;
98
99        if self.id != new_kv.id {
100            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
101                resource_id: self.id.clone(),
102                reason: "the 'id' field is immutable".to_string(),
103            }));
104        }
105        Ok(())
106    }
107
108    fn as_any(&self) -> &dyn Any {
109        self
110    }
111
112    fn as_any_mut(&mut self) -> &mut dyn Any {
113        self
114    }
115
116    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
117        Box::new(self.clone())
118    }
119
120    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
121        other.as_any().downcast_ref::<Kv>() == Some(self)
122    }
123
124    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
125        serde_json::to_value(self)
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn test_kv_builder() {
135        let kv = Kv::new("my-kv".to_string()).build();
136        assert_eq!(kv.id, "my-kv");
137    }
138
139    #[test]
140    fn test_kv_resource_type() {
141        assert_eq!(Kv::RESOURCE_TYPE.as_ref(), "kv");
142    }
143
144    #[test]
145    fn test_kv_resource_definition() {
146        let kv = Kv::new("test-kv".to_string()).build();
147        assert_eq!(kv.get_resource_type(), Kv::RESOURCE_TYPE);
148        assert_eq!(kv.id(), "test-kv");
149        assert!(kv.get_dependencies().is_empty());
150    }
151
152    #[test]
153    fn test_kv_validate_update() {
154        let original = Kv::new("test-kv".to_string()).build();
155        let valid_update = Kv::new("test-kv".to_string()).build();
156        let invalid_update = Kv::new("different-kv".to_string()).build();
157
158        // Same ID should be valid
159        assert!(original.validate_update(&valid_update).is_ok());
160
161        // Different ID should be invalid
162        assert!(original.validate_update(&invalid_update).is_err());
163    }
164
165    #[test]
166    fn test_kv_outputs_serialization() {
167        let outputs = KvOutputs {
168            store_name: "my-kv-store".to_string(),
169            identifier: Some(
170                "arn:aws:dynamodb:us-east-1:123456789012:table/my-kv-store".to_string(),
171            ),
172            endpoint: Some("https://my-kv-store.table.core.windows.net".to_string()),
173        };
174
175        let json = serde_json::to_string(&outputs).unwrap();
176        let deserialized: KvOutputs = serde_json::from_str(&json).unwrap();
177        assert_eq!(outputs, deserialized);
178    }
179}