fakecloud-cloudformation 0.40.0

CloudFormation implementation for FakeCloud
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! `AWS::AmazonMQ::Broker`, `AWS::AmazonMQ::Configuration`, and
//! `AWS::AmazonMQ::ConfigurationAssociation` CloudFormation provisioning. Each
//! resource is written through to the `mq` service state as the same wire JSON
//! the direct `CreateBroker` / `CreateConfiguration` handlers store, so a
//! CFN-created broker or configuration reads back identically on
//! `DescribeBroker` / `DescribeConfiguration` and persists through the `mq`
//! snapshot hook (survives a restart -- the #1766 phantom-resource lesson).
//!
//! Physical id + `Ref`:
//!   Broker        -> `BrokerId` (`b-<uuid>`)
//!   Configuration -> `Id` (`c-<uuid>`)
//!
//! `Fn::GetAtt` (verified against the AWS resource spec):
//!   Broker        -> Arn, IpAddresses, OpenWireEndpoints, AmqpEndpoints,
//!                    StompEndpoints, MqttEndpoints, WssEndpoints,
//!                    ConfigurationId, ConfigurationRevision
//!   Configuration -> Arn, Id, Revision

use serde_json::{json, Value};
use uuid::Uuid;

use fakecloud_mq::shared as mq_shared;

use super::{ProvisionResult, ResourceDefinition, ResourceProvisioner, StackResource};

impl ResourceProvisioner {
    // -------------------------------------------------------------- Broker

    pub(super) fn create_mq_broker(
        &self,
        resource: &ResourceDefinition,
    ) -> Result<ProvisionResult, String> {
        let props = &resource.properties;
        let name = mq_str(props, "BrokerName").unwrap_or_else(|| resource.logical_id.clone());
        let region = self.region.clone();
        let account = self.account_id.clone();

        // Translate the CFN PascalCase properties into a restJson1 `CreateBroker`
        // body and go through the exact same shared create path the direct API
        // uses, so a CFN-created broker is byte-for-byte identical (users,
        // synthesized subnets, auto-configuration, logs, encryption, tags) --
        // the two paths cannot diverge (#1766).
        let body = cfn_broker_body(props, &name);
        let engine = body
            .get("engineType")
            .and_then(Value::as_str)
            .unwrap_or("ACTIVEMQ")
            .to_string();
        let deployment = body
            .get("deploymentMode")
            .and_then(Value::as_str)
            .unwrap_or("SINGLE_INSTANCE")
            .to_string();

        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        // Broker names are unique per account+region (matching the API handler).
        if acct.brokers.values().any(|b| {
            b.get("brokerName").and_then(Value::as_str) == Some(name.as_str())
                && mq_shared::broker_region(b) == Some(region.as_str())
        }) {
            return Err(format!("Broker name {name} already exists"));
        }

        let (id, arn) = mq_shared::create_broker_record(acct, &account, &region, &body);
        // With an MQ container runtime configured, the broker is left
        // CREATION_IN_PROGRESS and backed by a REAL ActiveMQ/RabbitMQ container
        // in the background (drained after provisioning), settling to RUNNING
        // once it accepts connections -- the same container the direct
        // `CreateBroker` path spawns. Without a runtime (CI / metadata-only),
        // settle it through the in-memory lifecycle so the stack still reaches
        // CREATE_COMPLETE.
        let back_with_container = self.mq_runtime.is_some();
        if !back_with_container {
            acct.reconcile_brokers(true);
        }

        let (config_id, config_rev) = broker_current_config(acct.brokers.get(&id));
        if back_with_container {
            self.pending_container_spawns
                .lock()
                .push(super::ContainerSpawnIntent::MqBroker {
                    broker_id: id.clone(),
                });
        }
        Ok(broker_attributes(
            id,
            arn,
            &engine,
            &region,
            &deployment,
            &config_id,
            config_rev,
        ))
    }

    pub(super) fn update_mq_broker(
        &self,
        existing: &StackResource,
        resource: &ResourceDefinition,
    ) -> Result<ProvisionResult, String> {
        let props = &resource.properties;
        let id = existing.physical_id.clone();
        let new_name = mq_str(props, "BrokerName").unwrap_or_else(|| existing.logical_id.clone());
        let new_engine = mq_str(props, "EngineType")
            .unwrap_or_else(|| "ACTIVEMQ".to_string())
            .to_uppercase();
        let new_deployment =
            mq_str(props, "DeploymentMode").unwrap_or_else(|| "SINGLE_INSTANCE".to_string());

        let (old_name, old_engine, old_deployment) = {
            let guard = self.mq_state.read();
            let b = guard.get(&self.account_id).and_then(|a| a.brokers.get(&id));
            (
                b.and_then(|b| b.get("brokerName"))
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
                b.and_then(|b| b.get("engineType"))
                    .and_then(Value::as_str)
                    .unwrap_or("ACTIVEMQ")
                    .to_string(),
                b.and_then(|b| b.get("deploymentMode"))
                    .and_then(Value::as_str)
                    .unwrap_or("SINGLE_INSTANCE")
                    .to_string(),
            )
        };
        // BrokerName, EngineType, and DeploymentMode are replacement-required.
        if new_name != old_name || new_engine != old_engine || new_deployment != old_deployment {
            self.delete_mq_broker(&id);
            return self.create_mq_broker(resource);
        }

        let region = self.region.clone();
        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        let arn = acct
            .brokers
            .get(&id)
            .and_then(|b| b.get("brokerArn"))
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let (config_id, config_rev) = {
            let broker = acct
                .brokers
                .get_mut(&id)
                .ok_or_else(|| format!("MQ broker {id} not yet provisioned"))?;
            let obj = broker.as_object_mut().expect("broker is an object");
            if let Some(v) = mq_str(props, "HostInstanceType") {
                obj.insert("hostInstanceType".into(), json!(v));
            }
            if let Some(v) = mq_str(props, "EngineVersion") {
                obj.insert("engineVersion".into(), json!(v));
            }
            if props.get("SecurityGroups").is_some() {
                obj.insert(
                    "securityGroups".into(),
                    mq_string_list(props, "SecurityGroups"),
                );
            }
            obj.insert(
                "autoMinorVersionUpgrade".into(),
                json!(mq_bool(props, "AutoMinorVersionUpgrade")),
            );
            if let Some(cfg) = props.get("Configuration") {
                let cid = cfg
                    .get("Id")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string();
                let rev = cfg.get("Revision").and_then(Value::as_i64).unwrap_or(1);
                // Preserve configuration history: push the prior current onto
                // history rather than discarding it.
                mq_shared::set_broker_configuration(obj, &cid, rev);
            }
            let configs = obj.get("configurations");
            (
                configs
                    .and_then(|c| c.get("current"))
                    .and_then(|c| c.get("id"))
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
                configs
                    .and_then(|c| c.get("current"))
                    .and_then(|c| c.get("revision"))
                    .and_then(Value::as_i64)
                    .unwrap_or(0),
            )
        };
        let tags = mq_tags(props);
        if tags.is_empty() {
            acct.tags.remove(&arn);
        } else {
            acct.tags.insert(arn.clone(), tags);
        }
        Ok(broker_attributes(
            id,
            arn,
            &old_engine,
            &region,
            &old_deployment,
            &config_id,
            config_rev,
        ))
    }

    pub(super) fn get_att_mq_broker(&self, physical_id: &str, attribute: &str) -> Option<String> {
        let guard = self.mq_state.read();
        let acct = guard.get(&self.account_id)?;
        let b = acct.brokers.get(physical_id)?;
        if attribute == "Arn" {
            return b
                .get("brokerArn")
                .and_then(Value::as_str)
                .map(str::to_string);
        }
        let engine = b
            .get("engineType")
            .and_then(Value::as_str)
            .unwrap_or("ACTIVEMQ");
        let deployment = b
            .get("deploymentMode")
            .and_then(Value::as_str)
            .unwrap_or("SINGLE_INSTANCE");
        let cfg = b.get("configurations").and_then(|c| c.get("current"));
        let cid = cfg
            .and_then(|c| c.get("id"))
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let crev = cfg
            .and_then(|c| c.get("revision"))
            .and_then(Value::as_i64)
            .unwrap_or(0);
        let res = broker_attributes(
            physical_id.to_string(),
            b.get("brokerArn")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
            engine,
            &self.region,
            deployment,
            &cid,
            crev,
        );
        res.attributes.get(attribute).cloned()
    }

    pub(super) fn delete_mq_broker(&self, physical_id: &str) {
        {
            let mut guard = self.mq_state.write();
            let acct = guard.get_or_create(&self.account_id);
            if let Some(b) = acct.brokers.remove(physical_id) {
                if let Some(arn) = b.get("brokerArn").and_then(Value::as_str) {
                    acct.tags.remove(arn);
                }
            }
            acct.users.remove(physical_id);
            acct.data_plane.remove(physical_id);
        }
        // Reap the REAL backing container (if any) off the request path.
        if self.mq_runtime.is_some() {
            self.pending_container_teardowns.lock().push(
                super::ContainerTeardownIntent::MqBroker {
                    broker_id: physical_id.to_string(),
                },
            );
        }
    }

    // -------------------------------------------------------- Configuration

    pub(super) fn create_mq_configuration(
        &self,
        resource: &ResourceDefinition,
    ) -> Result<ProvisionResult, String> {
        let props = &resource.properties;
        let name = mq_str(props, "Name").unwrap_or_else(|| resource.logical_id.clone());
        let engine = mq_str(props, "EngineType")
            .unwrap_or_else(|| "ACTIVEMQ".to_string())
            .to_uppercase();
        let engine_version = mq_str(props, "EngineVersion")
            .unwrap_or_else(|| mq_shared::default_engine_version(&engine).to_string());
        let auth = mq_str(props, "AuthenticationStrategy").unwrap_or_else(|| "SIMPLE".to_string());
        let description = mq_str(props, "Description").unwrap_or_default();
        let data = mq_str(props, "Data").unwrap_or_else(|| mq_shared::default_config_data(&engine));
        let region = self.region.clone();
        let account = self.account_id.clone();
        let id = format!("c-{}", Uuid::new_v4());
        let arn = mq_shared::config_arn(&region, &account, &id);
        let created = mq_shared::now_iso();

        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        acct.configurations.insert(
            id.clone(),
            json!({
                "arn": arn,
                "authenticationStrategy": auth,
                "created": created,
                "description": description,
                "engineType": engine,
                "engineVersion": engine_version,
                "id": id,
                "latestRevision": { "revision": 1, "created": created, "description": description },
                "name": name,
            }),
        );
        acct.configuration_revisions.insert(
            id.clone(),
            vec![json!({ "revision": 1, "created": created, "description": description, "data": data })],
        );
        let tags = mq_tags(props);
        if !tags.is_empty() {
            acct.tags.insert(arn.clone(), tags);
        }

        Ok(ProvisionResult::new(id.clone())
            .with("Arn", arn)
            .with("Id", id)
            .with("Revision", "1"))
    }

    pub(super) fn update_mq_configuration(
        &self,
        existing: &StackResource,
        resource: &ResourceDefinition,
    ) -> Result<ProvisionResult, String> {
        let props = &resource.properties;
        let id = existing.physical_id.clone();
        // EngineType is replacement-required; a change re-provisions from scratch.
        let new_engine = mq_str(props, "EngineType")
            .unwrap_or_else(|| "ACTIVEMQ".to_string())
            .to_uppercase();
        let old_engine = {
            let guard = self.mq_state.read();
            guard
                .get(&self.account_id)
                .and_then(|a| a.configurations.get(&id))
                .and_then(|c| c.get("engineType"))
                .and_then(Value::as_str)
                .unwrap_or("ACTIVEMQ")
                .to_string()
        };
        if new_engine != old_engine {
            self.delete_mq_configuration(&id);
            return self.create_mq_configuration(resource);
        }

        let description = mq_str(props, "Description").unwrap_or_default();
        let data = mq_str(props, "Data");
        let created = mq_shared::now_iso();
        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        let arn = {
            let revs = acct.configuration_revisions.entry(id.clone()).or_default();
            let next = revs
                .iter()
                .filter_map(|r| r.get("revision").and_then(Value::as_i64))
                .max()
                .unwrap_or(0)
                + 1;
            revs.push(json!({
                "revision": next,
                "created": created,
                "description": description,
                "data": data.clone().unwrap_or_else(|| mq_shared::default_config_data(&old_engine)),
            }));
            let cfg = acct
                .configurations
                .get_mut(&id)
                .ok_or_else(|| format!("MQ configuration {id} not yet provisioned"))?;
            cfg["latestRevision"] =
                json!({ "revision": next, "created": created, "description": description });
            let arn = cfg
                .get("arn")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string();
            (arn, next)
        };
        let tags = mq_tags(props);
        if tags.is_empty() {
            acct.tags.remove(&arn.0);
        } else {
            acct.tags.insert(arn.0.clone(), tags);
        }
        Ok(ProvisionResult::new(id.clone())
            .with("Arn", arn.0)
            .with("Id", id)
            .with("Revision", arn.1.to_string()))
    }

    pub(super) fn get_att_mq_configuration(
        &self,
        physical_id: &str,
        attribute: &str,
    ) -> Option<String> {
        let guard = self.mq_state.read();
        let c = guard
            .get(&self.account_id)?
            .configurations
            .get(physical_id)?;
        match attribute {
            "Arn" => c.get("arn").and_then(Value::as_str).map(str::to_string),
            "Id" => Some(physical_id.to_string()),
            "Revision" => c
                .get("latestRevision")
                .and_then(|r| r.get("revision"))
                .and_then(Value::as_i64)
                .map(|n| n.to_string()),
            _ => None,
        }
    }

    pub(super) fn delete_mq_configuration(&self, physical_id: &str) {
        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        if let Some(c) = acct.configurations.remove(physical_id) {
            if let Some(arn) = c.get("arn").and_then(Value::as_str) {
                acct.tags.remove(arn);
            }
        }
        acct.configuration_revisions.remove(physical_id);
    }

    // --------------------------------------------- ConfigurationAssociation

    pub(super) fn create_mq_configuration_association(
        &self,
        resource: &ResourceDefinition,
    ) -> Result<ProvisionResult, String> {
        let props = &resource.properties;
        let broker_id = mq_str(props, "Broker")
            .ok_or_else(|| "AWS::AmazonMQ::ConfigurationAssociation requires Broker".to_string())?;
        let cfg = props.get("Configuration").ok_or_else(|| {
            "AWS::AmazonMQ::ConfigurationAssociation requires Configuration".to_string()
        })?;
        let cid = cfg
            .get("Id")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let rev = cfg.get("Revision").and_then(Value::as_i64).unwrap_or(1);

        let mut guard = self.mq_state.write();
        let acct = guard.get_or_create(&self.account_id);
        let broker = acct
            .brokers
            .get_mut(&broker_id)
            .ok_or_else(|| format!("MQ broker {broker_id} does not exist"))?;
        if let Some(obj) = broker.as_object_mut() {
            // Preserve the broker's configuration history: the prior current
            // configuration is pushed onto history, not discarded.
            mq_shared::set_broker_configuration(obj, &cid, rev);
        }
        // The association has no independent identity; Ref resolves to the broker.
        Ok(ProvisionResult::new(broker_id.clone()).with("Id", broker_id))
    }
}

/// Assemble a broker's `Fn::GetAtt` attribute set from its live wire endpoints
/// (projected from the single `mq_shared::broker_endpoints` source). The
/// list-valued attributes (`IpAddresses`, `*Endpoints`) are stored as JSON
/// arrays so `Fn::Select` / list-typed `Fn::GetAtt` resolve them as real lists
/// rather than collapsing to a scalar.
fn broker_attributes(
    id: String,
    arn: String,
    engine: &str,
    region: &str,
    deployment_mode: &str,
    config_id: &str,
    config_revision: i64,
) -> ProvisionResult {
    let e = mq_shared::broker_endpoints(&id, engine, region, deployment_mode, None);
    let mut res = ProvisionResult::new(id)
        .with("Arn", arn)
        .with("IpAddresses", json_list(&e.ips))
        .with("OpenWireEndpoints", json_list(&e.open_wire))
        .with("AmqpEndpoints", json_list(&e.amqp))
        .with("StompEndpoints", json_list(&e.stomp))
        .with("MqttEndpoints", json_list(&e.mqtt))
        .with("WssEndpoints", json_list(&e.wss));
    if !config_id.is_empty() {
        res = res
            .with("ConfigurationId", config_id.to_string())
            .with("ConfigurationRevision", config_revision.to_string());
    }
    res
}

/// A list-valued `Fn::GetAtt` attribute, encoded as a JSON array string so the
/// intrinsic-function resolver can hand it back as a real list.
fn json_list(items: &[String]) -> String {
    serde_json::to_string(items).unwrap_or_else(|_| "[]".to_string())
}

/// The `{id, revision}` of a broker's current configuration (empty id / 0 when
/// the broker has none, e.g. RabbitMQ).
fn broker_current_config(broker: Option<&Value>) -> (String, i64) {
    let cur = broker
        .and_then(|b| b.get("configurations"))
        .and_then(|c| c.get("current"));
    let id = cur
        .and_then(|c| c.get("id"))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let rev = cur
        .and_then(|c| c.get("revision"))
        .and_then(Value::as_i64)
        .unwrap_or(0);
    (id, rev)
}

/// Translate an `AWS::AmazonMQ::Broker` resource's PascalCase properties into a
/// restJson1 `CreateBroker` request body (camelCase members) so the CFN path
/// can reuse the exact shared service create logic.
fn cfn_broker_body(props: &Value, name: &str) -> Value {
    let mut b = serde_json::Map::new();
    b.insert("brokerName".into(), json!(name));
    b.insert(
        "engineType".into(),
        json!(mq_str(props, "EngineType")
            .unwrap_or_else(|| "ACTIVEMQ".to_string())
            .to_uppercase()),
    );
    if let Some(v) = mq_str(props, "EngineVersion") {
        b.insert("engineVersion".into(), json!(v));
    }
    b.insert(
        "deploymentMode".into(),
        json!(mq_str(props, "DeploymentMode").unwrap_or_else(|| "SINGLE_INSTANCE".to_string())),
    );
    if let Some(v) = mq_str(props, "HostInstanceType") {
        b.insert("hostInstanceType".into(), json!(v));
    }
    b.insert(
        "publiclyAccessible".into(),
        json!(mq_bool(props, "PubliclyAccessible")),
    );
    b.insert(
        "autoMinorVersionUpgrade".into(),
        json!(mq_bool(props, "AutoMinorVersionUpgrade")),
    );
    if let Some(v) = mq_str(props, "StorageType") {
        b.insert("storageType".into(), json!(v));
    }
    if let Some(v) = mq_str(props, "AuthenticationStrategy") {
        b.insert("authenticationStrategy".into(), json!(v));
    }
    if props.get("SecurityGroups").is_some() {
        b.insert(
            "securityGroups".into(),
            mq_string_list(props, "SecurityGroups"),
        );
    }
    // Only forward explicit subnets; when omitted, the shared path synthesizes
    // default-VPC subnet ids exactly as the direct API does.
    if props
        .get("SubnetIds")
        .and_then(Value::as_array)
        .is_some_and(|a| !a.is_empty())
    {
        b.insert("subnetIds".into(), mq_string_list(props, "SubnetIds"));
    }
    if let Some(logs) = props.get("Logs") {
        b.insert(
            "logs".into(),
            json!({
                "audit": logs.get("Audit").and_then(Value::as_bool).unwrap_or(false),
                "general": logs.get("General").and_then(Value::as_bool).unwrap_or(false),
            }),
        );
    }
    if let Some(cfg) = props.get("Configuration") {
        b.insert(
            "configuration".into(),
            json!({
                "id": cfg.get("Id").and_then(Value::as_str).unwrap_or_default(),
                "revision": cfg.get("Revision").and_then(Value::as_i64).unwrap_or(1),
            }),
        );
    }
    if let Some(arr) = props.get("Users").and_then(Value::as_array) {
        let users: Vec<Value> = arr
            .iter()
            .map(|u| {
                json!({
                    "username": u.get("Username").and_then(Value::as_str).unwrap_or_default(),
                    "password": u.get("Password").cloned().unwrap_or(json!("")),
                    "consoleAccess": u.get("ConsoleAccess").and_then(Value::as_bool).unwrap_or(false),
                    "groups": u.get("Groups").cloned().unwrap_or(json!([])),
                    "replicationUser": u.get("ReplicationUser").and_then(Value::as_bool).unwrap_or(false),
                })
            })
            .collect();
        b.insert("users".into(), Value::Array(users));
    }
    let tags = mq_tags(props);
    if !tags.is_empty() {
        b.insert("tags".into(), json!(tags));
    }
    Value::Object(b)
}

fn mq_str(props: &Value, key: &str) -> Option<String> {
    props
        .get(key)
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

fn mq_bool(props: &Value, key: &str) -> bool {
    match props.get(key) {
        Some(Value::Bool(b)) => *b,
        Some(Value::String(s)) => s.eq_ignore_ascii_case("true"),
        _ => false,
    }
}

fn mq_string_list(props: &Value, key: &str) -> Value {
    let mut out = Vec::new();
    if let Some(arr) = props.get(key).and_then(Value::as_array) {
        for v in arr {
            if let Some(s) = v.as_str() {
                out.push(json!(s));
            }
        }
    }
    Value::Array(out)
}

/// Convert CFN `Tags` (`[{Key,Value}]`) into the `mq` tag map.
fn mq_tags(props: &Value) -> std::collections::BTreeMap<String, String> {
    let mut out = std::collections::BTreeMap::new();
    if let Some(arr) = props.get("Tags").and_then(Value::as_array) {
        for t in arr {
            let key = t.get("Key").and_then(Value::as_str).unwrap_or("");
            let value = t.get("Value").and_then(Value::as_str).unwrap_or("");
            if !key.is_empty() {
                out.insert(key.to_string(), value.to_string());
            }
        }
    }
    out
}