Skip to main content

winterbaume_memorydb/
state.rs

1use std::collections::HashMap;
2
3use chrono::Utc;
4use thiserror::Error;
5
6use crate::types::*;
7
8/// In-memory state for the MemoryDB service.
9#[derive(Debug, Default)]
10pub struct MemoryDbState {
11    /// Clusters keyed by cluster name.
12    pub clusters: HashMap<String, Cluster>,
13    /// Snapshots keyed by snapshot name.
14    pub snapshots: HashMap<String, SnapshotData>,
15    /// Subnet groups keyed by subnet group name.
16    pub subnet_groups: HashMap<String, SubnetGroupData>,
17    /// ACLs keyed by ACL name.
18    pub acls: HashMap<String, AclData>,
19    /// Tags keyed by resource ARN.
20    pub tags: TagsMap,
21}
22
23/// Error type for MemoryDB operations.
24#[derive(Debug, Error)]
25pub enum MemoryDbError {
26    #[error("Cluster {0} already exists.")]
27    ClusterAlreadyExists(String),
28    #[error("Cluster {0} not found.")]
29    ClusterNotFound(String),
30    #[error("Snapshot {0} already exists.")]
31    SnapshotAlreadyExists(String),
32    #[error("Snapshot {0} not found.")]
33    SnapshotNotFound(String),
34    #[error("Subnet group {0} already exists.")]
35    SubnetGroupAlreadyExists(String),
36    #[error("Subnet group {0} not found.")]
37    SubnetGroupNotFound(String),
38    #[error("Subnet group {0} is in use and cannot be deleted.")]
39    SubnetGroupInUse(String),
40    #[error("The default subnet group cannot be deleted.")]
41    DefaultSubnetGroupCannotBeDeleted,
42    #[error("Tag with key {0} not found.")]
43    TagNotFound(String),
44    #[error("The resource with ARN {0} was not found.")]
45    InvalidArn(String),
46}
47
48impl MemoryDbState {
49    pub fn create_cluster(
50        &mut self,
51        account_id: &str,
52        region: &str,
53        name: &str,
54        node_type: &str,
55        acl_name: &str,
56        description: Option<&str>,
57        num_shards: Option<i32>,
58        num_replicas_per_shard: Option<i32>,
59        subnet_group_name: Option<&str>,
60        security_group_ids: Vec<String>,
61        engine_version: Option<&str>,
62        maintenance_window: Option<&str>,
63        snapshot_retention_limit: Option<i32>,
64        snapshot_window: Option<&str>,
65        parameter_group_name: Option<&str>,
66        tls_enabled: Option<bool>,
67        auto_minor_version_upgrade: Option<bool>,
68        tags: Vec<TagData>,
69    ) -> Result<&Cluster, MemoryDbError> {
70        if self.clusters.contains_key(name) {
71            return Err(MemoryDbError::ClusterAlreadyExists(name.to_string()));
72        }
73
74        let arn = format!("arn:aws:memorydb:{region}:{account_id}:cluster/{name}");
75        let cluster = Cluster {
76            name: name.to_string(),
77            arn: arn.clone(),
78            status: "available".to_string(),
79            node_type: node_type.to_string(),
80            num_shards: num_shards.unwrap_or(1),
81            num_replicas_per_shard: num_replicas_per_shard.unwrap_or(1),
82            description: description.unwrap_or("").to_string(),
83            engine: "redis".to_string(),
84            engine_version: engine_version.unwrap_or("7.1").to_string(),
85            subnet_group_name: subnet_group_name.unwrap_or("default").to_string(),
86            security_group_ids,
87            maintenance_window: maintenance_window
88                .unwrap_or("wed:03:00-wed:04:00")
89                .to_string(),
90            snapshot_retention_limit: snapshot_retention_limit.unwrap_or(0),
91            snapshot_window: snapshot_window.unwrap_or("05:00-06:00").to_string(),
92            acl_name: acl_name.to_string(),
93            parameter_group_name: parameter_group_name
94                .unwrap_or("default.memorydb-redis7")
95                .to_string(),
96            tls_enabled: tls_enabled.unwrap_or(true),
97            auto_minor_version_upgrade: auto_minor_version_upgrade.unwrap_or(true),
98            creation_time: Utc::now(),
99        };
100
101        self.clusters.insert(name.to_string(), cluster);
102        if !tags.is_empty() {
103            self.tags.insert(arn, tags);
104        }
105        Ok(self.clusters.get(name).unwrap())
106    }
107
108    pub fn describe_clusters(
109        &self,
110        cluster_name: Option<&str>,
111    ) -> Result<Vec<&Cluster>, MemoryDbError> {
112        match cluster_name {
113            Some(name) => {
114                if let Some(cluster) = self.clusters.get(name) {
115                    Ok(vec![cluster])
116                } else {
117                    Err(MemoryDbError::ClusterNotFound(name.to_string()))
118                }
119            }
120            None => Ok(self.clusters.values().collect()),
121        }
122    }
123
124    pub fn delete_cluster(
125        &mut self,
126        name: &str,
127        final_snapshot_name: Option<&str>,
128        account_id: &str,
129        region: &str,
130    ) -> Result<Cluster, MemoryDbError> {
131        if !self.clusters.contains_key(name) {
132            return Err(MemoryDbError::ClusterNotFound(name.to_string()));
133        }
134
135        // Create final snapshot if requested (before removing cluster)
136        if let Some(snap_name) = final_snapshot_name {
137            self.create_snapshot(account_id, region, snap_name, name, None, vec![])?;
138        }
139
140        let mut cluster = self.clusters.remove(name).unwrap();
141        cluster.status = "deleting".to_string();
142        Ok(cluster)
143    }
144
145    pub fn update_cluster(
146        &mut self,
147        name: &str,
148        description: Option<&str>,
149        security_group_ids: Option<Vec<String>>,
150        maintenance_window: Option<&str>,
151        snapshot_retention_limit: Option<i32>,
152        snapshot_window: Option<&str>,
153        parameter_group_name: Option<&str>,
154        engine_version: Option<&str>,
155        num_shards: Option<i32>,
156        num_replicas_per_shard: Option<i32>,
157        node_type: Option<&str>,
158        acl_name: Option<&str>,
159    ) -> Result<&Cluster, MemoryDbError> {
160        let cluster = self
161            .clusters
162            .get_mut(name)
163            .ok_or_else(|| MemoryDbError::ClusterNotFound(name.to_string()))?;
164
165        if let Some(desc) = description {
166            cluster.description = desc.to_string();
167        }
168        if let Some(sgs) = security_group_ids {
169            cluster.security_group_ids = sgs;
170        }
171        if let Some(mw) = maintenance_window {
172            cluster.maintenance_window = mw.to_string();
173        }
174        if let Some(srl) = snapshot_retention_limit {
175            cluster.snapshot_retention_limit = srl;
176        }
177        if let Some(sw) = snapshot_window {
178            cluster.snapshot_window = sw.to_string();
179        }
180        if let Some(pgn) = parameter_group_name {
181            cluster.parameter_group_name = pgn.to_string();
182        }
183        if let Some(ev) = engine_version {
184            cluster.engine_version = ev.to_string();
185        }
186        if let Some(ns) = num_shards {
187            cluster.num_shards = ns;
188        }
189        if let Some(nr) = num_replicas_per_shard {
190            cluster.num_replicas_per_shard = nr;
191        }
192        if let Some(nt) = node_type {
193            cluster.node_type = nt.to_string();
194        }
195        if let Some(acl) = acl_name {
196            cluster.acl_name = acl.to_string();
197        }
198
199        Ok(self.clusters.get(name).unwrap())
200    }
201
202    // --- Snapshot operations ---
203
204    pub fn create_snapshot(
205        &mut self,
206        account_id: &str,
207        region: &str,
208        snapshot_name: &str,
209        cluster_name: &str,
210        kms_key_id: Option<&str>,
211        tags: Vec<TagData>,
212    ) -> Result<&SnapshotData, MemoryDbError> {
213        if self.snapshots.contains_key(snapshot_name) {
214            return Err(MemoryDbError::SnapshotAlreadyExists(
215                snapshot_name.to_string(),
216            ));
217        }
218
219        let cluster = self
220            .clusters
221            .get(cluster_name)
222            .ok_or_else(|| MemoryDbError::ClusterNotFound(cluster_name.to_string()))?;
223
224        let arn = format!("arn:aws:memorydb:{region}:{account_id}:snapshot/{snapshot_name}");
225        let snapshot = SnapshotData {
226            name: snapshot_name.to_string(),
227            arn: arn.clone(),
228            status: "available".to_string(),
229            source: "manual".to_string(),
230            cluster_name: cluster.name.clone(),
231            cluster_description: cluster.description.clone(),
232            cluster_engine: cluster.engine.clone(),
233            cluster_engine_version: cluster.engine_version.clone(),
234            cluster_node_type: cluster.node_type.clone(),
235            cluster_num_shards: cluster.num_shards,
236            cluster_subnet_group_name: cluster.subnet_group_name.clone(),
237            cluster_snapshot_retention_limit: cluster.snapshot_retention_limit,
238            cluster_snapshot_window: cluster.snapshot_window.clone(),
239            cluster_maintenance_window: cluster.maintenance_window.clone(),
240            cluster_parameter_group_name: cluster.parameter_group_name.clone(),
241            kms_key_id: kms_key_id.map(|s| s.to_string()),
242        };
243
244        self.snapshots.insert(snapshot_name.to_string(), snapshot);
245        if !tags.is_empty() {
246            self.tags.insert(arn, tags);
247        }
248        Ok(self.snapshots.get(snapshot_name).unwrap())
249    }
250
251    pub fn delete_snapshot(&mut self, snapshot_name: &str) -> Result<SnapshotData, MemoryDbError> {
252        match self.snapshots.remove(snapshot_name) {
253            Some(mut snapshot) => {
254                // Clean up tags
255                self.tags.remove(&snapshot.arn);
256                snapshot.status = "deleting".to_string();
257                Ok(snapshot)
258            }
259            None => Err(MemoryDbError::SnapshotNotFound(snapshot_name.to_string())),
260        }
261    }
262
263    pub fn describe_snapshots(
264        &self,
265        cluster_name: Option<&str>,
266        snapshot_name: Option<&str>,
267        source: Option<&str>,
268    ) -> Result<Vec<&SnapshotData>, MemoryDbError> {
269        // When snapshot_name is specified, filter by it (and also by cluster if given)
270        if let Some(name) = snapshot_name {
271            if let Some(snapshot) = self.snapshots.get(name) {
272                // If cluster_name is also given, verify it matches
273                if let Some(cn) = cluster_name
274                    && snapshot.cluster_name != cn
275                {
276                    return Err(MemoryDbError::SnapshotNotFound(name.to_string()));
277                }
278                return Ok(vec![snapshot]);
279            } else {
280                return Err(MemoryDbError::SnapshotNotFound(name.to_string()));
281            }
282        }
283
284        let mut results: Vec<&SnapshotData> = self.snapshots.values().collect();
285
286        if let Some(cn) = cluster_name {
287            results.retain(|s| s.cluster_name == cn);
288        }
289        if let Some(src) = source {
290            results.retain(|s| s.source == src);
291        }
292
293        Ok(results)
294    }
295
296    // --- Subnet group operations ---
297
298    pub fn create_subnet_group(
299        &mut self,
300        account_id: &str,
301        region: &str,
302        name: &str,
303        description: Option<&str>,
304        subnet_ids: Vec<String>,
305        tags: Vec<TagData>,
306    ) -> Result<&SubnetGroupData, MemoryDbError> {
307        if self.subnet_groups.contains_key(name) {
308            return Err(MemoryDbError::SubnetGroupAlreadyExists(name.to_string()));
309        }
310
311        let arn = format!("arn:aws:memorydb:{region}:{account_id}:subnetgroup/{name}");
312        let subnet_group = SubnetGroupData {
313            name: name.to_string(),
314            arn: arn.clone(),
315            description: description.unwrap_or("").to_string(),
316            vpc_id: format!(
317                "vpc-{:012x}",
318                name.as_bytes()
319                    .iter()
320                    .fold(0u64, |acc, &b| acc.wrapping_mul(31).wrapping_add(b as u64))
321            ),
322            subnet_ids,
323        };
324
325        self.subnet_groups.insert(name.to_string(), subnet_group);
326        if !tags.is_empty() {
327            self.tags.insert(arn, tags);
328        }
329        Ok(self.subnet_groups.get(name).unwrap())
330    }
331
332    pub fn delete_subnet_group(&mut self, name: &str) -> Result<SubnetGroupData, MemoryDbError> {
333        if name == "default" {
334            return Err(MemoryDbError::DefaultSubnetGroupCannotBeDeleted);
335        }
336
337        if !self.subnet_groups.contains_key(name) {
338            return Err(MemoryDbError::SubnetGroupNotFound(name.to_string()));
339        }
340
341        // Check if the subnet group is in use by any cluster
342        let in_use = self.clusters.values().any(|c| c.subnet_group_name == name);
343        if in_use {
344            return Err(MemoryDbError::SubnetGroupInUse(name.to_string()));
345        }
346
347        let sg = self.subnet_groups.remove(name).unwrap();
348        self.tags.remove(&sg.arn);
349        Ok(sg)
350    }
351
352    pub fn describe_subnet_groups(
353        &self,
354        name: Option<&str>,
355    ) -> Result<Vec<&SubnetGroupData>, MemoryDbError> {
356        match name {
357            Some(n) => {
358                if let Some(sg) = self.subnet_groups.get(n) {
359                    Ok(vec![sg])
360                } else {
361                    Err(MemoryDbError::SubnetGroupNotFound(n.to_string()))
362                }
363            }
364            None => Ok(self.subnet_groups.values().collect()),
365        }
366    }
367
368    // --- Tag operations ---
369
370    pub fn tag_resource(
371        &mut self,
372        resource_arn: &str,
373        tags: Vec<TagData>,
374    ) -> Result<Vec<TagData>, MemoryDbError> {
375        // Validate that the resource exists
376        self.validate_resource_arn(resource_arn)?;
377
378        let existing = self.tags.entry(resource_arn.to_string()).or_default();
379        for tag in tags {
380            // Update existing tag or add new one
381            if let Some(pos) = existing.iter().position(|t| t.key == tag.key) {
382                existing[pos] = tag;
383            } else {
384                existing.push(tag);
385            }
386        }
387        Ok(existing.clone())
388    }
389
390    pub fn untag_resource(
391        &mut self,
392        resource_arn: &str,
393        tag_keys: &[String],
394    ) -> Result<Vec<TagData>, MemoryDbError> {
395        self.validate_resource_arn(resource_arn)?;
396
397        let existing = self.tags.entry(resource_arn.to_string()).or_default();
398
399        // Validate that all tag keys exist
400        for key in tag_keys {
401            if !existing.iter().any(|t| &t.key == key) {
402                return Err(MemoryDbError::TagNotFound(key.clone()));
403            }
404        }
405
406        existing.retain(|t| !tag_keys.contains(&t.key));
407        Ok(existing.clone())
408    }
409
410    pub fn list_tags(&self, resource_arn: &str) -> Result<Vec<TagData>, MemoryDbError> {
411        self.validate_resource_arn(resource_arn)?;
412
413        Ok(self.tags.get(resource_arn).cloned().unwrap_or_default())
414    }
415
416    fn validate_resource_arn(&self, arn: &str) -> Result<(), MemoryDbError> {
417        // Parse the resource type from the ARN to return a type-specific error
418        // ARN format: arn:aws:memorydb:region:account:resource-type/name
419        if let Some(resource_part) = arn.rsplit(':').next() {
420            if resource_part.starts_with("cluster/") {
421                let name = resource_part.strip_prefix("cluster/").unwrap_or("");
422                let is_cluster = self.clusters.values().any(|c| c.arn == arn);
423                if is_cluster {
424                    return Ok(());
425                }
426                return Err(MemoryDbError::ClusterNotFound(name.to_string()));
427            } else if resource_part.starts_with("snapshot/") {
428                let name = resource_part.strip_prefix("snapshot/").unwrap_or("");
429                let is_snapshot = self.snapshots.values().any(|s| s.arn == arn);
430                if is_snapshot {
431                    return Ok(());
432                }
433                return Err(MemoryDbError::SnapshotNotFound(name.to_string()));
434            } else if resource_part.starts_with("subnetgroup/") {
435                let name = resource_part.strip_prefix("subnetgroup/").unwrap_or("");
436                let is_subnet_group = self.subnet_groups.values().any(|sg| sg.arn == arn);
437                if is_subnet_group {
438                    return Ok(());
439                }
440                return Err(MemoryDbError::SubnetGroupNotFound(name.to_string()));
441            }
442        }
443
444        // Check all resources as fallback
445        let is_cluster = self.clusters.values().any(|c| c.arn == arn);
446        let is_snapshot = self.snapshots.values().any(|s| s.arn == arn);
447        let is_subnet_group = self.subnet_groups.values().any(|sg| sg.arn == arn);
448
449        if is_cluster || is_snapshot || is_subnet_group {
450            Ok(())
451        } else {
452            Err(MemoryDbError::InvalidArn(arn.to_string()))
453        }
454    }
455}