Skip to main content

winterbaume_memorydb/
handlers.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4
5use serde_json::{Value, json};
6use winterbaume_core::{
7    BackendState, MockRequest, MockResponse, MockService, StateChangeNotifier, StatefulService,
8    default_account_id,
9};
10
11use crate::state::{MemoryDbError, MemoryDbState};
12use crate::views::MemoryDbStateView;
13use crate::wire;
14
15/// MemoryDB service handler that processes awsJson1.1 protocol requests.
16pub struct MemoryDbService {
17    pub(crate) state: Arc<BackendState<MemoryDbState>>,
18    pub(crate) notifier: StateChangeNotifier<MemoryDbStateView>,
19}
20
21impl MemoryDbService {
22    pub fn new() -> Self {
23        Self {
24            state: Arc::new(BackendState::new()),
25            notifier: StateChangeNotifier::new(),
26        }
27    }
28}
29
30impl Default for MemoryDbService {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl MockService for MemoryDbService {
37    fn service_name(&self) -> &str {
38        "memory-db"
39    }
40
41    fn url_patterns(&self) -> Vec<&str> {
42        vec![
43            r"https?://memory-db\..*\.amazonaws\.com",
44            r"https?://memory-db\.amazonaws\.com",
45        ]
46    }
47
48    fn handle(
49        &self,
50        request: MockRequest,
51    ) -> Pin<Box<dyn Future<Output = MockResponse> + Send + '_>> {
52        Box::pin(async move { self.dispatch(request).await })
53    }
54}
55
56impl MemoryDbService {
57    async fn dispatch(&self, request: MockRequest) -> MockResponse {
58        let region = winterbaume_core::auth::extract_region_from_uri(&request.uri);
59        let account_id = default_account_id();
60
61        // Extract action from X-Amz-Target header
62        // Format: "AmazonMemoryDB.CreateCluster"
63        let action = request
64            .headers
65            .get("x-amz-target")
66            .and_then(|v| v.to_str().ok())
67            .and_then(|v| v.split('.').next_back())
68            .map(|s| s.to_string());
69
70        let action = match action {
71            Some(a) => a,
72            None => {
73                return json_error_response(400, "MissingAction", "Missing X-Amz-Target header");
74            }
75        };
76
77        // Validate the body is well-formed JSON up-front; the typed deserialisers in
78        // `wire` re-parse the bytes per operation.
79        if serde_json::from_slice::<Value>(&request.body).is_err() {
80            return json_error_response(400, "SerializationException", "Invalid JSON body");
81        }
82        let body_bytes: &[u8] = &request.body;
83
84        let state = self.state.get(account_id, &region);
85
86        let response = match action.as_str() {
87            "CreateCluster" => {
88                self.handle_create_cluster(&state, body_bytes, account_id, &region)
89                    .await
90            }
91            "DescribeClusters" => self.handle_describe_clusters(&state, body_bytes).await,
92            "DeleteCluster" => {
93                self.handle_delete_cluster(&state, body_bytes, account_id, &region)
94                    .await
95            }
96            "UpdateCluster" => self.handle_update_cluster(&state, body_bytes).await,
97            "CreateSnapshot" => {
98                self.handle_create_snapshot(&state, body_bytes, account_id, &region)
99                    .await
100            }
101            "DeleteSnapshot" => self.handle_delete_snapshot(&state, body_bytes).await,
102            "DescribeSnapshots" => self.handle_describe_snapshots(&state, body_bytes).await,
103            "CreateSubnetGroup" => {
104                self.handle_create_subnet_group(&state, body_bytes, account_id, &region)
105                    .await
106            }
107            "DeleteSubnetGroup" => self.handle_delete_subnet_group(&state, body_bytes).await,
108            "DescribeSubnetGroups" => self.handle_describe_subnet_groups(&state, body_bytes).await,
109            "TagResource" => self.handle_tag_resource(&state, body_bytes).await,
110            "UntagResource" => self.handle_untag_resource(&state, body_bytes).await,
111            "ListTags" => self.handle_list_tags(&state, body_bytes).await,
112            _ => json_error_response(
113                400,
114                "InvalidAction",
115                &format!("Could not find operation {action} for MemoryDB"),
116            ),
117        };
118
119        if matches!(
120            action.as_str(),
121            "CreateCluster"
122                | "DeleteCluster"
123                | "UpdateCluster"
124                | "CreateSnapshot"
125                | "DeleteSnapshot"
126                | "CreateSubnetGroup"
127                | "DeleteSubnetGroup"
128                | "TagResource"
129                | "UntagResource"
130        ) && response.status / 100 == 2
131        {
132            self.notify_state_changed(account_id, &region).await;
133        }
134        response
135    }
136
137    async fn handle_create_cluster(
138        &self,
139        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
140        body: &[u8],
141        account_id: &str,
142        region: &str,
143    ) -> MockResponse {
144        let input = match wire::deserialize_create_cluster_request(body) {
145            Ok(v) => v,
146            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
147        };
148        if input.cluster_name.is_empty() {
149            return json_error_response(
150                400,
151                "InvalidParameterValueException",
152                "ClusterName is required",
153            );
154        }
155        if input.node_type.is_empty() {
156            return json_error_response(
157                400,
158                "InvalidParameterValueException",
159                "NodeType is required",
160            );
161        }
162        if input.a_c_l_name.is_empty() {
163            return json_error_response(
164                400,
165                "InvalidParameterValueException",
166                "ACLName is required",
167            );
168        }
169
170        let description = input.description.as_deref();
171        let num_shards = input.num_shards;
172        let num_replicas_per_shard = input.num_replicas_per_shard;
173        let subnet_group_name = input.subnet_group_name.as_deref();
174        let security_group_ids = input.security_group_ids.unwrap_or_default();
175        let engine_version = input.engine_version.as_deref();
176        let maintenance_window = input.maintenance_window.as_deref();
177        let snapshot_retention_limit = input.snapshot_retention_limit;
178        let snapshot_window = input.snapshot_window.as_deref();
179        let parameter_group_name = input.parameter_group_name.as_deref();
180        let tls_enabled = input.t_l_s_enabled;
181        let auto_minor_version_upgrade = input.auto_minor_version_upgrade;
182        let tags = wire_tags_to_data(input.tags.as_deref());
183
184        let mut state = state.write().await;
185        match state.create_cluster(
186            account_id,
187            region,
188            &input.cluster_name,
189            &input.node_type,
190            &input.a_c_l_name,
191            description,
192            num_shards,
193            num_replicas_per_shard,
194            subnet_group_name,
195            security_group_ids,
196            engine_version,
197            maintenance_window,
198            snapshot_retention_limit,
199            snapshot_window,
200            parameter_group_name,
201            tls_enabled,
202            auto_minor_version_upgrade,
203            tags,
204        ) {
205            Ok(cluster) => wire::serialize_create_cluster_response(&wire::CreateClusterResponse {
206                cluster: Some(cluster_to_wire(cluster)),
207            }),
208            Err(e) => memorydb_error_response(&e),
209        }
210    }
211
212    async fn handle_describe_clusters(
213        &self,
214        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
215        body: &[u8],
216    ) -> MockResponse {
217        let input = match wire::deserialize_describe_clusters_request(body) {
218            Ok(v) => v,
219            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
220        };
221        let cluster_name = input.cluster_name.as_deref();
222        let show_shard_details = input.show_shard_details.unwrap_or(false);
223
224        let state = state.read().await;
225        match state.describe_clusters(cluster_name) {
226            Ok(clusters) => {
227                wire::serialize_describe_clusters_response(&wire::DescribeClustersResponse {
228                    clusters: Some(
229                        clusters
230                            .iter()
231                            .map(|c| cluster_to_wire_with_shards(c, show_shard_details))
232                            .collect(),
233                    ),
234                    next_token: None,
235                })
236            }
237            Err(e) => memorydb_error_response(&e),
238        }
239    }
240
241    async fn handle_delete_cluster(
242        &self,
243        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
244        body: &[u8],
245        account_id: &str,
246        region: &str,
247    ) -> MockResponse {
248        let input = match wire::deserialize_delete_cluster_request(body) {
249            Ok(v) => v,
250            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
251        };
252        if input.cluster_name.is_empty() {
253            return json_error_response(
254                400,
255                "InvalidParameterValueException",
256                "ClusterName is required",
257            );
258        }
259        let final_snapshot_name = input.final_snapshot_name.as_deref();
260
261        let mut state = state.write().await;
262        match state.delete_cluster(&input.cluster_name, final_snapshot_name, account_id, region) {
263            Ok(cluster) => wire::serialize_delete_cluster_response(&wire::DeleteClusterResponse {
264                cluster: Some(cluster_to_wire(&cluster)),
265            }),
266            Err(e) => memorydb_error_response(&e),
267        }
268    }
269
270    async fn handle_update_cluster(
271        &self,
272        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
273        body: &[u8],
274    ) -> MockResponse {
275        let input = match wire::deserialize_update_cluster_request(body) {
276            Ok(v) => v,
277            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
278        };
279        if input.cluster_name.is_empty() {
280            return json_error_response(
281                400,
282                "InvalidParameterValueException",
283                "ClusterName is required",
284            );
285        }
286
287        let description = input.description.as_deref();
288        let security_group_ids = input.security_group_ids;
289        let maintenance_window = input.maintenance_window.as_deref();
290        let snapshot_retention_limit = input.snapshot_retention_limit;
291        let snapshot_window = input.snapshot_window.as_deref();
292        let parameter_group_name = input.parameter_group_name.as_deref();
293        let engine_version = input.engine_version.as_deref();
294        let num_shards = input
295            .shard_configuration
296            .as_ref()
297            .and_then(|s| s.shard_count);
298        let num_replicas_per_shard = input
299            .replica_configuration
300            .as_ref()
301            .and_then(|r| r.replica_count);
302        let node_type = input.node_type.as_deref();
303        let acl_name = input.a_c_l_name.as_deref();
304
305        let mut state = state.write().await;
306        match state.update_cluster(
307            &input.cluster_name,
308            description,
309            security_group_ids,
310            maintenance_window,
311            snapshot_retention_limit,
312            snapshot_window,
313            parameter_group_name,
314            engine_version,
315            num_shards,
316            num_replicas_per_shard,
317            node_type,
318            acl_name,
319        ) {
320            Ok(cluster) => wire::serialize_update_cluster_response(&wire::UpdateClusterResponse {
321                cluster: Some(cluster_to_wire(cluster)),
322            }),
323            Err(e) => memorydb_error_response(&e),
324        }
325    }
326
327    // --- Snapshot operations ---
328
329    async fn handle_create_snapshot(
330        &self,
331        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
332        body: &[u8],
333        account_id: &str,
334        region: &str,
335    ) -> MockResponse {
336        let input = match wire::deserialize_create_snapshot_request(body) {
337            Ok(v) => v,
338            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
339        };
340        if input.snapshot_name.is_empty() {
341            return json_error_response(
342                400,
343                "InvalidParameterValueException",
344                "SnapshotName is required",
345            );
346        }
347        if input.cluster_name.is_empty() {
348            return json_error_response(
349                400,
350                "InvalidParameterValueException",
351                "ClusterName is required",
352            );
353        }
354
355        let kms_key_id = input.kms_key_id.as_deref();
356        let tags = wire_tags_to_data(input.tags.as_deref());
357
358        let mut state = state.write().await;
359        match state.create_snapshot(
360            account_id,
361            region,
362            &input.snapshot_name,
363            &input.cluster_name,
364            kms_key_id,
365            tags,
366        ) {
367            Ok(snapshot) => {
368                wire::serialize_create_snapshot_response(&wire::CreateSnapshotResponse {
369                    snapshot: Some(snapshot_to_wire(snapshot)),
370                })
371            }
372            Err(e) => memorydb_error_response(&e),
373        }
374    }
375
376    async fn handle_delete_snapshot(
377        &self,
378        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
379        body: &[u8],
380    ) -> MockResponse {
381        let input = match wire::deserialize_delete_snapshot_request(body) {
382            Ok(v) => v,
383            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
384        };
385        if input.snapshot_name.is_empty() {
386            return json_error_response(
387                400,
388                "InvalidParameterValueException",
389                "SnapshotName is required",
390            );
391        }
392
393        let mut state = state.write().await;
394        match state.delete_snapshot(&input.snapshot_name) {
395            Ok(snapshot) => {
396                wire::serialize_delete_snapshot_response(&wire::DeleteSnapshotResponse {
397                    snapshot: Some(snapshot_to_wire(&snapshot)),
398                })
399            }
400            Err(e) => memorydb_error_response(&e),
401        }
402    }
403
404    async fn handle_describe_snapshots(
405        &self,
406        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
407        body: &[u8],
408    ) -> MockResponse {
409        let input = match wire::deserialize_describe_snapshots_request(body) {
410            Ok(v) => v,
411            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
412        };
413        let cluster_name = input.cluster_name.as_deref();
414        let snapshot_name = input.snapshot_name.as_deref();
415        let source = input.source.as_deref();
416        let show_detail = input.show_detail.unwrap_or(false);
417
418        let state = state.read().await;
419        match state.describe_snapshots(cluster_name, snapshot_name, source) {
420            Ok(snapshots) => {
421                wire::serialize_describe_snapshots_response(&wire::DescribeSnapshotsResponse {
422                    snapshots: Some(
423                        snapshots
424                            .iter()
425                            .map(|s| snapshot_to_wire_with_details(s, show_detail))
426                            .collect(),
427                    ),
428                    next_token: None,
429                })
430            }
431            Err(e) => memorydb_error_response(&e),
432        }
433    }
434
435    // --- Subnet group operations ---
436
437    async fn handle_create_subnet_group(
438        &self,
439        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
440        body: &[u8],
441        account_id: &str,
442        region: &str,
443    ) -> MockResponse {
444        let input = match wire::deserialize_create_subnet_group_request(body) {
445            Ok(v) => v,
446            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
447        };
448        if input.subnet_group_name.is_empty() {
449            return json_error_response(
450                400,
451                "InvalidParameterValueException",
452                "SubnetGroupName is required",
453            );
454        }
455
456        let subnet_ids = input.subnet_ids;
457        let description = input.description.as_deref();
458        let tags = wire_tags_to_data(input.tags.as_deref());
459
460        let mut state = state.write().await;
461        match state.create_subnet_group(
462            account_id,
463            region,
464            &input.subnet_group_name,
465            description,
466            subnet_ids,
467            tags,
468        ) {
469            Ok(sg) => {
470                wire::serialize_create_subnet_group_response(&wire::CreateSubnetGroupResponse {
471                    subnet_group: Some(subnet_group_to_wire(sg)),
472                })
473            }
474            Err(e) => memorydb_error_response(&e),
475        }
476    }
477
478    async fn handle_delete_subnet_group(
479        &self,
480        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
481        body: &[u8],
482    ) -> MockResponse {
483        let input = match wire::deserialize_delete_subnet_group_request(body) {
484            Ok(v) => v,
485            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
486        };
487        if input.subnet_group_name.is_empty() {
488            return json_error_response(
489                400,
490                "InvalidParameterValueException",
491                "SubnetGroupName is required",
492            );
493        }
494
495        let mut state = state.write().await;
496        match state.delete_subnet_group(&input.subnet_group_name) {
497            Ok(sg) => {
498                wire::serialize_delete_subnet_group_response(&wire::DeleteSubnetGroupResponse {
499                    subnet_group: Some(subnet_group_to_wire(&sg)),
500                })
501            }
502            Err(e) => memorydb_error_response(&e),
503        }
504    }
505
506    async fn handle_describe_subnet_groups(
507        &self,
508        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
509        body: &[u8],
510    ) -> MockResponse {
511        let input = match wire::deserialize_describe_subnet_groups_request(body) {
512            Ok(v) => v,
513            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
514        };
515        let name = input.subnet_group_name.as_deref();
516
517        let state = state.read().await;
518        match state.describe_subnet_groups(name) {
519            Ok(groups) => wire::serialize_describe_subnet_groups_response(
520                &wire::DescribeSubnetGroupsResponse {
521                    subnet_groups: Some(groups.iter().map(|sg| subnet_group_to_wire(sg)).collect()),
522                    next_token: None,
523                },
524            ),
525            Err(e) => memorydb_error_response(&e),
526        }
527    }
528
529    // --- Tag operations ---
530
531    async fn handle_tag_resource(
532        &self,
533        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
534        body: &[u8],
535    ) -> MockResponse {
536        let input = match wire::deserialize_tag_resource_request(body) {
537            Ok(v) => v,
538            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
539        };
540        if input.resource_arn.is_empty() {
541            return json_error_response(
542                400,
543                "InvalidParameterValueException",
544                "ResourceArn is required",
545            );
546        }
547
548        let tags = wire_tags_to_data(Some(input.tags.as_slice()));
549        if tags.is_empty() {
550            return json_error_response(400, "InvalidParameterValueException", "Tags is required");
551        }
552
553        let mut state = state.write().await;
554        match state.tag_resource(&input.resource_arn, tags) {
555            Ok(tag_list) => wire::serialize_tag_resource_response(&wire::TagResourceResponse {
556                tag_list: Some(tags_to_wire(&tag_list)),
557            }),
558            Err(e) => memorydb_error_response(&e),
559        }
560    }
561
562    async fn handle_untag_resource(
563        &self,
564        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
565        body: &[u8],
566    ) -> MockResponse {
567        let input = match wire::deserialize_untag_resource_request(body) {
568            Ok(v) => v,
569            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
570        };
571        if input.resource_arn.is_empty() {
572            return json_error_response(
573                400,
574                "InvalidParameterValueException",
575                "ResourceArn is required",
576            );
577        }
578
579        let mut state = state.write().await;
580        match state.untag_resource(&input.resource_arn, &input.tag_keys) {
581            Ok(tag_list) => wire::serialize_untag_resource_response(&wire::UntagResourceResponse {
582                tag_list: Some(tags_to_wire(&tag_list)),
583            }),
584            Err(e) => memorydb_error_response(&e),
585        }
586    }
587
588    async fn handle_list_tags(
589        &self,
590        state: &Arc<tokio::sync::RwLock<MemoryDbState>>,
591        body: &[u8],
592    ) -> MockResponse {
593        let input = match wire::deserialize_list_tags_request(body) {
594            Ok(v) => v,
595            Err(e) => return json_error_response(400, "InvalidParameterValueException", &e),
596        };
597        if input.resource_arn.is_empty() {
598            return json_error_response(
599                400,
600                "InvalidParameterValueException",
601                "ResourceArn is required",
602            );
603        }
604
605        let state = state.read().await;
606        match state.list_tags(&input.resource_arn) {
607            Ok(tag_list) => wire::serialize_list_tags_response(&wire::ListTagsResponse {
608                tag_list: Some(tags_to_wire(&tag_list)),
609            }),
610            Err(e) => memorydb_error_response(&e),
611        }
612    }
613}
614
615// --- Utility functions ---
616
617fn cluster_to_wire(cluster: &crate::types::Cluster) -> wire::Cluster {
618    cluster_to_wire_with_shards(cluster, false)
619}
620
621fn cluster_to_wire_with_shards(
622    cluster: &crate::types::Cluster,
623    show_shard_details: bool,
624) -> wire::Cluster {
625    let shards = if show_shard_details {
626        Some(generate_shards(
627            cluster.num_shards,
628            cluster.num_replicas_per_shard,
629        ))
630    } else {
631        None
632    };
633
634    wire::Cluster {
635        name: Some(cluster.name.clone()),
636        a_r_n: Some(cluster.arn.clone()),
637        status: Some(cluster.status.clone()),
638        node_type: Some(cluster.node_type.clone()),
639        number_of_shards: Some(cluster.num_shards),
640        description: Some(cluster.description.clone()),
641        engine: Some(cluster.engine.clone()),
642        engine_version: Some(cluster.engine_version.clone()),
643        subnet_group_name: Some(cluster.subnet_group_name.clone()),
644        security_groups: Some(
645            cluster
646                .security_group_ids
647                .iter()
648                .map(|sg| wire::SecurityGroupMembership {
649                    security_group_id: Some(sg.clone()),
650                    status: Some("active".to_string()),
651                })
652                .collect(),
653        ),
654        maintenance_window: Some(cluster.maintenance_window.clone()),
655        snapshot_retention_limit: Some(cluster.snapshot_retention_limit),
656        snapshot_window: Some(cluster.snapshot_window.clone()),
657        a_c_l_name: Some(cluster.acl_name.clone()),
658        parameter_group_name: Some(cluster.parameter_group_name.clone()),
659        t_l_s_enabled: Some(cluster.tls_enabled),
660        auto_minor_version_upgrade: Some(cluster.auto_minor_version_upgrade),
661        shards,
662        ..Default::default()
663    }
664}
665
666/// Generate mock shard data matching moto behavior.
667/// Each shard has num_replicas + 1 nodes (1 primary + N replicas).
668fn generate_shards(num_shards: i32, num_replicas: i32) -> Vec<wire::Shard> {
669    let total_slots = 16384;
670    let slots_per_shard = total_slots / num_shards;
671    (0..num_shards)
672        .map(|i| {
673            let start = i * slots_per_shard;
674            let end = if i == num_shards - 1 {
675                total_slots - 1
676            } else {
677                (i + 1) * slots_per_shard - 1
678            };
679            wire::Shard {
680                name: Some(format!("{:04}", i + 1)),
681                number_of_nodes: Some(num_replicas + 1),
682                slots: Some(format!("{start}-{end}")),
683                status: Some("available".to_string()),
684                ..Default::default()
685            }
686        })
687        .collect()
688}
689
690fn memorydb_error_response(err: &MemoryDbError) -> MockResponse {
691    let (error_type, status) = match err {
692        MemoryDbError::ClusterAlreadyExists(_) => ("ClusterAlreadyExistsFault", 400),
693        MemoryDbError::ClusterNotFound(_) => ("ClusterNotFoundFault", 400),
694        MemoryDbError::SnapshotAlreadyExists(_) => ("SnapshotAlreadyExistsFault", 400),
695        MemoryDbError::SnapshotNotFound(_) => ("SnapshotNotFoundFault", 400),
696        MemoryDbError::SubnetGroupAlreadyExists(_) => ("SubnetGroupAlreadyExistsFault", 400),
697        MemoryDbError::SubnetGroupNotFound(_) => ("SubnetGroupNotFoundFault", 400),
698        MemoryDbError::SubnetGroupInUse(_) => ("SubnetGroupInUseFault", 400),
699        MemoryDbError::DefaultSubnetGroupCannotBeDeleted => ("InvalidParameterValueException", 400),
700        MemoryDbError::TagNotFound(_) => ("TagNotFoundFault", 400),
701        MemoryDbError::InvalidArn(_) => ("InvalidARNFault", 400),
702    };
703    let body = json!({
704        "__type": error_type,
705        "message": err.to_string(),
706    });
707    MockResponse::json(status, body.to_string())
708}
709
710fn snapshot_to_wire(snapshot: &crate::types::SnapshotData) -> wire::Snapshot {
711    snapshot_to_wire_with_details(snapshot, false)
712}
713
714fn snapshot_to_wire_with_details(
715    snapshot: &crate::types::SnapshotData,
716    show_detail: bool,
717) -> wire::Snapshot {
718    let shards = if show_detail {
719        Some(vec![wire::ShardDetail {
720            name: Some("0001".to_string()),
721            configuration: Some(wire::ShardConfiguration {
722                slots: Some("0-16383".to_string()),
723                replica_count: Some(1),
724            }),
725            size: Some("10".to_string()),
726            ..Default::default()
727        }])
728    } else {
729        None
730    };
731
732    wire::Snapshot {
733        name: Some(snapshot.name.clone()),
734        a_r_n: Some(snapshot.arn.clone()),
735        status: Some(snapshot.status.clone()),
736        source: Some(snapshot.source.clone()),
737        cluster_configuration: Some(wire::ClusterConfiguration {
738            name: Some(snapshot.cluster_name.clone()),
739            description: Some(snapshot.cluster_description.clone()),
740            engine: Some(snapshot.cluster_engine.clone()),
741            engine_version: Some(snapshot.cluster_engine_version.clone()),
742            node_type: Some(snapshot.cluster_node_type.clone()),
743            num_shards: Some(snapshot.cluster_num_shards),
744            subnet_group_name: Some(snapshot.cluster_subnet_group_name.clone()),
745            snapshot_retention_limit: Some(snapshot.cluster_snapshot_retention_limit),
746            snapshot_window: Some(snapshot.cluster_snapshot_window.clone()),
747            maintenance_window: Some(snapshot.cluster_maintenance_window.clone()),
748            parameter_group_name: Some(snapshot.cluster_parameter_group_name.clone()),
749            shards,
750            ..Default::default()
751        }),
752        kms_key_id: snapshot.kms_key_id.clone(),
753        data_tiering: Some("false".to_string()),
754        ..Default::default()
755    }
756}
757
758fn subnet_group_to_wire(sg: &crate::types::SubnetGroupData) -> wire::SubnetGroup {
759    wire::SubnetGroup {
760        name: Some(sg.name.clone()),
761        a_r_n: Some(sg.arn.clone()),
762        description: Some(sg.description.clone()),
763        vpc_id: Some(sg.vpc_id.clone()),
764        subnets: Some(
765            sg.subnet_ids
766                .iter()
767                .map(|sid| wire::Subnet {
768                    identifier: Some(sid.clone()),
769                    availability_zone: Some(wire::AvailabilityZone {
770                        name: Some(az_for_subnet(sid)),
771                    }),
772                    ..Default::default()
773                })
774                .collect(),
775        ),
776        ..Default::default()
777    }
778}
779
780/// Derive a stable, plausible AZ name from a subnet id by mapping the trailing
781/// character of the id to one of three AZs. Distinct subnets in the same group
782/// will therefore typically advertise distinct AZs in describe responses.
783fn az_for_subnet(subnet_id: &str) -> String {
784    const ZONES: [&str; 3] = ["us-east-1a", "us-east-1b", "us-east-1c"];
785    let idx = subnet_id
786        .chars()
787        .last()
788        .map(|c| (c as usize) % ZONES.len())
789        .unwrap_or(0);
790    ZONES[idx].to_string()
791}
792
793fn tags_to_wire(tags: &[crate::types::TagData]) -> Vec<wire::Tag> {
794    tags.iter()
795        .map(|t| wire::Tag {
796            key: Some(t.key.clone()),
797            value: Some(t.value.clone()),
798        })
799        .collect()
800}
801
802fn wire_tags_to_data(tags: Option<&[wire::Tag]>) -> Vec<crate::types::TagData> {
803    tags.map(|arr| {
804        arr.iter()
805            .filter_map(|t| {
806                let key = t.key.as_deref()?.to_string();
807                let value = t.value.as_deref().unwrap_or("").to_string();
808                Some(crate::types::TagData { key, value })
809            })
810            .collect()
811    })
812    .unwrap_or_default()
813}
814
815fn json_error_response(status: u16, code: &str, message: &str) -> MockResponse {
816    let body = json!({
817        "__type": code,
818        "message": message,
819    });
820    MockResponse::json(status, body.to_string())
821}