cargo-lambda-metadata 1.9.1

Cargo subcommand to work with AWS Lambda
Documentation
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use cargo_lambda_remote::{
    RemoteConfig,
    aws_sdk_iam::types::Tag,
    aws_sdk_lambda::types::{Environment, TracingConfig},
};
use clap::{ArgAction, Args, ValueHint};
use serde::{Deserialize, Serialize, ser::SerializeStruct};
use std::{collections::HashMap, fmt::Debug, path::PathBuf};
use strum_macros::{Display, EnumString};

use crate::{
    env::EnvOptions,
    error::MetadataError,
    lambda::{Memory, MemoryValueParser, Timeout, Tracing},
};

use crate::cargo::deserialize_vec_or_map;

const DEFAULT_MANIFEST_PATH: &str = "Cargo.toml";
const DEFAULT_COMPATIBLE_RUNTIMES: &str = "provided.al2,provided.al2023";
const DEFAULT_RUNTIME: &str = "provided.al2023";

#[derive(Args, Clone, Debug, Default, Deserialize)]
#[command(
    name = "deploy",
    after_help = "Full command documentation: https://www.cargo-lambda.info/commands/deploy.html"
)]
pub struct Deploy {
    #[command(flatten)]
    #[serde(default, flatten, skip_serializing_if = "Option::is_none")]
    pub remote_config: Option<RemoteConfig>,

    #[command(flatten)]
    #[serde(
        default,
        flatten,
        skip_serializing_if = "FunctionDeployConfig::is_empty"
    )]
    pub function_config: FunctionDeployConfig,

    /// Directory where the lambda binaries are located
    #[arg(short, long, value_hint = ValueHint::DirPath)]
    #[serde(default)]
    pub lambda_dir: Option<PathBuf>,

    /// Path to Cargo.toml
    #[arg(long, value_name = "PATH", default_value = DEFAULT_MANIFEST_PATH)]
    #[serde(default)]
    pub manifest_path: Option<PathBuf>,

    /// Name of the binary to deploy if it doesn't match the name that you want to deploy it with
    #[arg(long, conflicts_with = "binary_path")]
    #[serde(default)]
    pub binary_name: Option<String>,

    /// Local path of the binary to deploy if it doesn't match the target path generated by cargo-lambda-build
    #[arg(long, conflicts_with = "binary_name")]
    #[serde(default)]
    pub binary_path: Option<PathBuf>,

    /// S3 bucket to upload the code to
    #[arg(long)]
    #[serde(default)]
    pub s3_bucket: Option<String>,

    /// Name with prefix where the code will be uploaded to in S3
    #[arg(long)]
    #[serde(default)]
    pub s3_key: Option<String>,

    /// Whether the code that you're deploying is a Lambda Extension
    #[arg(long)]
    #[serde(default)]
    pub extension: bool,

    /// Whether an extension is internal or external
    #[arg(long, requires = "extension")]
    #[serde(default)]
    pub internal: bool,

    /// Comma separated list with compatible runtimes for the Lambda Extension (--compatible_runtimes=provided.al2,nodejs16.x)
    /// List of allowed runtimes can be found in the AWS documentation: https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html#SSS-CreateFunction-request-Runtime
    #[arg(
        long,
        value_delimiter = ',',
        default_value = DEFAULT_COMPATIBLE_RUNTIMES,
        requires = "extension"
    )]
    #[serde(default)]
    compatible_runtimes: Option<Vec<String>>,

    /// Format to render the output (text, or json)
    #[arg(short, long)]
    #[serde(default)]
    output_format: Option<OutputFormat>,

    /// Comma separated list of tags to apply to the function or extension (--tag organization=aws,team=lambda).
    /// It can be used multiple times to add more tags. (--tag organization=aws --tag team=lambda)
    #[arg(long, value_delimiter = ',', action = ArgAction::Append, visible_alias = "tags")]
    #[serde(default, alias = "tags", deserialize_with = "deserialize_vec_or_map")]
    pub tag: Option<Vec<String>>,

    /// Option to add one or more files and directories to include in the zip file to upload.
    #[arg(short, long)]
    #[serde(default)]
    pub include: Option<Vec<String>>,

    /// Perform all the operations to locate and package the binary to deploy, but don't do the final deploy.
    #[arg(long, alias = "dry-run")]
    #[serde(default)]
    pub dry: bool,

    /// Merge environment variables with existing ones instead of overwriting them.
    /// When enabled, existing environment variables on AWS Lambda are preserved,
    /// and only new variables are added or updated from the configuration.
    #[arg(long)]
    #[serde(default)]
    pub merge_env: bool,

    /// Name of the function or extension to deploy
    #[arg(value_name = "NAME")]
    #[serde(default)]
    pub name: Option<String>,

    #[arg(skip)]
    #[serde(skip)]
    pub base_env: HashMap<String, String>,

    #[arg(skip)]
    #[serde(skip)]
    pub remote_env: HashMap<String, String>,
}

impl Deploy {
    pub fn manifest_path(&self) -> PathBuf {
        self.manifest_path
            .clone()
            .unwrap_or_else(default_manifest_path)
    }

    pub fn output_format(&self) -> OutputFormat {
        self.output_format.clone().unwrap_or_default()
    }

    pub fn compatible_runtimes(&self) -> Vec<String> {
        self.compatible_runtimes
            .clone()
            .unwrap_or_else(default_compatible_runtimes)
    }

    pub fn tracing_config(&self) -> Option<TracingConfig> {
        let tracing = self.function_config.tracing.clone()?;

        Some(
            TracingConfig::builder()
                .mode(tracing.as_str().into())
                .build(),
        )
    }

    pub fn lambda_tags(&self) -> Option<HashMap<String, String>> {
        match &self.tag {
            None => None,
            Some(tags) if tags.is_empty() => None,
            Some(tags) => Some(extract_tags(tags)),
        }
    }

    pub fn s3_tags(&self) -> Option<String> {
        match &self.tag {
            None => None,
            Some(tags) if tags.is_empty() => None,
            Some(tags) => Some(tags.join("&")),
        }
    }

    pub fn iam_tags(&self) -> Option<Vec<Tag>> {
        match &self.tag {
            None => None,
            Some(tags) if tags.is_empty() => None,
            Some(tags) => Some(
                extract_tags(tags)
                    .into_iter()
                    .map(|(k, v)| Tag::builder().key(k).value(v).build())
                    .collect::<Result<Vec<_>, _>>()
                    .expect("failed to build IAM tags"),
            ),
        }
    }

    pub fn lambda_environment(&self) -> Result<Option<Environment>, MetadataError> {
        let builder = Environment::builder();

        let mut env = if self.merge_env {
            // Start with remote environment variables when merging
            self.remote_env.clone()
        } else {
            HashMap::new()
        };

        // Add base environment variables
        env.extend(self.base_env.clone());

        // Add or override with environment variables from configuration
        match &self.function_config.env_options {
            None => {}
            Some(env_options) => {
                let local_env = env_options.lambda_environment(&HashMap::new())?;
                env.extend(local_env);
            }
        };

        if env.is_empty() {
            return Ok(None);
        }

        Ok(Some(builder.set_variables(Some(env)).build()))
    }

    pub fn publish_code_without_description(&self) -> bool {
        self.function_config.description.is_none()
    }

    pub fn deploy_alias(&self) -> Option<String> {
        self.remote_config.as_ref().and_then(|r| r.alias.clone())
    }
}

impl Serialize for Deploy {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        let len = self.manifest_path.is_some() as usize
            + self.lambda_dir.is_some() as usize
            + self.binary_path.is_some() as usize
            + self.binary_name.is_some() as usize
            + self.s3_bucket.is_some() as usize
            + self.s3_key.is_some() as usize
            + self.extension as usize
            + self.internal as usize
            + self.compatible_runtimes.is_some() as usize
            + self.output_format.is_some() as usize
            + self.tag.is_some() as usize
            + self.include.is_some() as usize
            + self.dry as usize
            + self.merge_env as usize
            + self.name.is_some() as usize
            + self.remote_config.as_ref().map_or(0, |r| r.count_fields())
            + self.function_config.count_fields();

        let mut state = serializer.serialize_struct("Deploy", len)?;

        if let Some(ref path) = self.manifest_path {
            state.serialize_field("manifest_path", path)?;
        }
        if let Some(ref dir) = self.lambda_dir {
            state.serialize_field("lambda_dir", dir)?;
        }
        if let Some(ref path) = self.binary_path {
            state.serialize_field("binary_path", path)?;
        }
        if let Some(ref name) = self.binary_name {
            state.serialize_field("binary_name", name)?;
        }
        if let Some(ref bucket) = self.s3_bucket {
            state.serialize_field("s3_bucket", bucket)?;
        }
        if let Some(ref key) = self.s3_key {
            state.serialize_field("s3_key", key)?;
        }
        if self.extension {
            state.serialize_field("extension", &self.extension)?;
        }
        if self.internal {
            state.serialize_field("internal", &self.internal)?;
        }
        if let Some(ref runtimes) = self.compatible_runtimes {
            state.serialize_field("compatible_runtimes", runtimes)?;
        }
        if let Some(ref format) = self.output_format {
            state.serialize_field("output_format", format)?;
        }
        if let Some(ref tag) = self.tag {
            state.serialize_field("tag", tag)?;
        }
        if let Some(ref include) = self.include {
            state.serialize_field("include", include)?;
        }
        if self.dry {
            state.serialize_field("dry", &self.dry)?;
        }
        if self.merge_env {
            state.serialize_field("merge_env", &self.merge_env)?;
        }
        if let Some(ref name) = self.name {
            state.serialize_field("name", name)?;
        }
        if let Some(ref remote_config) = self.remote_config {
            remote_config.serialize_fields::<S>(&mut state)?;
        }
        self.function_config.serialize_fields::<S>(&mut state)?;

        state.end()
    }
}

fn default_manifest_path() -> PathBuf {
    PathBuf::from(DEFAULT_MANIFEST_PATH)
}

fn default_compatible_runtimes() -> Vec<String> {
    DEFAULT_COMPATIBLE_RUNTIMES
        .split(',')
        .map(String::from)
        .collect()
}

#[derive(Clone, Debug, Default, Deserialize, Display, EnumString, Serialize)]
#[strum(ascii_case_insensitive)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    #[default]
    Text,
    Json,
}

#[derive(Args, Clone, Debug, Default, Deserialize, Serialize)]
pub struct FunctionDeployConfig {
    /// Enable function URL for this function
    #[arg(long)]
    #[serde(default)]
    pub enable_function_url: bool,

    /// Disable function URL for this function
    #[arg(long)]
    #[serde(default)]
    pub disable_function_url: bool,

    /// Memory allocated for the function. Value must be between 128 and 10240.
    #[arg(long, alias = "memory-size", value_parser = MemoryValueParser)]
    #[serde(default)]
    pub memory: Option<Memory>,

    /// How long the function can be running for, in seconds
    #[arg(long)]
    #[serde(default)]
    pub timeout: Option<Timeout>,

    #[command(flatten)]
    #[serde(default, flatten, skip_serializing_if = "Option::is_none")]
    pub env_options: Option<EnvOptions>,

    /// Tracing mode with X-Ray
    #[arg(long)]
    #[serde(default)]
    pub tracing: Option<Tracing>,

    /// IAM Role associated with the function
    #[arg(long, visible_alias = "iam-role")]
    #[serde(default, alias = "iam_role")]
    pub role: Option<String>,

    /// Lambda Layer ARN to associate the deployed function with.
    /// Can be used multiple times to add more layers.
    /// `--layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer1 --layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer2`.
    /// It can also be used with comma separated list of layer ARNs.
    /// `--layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer1,arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer2`.
    #[arg(long, value_delimiter = ',', action = ArgAction::Append, visible_alias = "layer-arn")]
    #[serde(default, alias = "layers")]
    pub layer: Option<Vec<String>>,

    #[command(flatten)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vpc: Option<VpcConfig>,

    /// Choose a different Lambda runtime to deploy with.
    /// The only other option that might work is `provided.al2`.
    #[arg(long, default_value = DEFAULT_RUNTIME)]
    #[serde(default)]
    pub runtime: Option<String>,

    /// A description for the new function version.
    #[arg(long)]
    #[serde(default)]
    pub description: Option<String>,

    /// Retention policy for the function's log group.
    /// The value is the number of days to keep the logs.
    #[arg(long)]
    #[serde(default)]
    pub log_retention: Option<i32>,
}

fn default_runtime() -> String {
    DEFAULT_RUNTIME.to_string()
}

impl FunctionDeployConfig {
    #[allow(dead_code)]
    fn is_empty(&self) -> bool {
        self.runtime.is_none()
            && self.memory.is_none()
            && self.timeout.is_none()
            && self.env_options.is_none()
            && self.tracing.is_none()
            && self.role.is_none()
            && self.vpc.is_none()
            && self.description.is_none()
            && self.log_retention.is_none()
            && self.layer.is_none()
            && !self.disable_function_url
            && !self.enable_function_url
    }

    pub fn runtime(&self) -> String {
        self.runtime.clone().unwrap_or_else(default_runtime)
    }

    pub fn should_update(&self) -> bool {
        let Ok(val) = serde_json::to_value(self) else {
            return false;
        };
        let Ok(default) = serde_json::to_value(FunctionDeployConfig::default()) else {
            return false;
        };
        val != default
    }

    fn count_fields(&self) -> usize {
        self.disable_function_url as usize
            + self.enable_function_url as usize
            + self.layer.as_ref().is_some_and(|l| !l.is_empty()) as usize
            + self.tracing.is_some() as usize
            + self.role.is_some() as usize
            + self.memory.is_some() as usize
            + self.timeout.is_some() as usize
            + self.runtime.is_some() as usize
            + self.description.is_some() as usize
            + self.log_retention.is_some() as usize
            + self.vpc.is_some() as usize
            + self
                .env_options
                .as_ref()
                .map_or(0, |env| env.count_fields())
    }

    fn serialize_fields<S>(
        &self,
        state: &mut <S as serde::Serializer>::SerializeStruct,
    ) -> Result<(), S::Error>
    where
        S: serde::Serializer,
    {
        if self.disable_function_url {
            state.serialize_field("disable_function_url", &true)?;
        }

        if self.enable_function_url {
            state.serialize_field("enable_function_url", &true)?;
        }

        if let Some(memory) = &self.memory {
            state.serialize_field("memory", &memory)?;
        }

        if let Some(timeout) = &self.timeout {
            state.serialize_field("timeout", &timeout)?;
        }

        if let Some(runtime) = &self.runtime {
            state.serialize_field("runtime", &runtime)?;
        }

        if let Some(tracing) = &self.tracing {
            state.serialize_field("tracing", &tracing)?;
        }

        if let Some(role) = &self.role {
            state.serialize_field("role", &role)?;
        }

        if let Some(layer) = &self.layer {
            if !layer.is_empty() {
                state.serialize_field("layer", &layer)?;
            }
        }

        if let Some(description) = &self.description {
            state.serialize_field("description", &description)?;
        }

        if let Some(log_retention) = &self.log_retention {
            state.serialize_field("log_retention", &log_retention)?;
        }

        if let Some(vpc) = &self.vpc {
            state.serialize_field("vpc", vpc)?;
        }

        if let Some(env_options) = &self.env_options {
            env_options.serialize_fields::<S>(state)?;
        }

        Ok(())
    }
}

#[derive(Args, Clone, Debug, Default, Deserialize, Serialize)]
pub struct VpcConfig {
    /// Subnet IDs to associate the deployed function with a VPC
    #[arg(long, value_delimiter = ',')]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subnet_ids: Option<Vec<String>>,

    /// Security Group IDs to associate the deployed function
    #[arg(long, value_delimiter = ',')]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub security_group_ids: Option<Vec<String>>,

    /// Allow outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets
    #[arg(long)]
    #[serde(default, skip_serializing_if = "is_false")]
    pub ipv6_allowed_for_dual_stack: bool,
}

fn is_false(b: &bool) -> bool {
    !b
}

impl VpcConfig {
    pub fn should_update(&self) -> bool {
        let Ok(val) = serde_json::to_value(self) else {
            return false;
        };
        let Ok(default) = serde_json::to_value(VpcConfig::default()) else {
            return false;
        };
        val != default
    }
}

fn extract_tags(tags: &Vec<String>) -> HashMap<String, String> {
    let mut map = HashMap::new();

    for var in tags {
        let mut split = var.splitn(2, '=');
        if let (Some(k), Some(v)) = (split.next(), split.next()) {
            map.insert(k.to_string(), v.to_string());
        }
    }

    map
}

#[cfg(test)]
mod tests {
    use crate::{
        cargo::load_metadata,
        config::{ConfigOptions, FunctionNames, load_config_without_cli_flags},
        lambda::Timeout,
        tests::fixture_metadata,
    };

    use super::*;

    #[test]
    fn test_extract_tags() {
        let tags = vec!["organization=aws".to_string(), "team=lambda".to_string()];
        let map = extract_tags(&tags);
        assert_eq!(map.get("organization"), Some(&"aws".to_string()));
        assert_eq!(map.get("team"), Some(&"lambda".to_string()));
    }

    #[test]
    fn test_lambda_environment() {
        let deploy = Deploy::default();
        let env = deploy.lambda_environment().unwrap();
        assert_eq!(env, None);

        let deploy = Deploy {
            base_env: HashMap::from([("FOO".to_string(), "BAR".to_string())]),
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        assert_eq!(env.variables().unwrap().len(), 1);
        assert_eq!(
            env.variables().unwrap().get("FOO"),
            Some(&"BAR".to_string())
        );

        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_var: Some(vec!["FOO=BAR".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        assert_eq!(env.variables().unwrap().len(), 1);
        assert_eq!(
            env.variables().unwrap().get("FOO"),
            Some(&"BAR".to_string())
        );

        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_var: Some(vec!["FOO=BAR".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            base_env: HashMap::from([("BAZ".to_string(), "QUX".to_string())]),
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        assert_eq!(env.variables().unwrap().len(), 2);
        assert_eq!(
            env.variables().unwrap().get("BAZ"),
            Some(&"QUX".to_string())
        );
        assert_eq!(
            env.variables().unwrap().get("FOO"),
            Some(&"BAR".to_string())
        );

        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path();
        std::fs::write(path, "FOO=BAR\nBAZ=QUX").unwrap();

        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_file: Some(path.to_path_buf()),
                    ..Default::default()
                }),
                ..Default::default()
            },
            base_env: HashMap::from([("QUUX".to_string(), "QUUX".to_string())]),
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        assert_eq!(env.variables().unwrap().len(), 3);
        assert_eq!(
            env.variables().unwrap().get("BAZ"),
            Some(&"QUX".to_string())
        );
        assert_eq!(
            env.variables().unwrap().get("FOO"),
            Some(&"BAR".to_string())
        );
        assert_eq!(
            env.variables().unwrap().get("QUUX"),
            Some(&"QUUX".to_string())
        );
    }

    #[test]
    fn test_lambda_environment_merge_mode() {
        // Test merge_env=false (default behavior - overwrites)
        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_var: Some(vec!["LOCAL=VALUE".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            remote_env: HashMap::from([
                ("REMOTE1".to_string(), "REMOTE_VALUE1".to_string()),
                ("REMOTE2".to_string(), "REMOTE_VALUE2".to_string()),
            ]),
            merge_env: false,
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        let vars = env.variables().unwrap();
        // When merge_env is false, only local env vars should be present
        assert_eq!(vars.len(), 1);
        assert_eq!(vars.get("LOCAL"), Some(&"VALUE".to_string()));
        assert_eq!(vars.get("REMOTE1"), None);
        assert_eq!(vars.get("REMOTE2"), None);

        // Test merge_env=true (merge behavior - preserves remote vars)
        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_var: Some(vec!["LOCAL=VALUE".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            remote_env: HashMap::from([
                ("REMOTE1".to_string(), "REMOTE_VALUE1".to_string()),
                ("REMOTE2".to_string(), "REMOTE_VALUE2".to_string()),
            ]),
            merge_env: true,
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        let vars = env.variables().unwrap();
        // When merge_env is true, both remote and local vars should be present
        assert_eq!(vars.len(), 3);
        assert_eq!(vars.get("LOCAL"), Some(&"VALUE".to_string()));
        assert_eq!(vars.get("REMOTE1"), Some(&"REMOTE_VALUE1".to_string()));
        assert_eq!(vars.get("REMOTE2"), Some(&"REMOTE_VALUE2".to_string()));

        // Test merge_env=true with overlapping keys (local should win)
        let deploy = Deploy {
            function_config: FunctionDeployConfig {
                env_options: Some(EnvOptions {
                    env_var: Some(vec!["REMOTE1=LOCAL_OVERRIDE".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            remote_env: HashMap::from([
                ("REMOTE1".to_string(), "REMOTE_VALUE1".to_string()),
                ("REMOTE2".to_string(), "REMOTE_VALUE2".to_string()),
            ]),
            merge_env: true,
            ..Default::default()
        };
        let env = deploy.lambda_environment().unwrap().unwrap();
        let vars = env.variables().unwrap();
        // Local value should override remote value
        assert_eq!(vars.len(), 2);
        assert_eq!(vars.get("REMOTE1"), Some(&"LOCAL_OVERRIDE".to_string()));
        assert_eq!(vars.get("REMOTE2"), Some(&"REMOTE_VALUE2".to_string()));
    }

    #[test]
    fn test_load_config_from_workspace() {
        let options = ConfigOptions {
            names: FunctionNames::from_package("crate-3"),
            admerge: true,
            ..Default::default()
        };

        let metadata = load_metadata(fixture_metadata("workspace-package"), None).unwrap();
        let config = load_config_without_cli_flags(&metadata, &options).unwrap();
        assert_eq!(
            config.deploy.function_config.timeout,
            Some(Timeout::new(120))
        );
        assert_eq!(config.deploy.function_config.memory, Some(10240.into()));

        let tags = config.deploy.lambda_tags().unwrap();
        assert_eq!(tags.len(), 2);
        assert_eq!(tags.get("organization"), Some(&"aws".to_string()));
        assert_eq!(tags.get("team"), Some(&"lambda".to_string()));

        assert_eq!(
            config.deploy.include,
            Some(vec!["src/bin/main.rs".to_string()])
        );

        assert_eq!(
            config.deploy.function_config.env_options.unwrap().env_var,
            Some(vec!["APP_ENV=production".to_string()])
        );

        assert_eq!(config.deploy.function_config.log_retention, Some(14));
    }

    #[test]
    fn test_load_region_from_package_metadata() {
        let metadata = load_metadata(fixture_metadata("single-binary-package"), None).unwrap();

        let options = ConfigOptions {
            names: FunctionNames::from_package("basic-lambda"),
            ..Default::default()
        };

        let config = load_config_without_cli_flags(&metadata, &options).unwrap();

        // Region and profile should be loaded from package.metadata.lambda.deploy
        let remote_config = config
            .deploy
            .remote_config
            .expect("remote_config should be Some");
        assert_eq!(
            remote_config.region,
            Some("eu-central-1".to_string()),
            "region should be loaded from Cargo.toml"
        );
        assert_eq!(
            remote_config.profile,
            Some("test-profile".to_string()),
            "profile should be loaded from Cargo.toml"
        );
    }

    #[test]
    fn test_deploy_serialization_with_remote_config() {
        use cargo_lambda_remote::RemoteConfig;

        let deploy = Deploy {
            remote_config: Some(RemoteConfig {
                region: Some("us-west-2".to_string()),
                profile: Some("production".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };

        // Serialize to JSON
        let serialized = serde_json::to_value(&deploy).unwrap();

        // Should serialize as flat fields at top level
        assert_eq!(serialized["region"], "us-west-2");
        assert_eq!(serialized["profile"], "production");
        assert!(
            !serialized
                .as_object()
                .unwrap()
                .contains_key("remote_config"),
            "remote_config should be flattened, not nested"
        );

        // Deserialize back
        let deserialized: Deploy = serde_json::from_value(serialized).unwrap();
        let rc = deserialized.remote_config.unwrap();
        assert_eq!(rc.region, Some("us-west-2".to_string()));
        assert_eq!(rc.profile, Some("production".to_string()));
    }
}