cargo_lambda_metadata/cargo/
deploy.rs

1use cargo_lambda_remote::{
2    RemoteConfig,
3    aws_sdk_lambda::types::{Environment, TracingConfig},
4};
5use clap::{ArgAction, Args, ValueHint};
6use serde::{Deserialize, Serialize, ser::SerializeStruct};
7use std::{collections::HashMap, fmt::Debug, path::PathBuf};
8use strum_macros::{Display, EnumString};
9
10use crate::{
11    env::EnvOptions,
12    error::MetadataError,
13    lambda::{Memory, MemoryValueParser, Timeout, Tracing},
14};
15
16use crate::cargo::deserialize_vec_or_map;
17
18const DEFAULT_MANIFEST_PATH: &str = "Cargo.toml";
19const DEFAULT_COMPATIBLE_RUNTIMES: &str = "provided.al2,provided.al2023";
20const DEFAULT_RUNTIME: &str = "provided.al2023";
21
22#[derive(Args, Clone, Debug, Default, Deserialize)]
23#[command(
24    name = "deploy",
25    after_help = "Full command documentation: https://www.cargo-lambda.info/commands/deploy.html"
26)]
27pub struct Deploy {
28    #[command(flatten)]
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub remote_config: Option<RemoteConfig>,
31
32    #[command(flatten)]
33    #[serde(
34        default,
35        flatten,
36        skip_serializing_if = "FunctionDeployConfig::is_empty"
37    )]
38    pub function_config: FunctionDeployConfig,
39
40    /// Directory where the lambda binaries are located
41    #[arg(short, long, value_hint = ValueHint::DirPath)]
42    #[serde(default)]
43    pub lambda_dir: Option<PathBuf>,
44
45    /// Path to Cargo.toml
46    #[arg(long, value_name = "PATH", default_value = DEFAULT_MANIFEST_PATH)]
47    #[serde(default)]
48    pub manifest_path: Option<PathBuf>,
49
50    /// Name of the binary to deploy if it doesn't match the name that you want to deploy it with
51    #[arg(long, conflicts_with = "binary_path")]
52    #[serde(default)]
53    pub binary_name: Option<String>,
54
55    /// Local path of the binary to deploy if it doesn't match the target path generated by cargo-lambda-build
56    #[arg(long, conflicts_with = "binary_name")]
57    #[serde(default)]
58    pub binary_path: Option<PathBuf>,
59
60    /// S3 bucket to upload the code to
61    #[arg(long)]
62    #[serde(default)]
63    pub s3_bucket: Option<String>,
64
65    /// Name with prefix where the code will be uploaded to in S3
66    #[arg(long)]
67    #[serde(default)]
68    pub s3_key: Option<String>,
69
70    /// Whether the code that you're deploying is a Lambda Extension
71    #[arg(long)]
72    #[serde(default)]
73    pub extension: bool,
74
75    /// Whether an extension is internal or external
76    #[arg(long, requires = "extension")]
77    #[serde(default)]
78    pub internal: bool,
79
80    /// Comma separated list with compatible runtimes for the Lambda Extension (--compatible_runtimes=provided.al2,nodejs16.x)
81    /// 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
82    #[arg(
83        long,
84        value_delimiter = ',',
85        default_value = DEFAULT_COMPATIBLE_RUNTIMES,
86        requires = "extension"
87    )]
88    #[serde(default)]
89    compatible_runtimes: Option<Vec<String>>,
90
91    /// Format to render the output (text, or json)
92    #[arg(short, long)]
93    #[serde(default)]
94    output_format: Option<OutputFormat>,
95
96    /// Comma separated list of tags to apply to the function or extension (--tag organization=aws,team=lambda).
97    /// It can be used multiple times to add more tags. (--tag organization=aws --tag team=lambda)
98    #[arg(long, value_delimiter = ',', action = ArgAction::Append, visible_alias = "tags")]
99    #[serde(default, alias = "tags", deserialize_with = "deserialize_vec_or_map")]
100    pub tag: Option<Vec<String>>,
101
102    /// Option to add one or more files and directories to include in the zip file to upload.
103    #[arg(short, long)]
104    #[serde(default)]
105    pub include: Option<Vec<String>>,
106
107    /// Perform all the operations to locate and package the binary to deploy, but don't do the final deploy.
108    #[arg(long, alias = "dry-run")]
109    #[serde(default)]
110    pub dry: bool,
111
112    /// Name of the function or extension to deploy
113    #[arg(value_name = "NAME")]
114    #[serde(default)]
115    pub name: Option<String>,
116
117    #[arg(skip)]
118    #[serde(skip)]
119    pub base_env: HashMap<String, String>,
120}
121
122impl Deploy {
123    pub fn manifest_path(&self) -> PathBuf {
124        self.manifest_path
125            .clone()
126            .unwrap_or_else(default_manifest_path)
127    }
128
129    pub fn output_format(&self) -> OutputFormat {
130        self.output_format.clone().unwrap_or_default()
131    }
132
133    pub fn compatible_runtimes(&self) -> Vec<String> {
134        self.compatible_runtimes
135            .clone()
136            .unwrap_or_else(default_compatible_runtimes)
137    }
138
139    pub fn tracing_config(&self) -> Option<TracingConfig> {
140        let tracing = self.function_config.tracing.clone()?;
141
142        Some(
143            TracingConfig::builder()
144                .mode(tracing.as_str().into())
145                .build(),
146        )
147    }
148
149    pub fn lambda_tags(&self) -> Option<HashMap<String, String>> {
150        match &self.tag {
151            None => None,
152            Some(tags) if tags.is_empty() => None,
153            Some(tags) => Some(extract_tags(tags)),
154        }
155    }
156
157    pub fn s3_tags(&self) -> Option<String> {
158        match &self.tag {
159            None => None,
160            Some(tags) if tags.is_empty() => None,
161            Some(tags) => Some(tags.join("&")),
162        }
163    }
164
165    pub fn lambda_environment(&self) -> Result<Option<Environment>, MetadataError> {
166        let builder = Environment::builder();
167
168        let env = match &self.function_config.env_options {
169            None => self.base_env.clone(),
170            Some(env_options) => env_options.lambda_environment(&self.base_env)?,
171        };
172
173        if env.is_empty() {
174            return Ok(None);
175        }
176
177        Ok(Some(builder.set_variables(Some(env)).build()))
178    }
179
180    pub fn publish_code_without_description(&self) -> bool {
181        self.function_config.description.is_none()
182    }
183
184    pub fn deploy_alias(&self) -> Option<String> {
185        self.remote_config.as_ref().and_then(|r| r.alias.clone())
186    }
187}
188
189impl Serialize for Deploy {
190    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
191    where
192        S: serde::Serializer,
193    {
194        use serde::ser::SerializeStruct;
195
196        let len = self.manifest_path.is_some() as usize
197            + self.lambda_dir.is_some() as usize
198            + self.binary_path.is_some() as usize
199            + self.binary_name.is_some() as usize
200            + self.s3_bucket.is_some() as usize
201            + self.s3_key.is_some() as usize
202            + self.extension as usize
203            + self.internal as usize
204            + self.compatible_runtimes.is_some() as usize
205            + self.output_format.is_some() as usize
206            + self.tag.is_some() as usize
207            + self.include.is_some() as usize
208            + self.dry as usize
209            + self.name.is_some() as usize
210            + self.remote_config.is_some() as usize
211            + self.function_config.count_fields();
212
213        let mut state = serializer.serialize_struct("Deploy", len)?;
214
215        if let Some(ref path) = self.manifest_path {
216            state.serialize_field("manifest_path", path)?;
217        }
218        if let Some(ref dir) = self.lambda_dir {
219            state.serialize_field("lambda_dir", dir)?;
220        }
221        if let Some(ref path) = self.binary_path {
222            state.serialize_field("binary_path", path)?;
223        }
224        if let Some(ref name) = self.binary_name {
225            state.serialize_field("binary_name", name)?;
226        }
227        if let Some(ref bucket) = self.s3_bucket {
228            state.serialize_field("s3_bucket", bucket)?;
229        }
230        if let Some(ref key) = self.s3_key {
231            state.serialize_field("s3_key", key)?;
232        }
233        if self.extension {
234            state.serialize_field("extension", &self.extension)?;
235        }
236        if self.internal {
237            state.serialize_field("internal", &self.internal)?;
238        }
239        if let Some(ref runtimes) = self.compatible_runtimes {
240            state.serialize_field("compatible_runtimes", runtimes)?;
241        }
242        if let Some(ref format) = self.output_format {
243            state.serialize_field("output_format", format)?;
244        }
245        if let Some(ref tag) = self.tag {
246            state.serialize_field("tag", tag)?;
247        }
248        if let Some(ref include) = self.include {
249            state.serialize_field("include", include)?;
250        }
251        if self.dry {
252            state.serialize_field("dry", &self.dry)?;
253        }
254        if let Some(ref name) = self.name {
255            state.serialize_field("name", name)?;
256        }
257        if let Some(ref remote_config) = self.remote_config {
258            state.serialize_field("remote_config", remote_config)?;
259        }
260        self.function_config.serialize_fields::<S>(&mut state)?;
261
262        state.end()
263    }
264}
265
266fn default_manifest_path() -> PathBuf {
267    PathBuf::from(DEFAULT_MANIFEST_PATH)
268}
269
270fn default_compatible_runtimes() -> Vec<String> {
271    DEFAULT_COMPATIBLE_RUNTIMES
272        .split(',')
273        .map(String::from)
274        .collect()
275}
276
277#[derive(Clone, Debug, Default, Deserialize, Display, EnumString, Serialize)]
278#[strum(ascii_case_insensitive)]
279#[serde(rename_all = "lowercase")]
280pub enum OutputFormat {
281    #[default]
282    Text,
283    Json,
284}
285
286#[derive(Args, Clone, Debug, Default, Deserialize, Serialize)]
287pub struct FunctionDeployConfig {
288    /// Enable function URL for this function
289    #[arg(long)]
290    #[serde(default)]
291    pub enable_function_url: bool,
292
293    /// Disable function URL for this function
294    #[arg(long)]
295    #[serde(default)]
296    pub disable_function_url: bool,
297
298    /// Memory allocated for the function. Value must be between 128 and 10240.
299    #[arg(long, alias = "memory-size", value_parser = MemoryValueParser)]
300    #[serde(default)]
301    pub memory: Option<Memory>,
302
303    /// How long the function can be running for, in seconds
304    #[arg(long)]
305    #[serde(default)]
306    pub timeout: Option<Timeout>,
307
308    #[command(flatten)]
309    #[serde(default, flatten, skip_serializing_if = "Option::is_none")]
310    pub env_options: Option<EnvOptions>,
311
312    /// Tracing mode with X-Ray
313    #[arg(long)]
314    #[serde(default)]
315    pub tracing: Option<Tracing>,
316
317    /// IAM Role associated with the function
318    #[arg(long, visible_alias = "iam-role")]
319    #[serde(default, alias = "iam_role")]
320    pub role: Option<String>,
321
322    /// Lambda Layer ARN to associate the deployed function with.
323    /// Can be used multiple times to add more layers.
324    /// `--layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer1 --layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer2`.
325    /// It can also be used with comma separated list of layer ARNs.
326    /// `--layer arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer1,arn:aws:lambda:us-east-1:xxxxxxxx:layers:layer2`.
327    #[arg(long, value_delimiter = ',', action = ArgAction::Append, visible_alias = "layer-arn")]
328    #[serde(default, alias = "layers")]
329    pub layer: Option<Vec<String>>,
330
331    #[command(flatten)]
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub vpc: Option<VpcConfig>,
334
335    /// Choose a different Lambda runtime to deploy with.
336    /// The only other option that might work is `provided.al2`.
337    #[arg(long, default_value = DEFAULT_RUNTIME)]
338    #[serde(default)]
339    pub runtime: Option<String>,
340
341    /// A description for the new function version.
342    #[arg(long)]
343    #[serde(default)]
344    pub description: Option<String>,
345
346    /// Retention policy for the function's log group.
347    /// The value is the number of days to keep the logs.
348    #[arg(long)]
349    #[serde(default)]
350    pub log_retention: Option<i32>,
351}
352
353fn default_runtime() -> String {
354    DEFAULT_RUNTIME.to_string()
355}
356
357impl FunctionDeployConfig {
358    #[allow(dead_code)]
359    fn is_empty(&self) -> bool {
360        self.runtime.is_none()
361            && self.memory.is_none()
362            && self.timeout.is_none()
363            && self.env_options.is_none()
364            && self.tracing.is_none()
365            && self.role.is_none()
366            && self.vpc.is_none()
367            && self.description.is_none()
368            && self.log_retention.is_none()
369            && self.layer.is_none()
370            && !self.disable_function_url
371            && !self.enable_function_url
372    }
373
374    pub fn runtime(&self) -> String {
375        self.runtime.clone().unwrap_or_else(default_runtime)
376    }
377
378    pub fn should_update(&self) -> bool {
379        let Ok(val) = serde_json::to_value(self) else {
380            return false;
381        };
382        let Ok(default) = serde_json::to_value(FunctionDeployConfig::default()) else {
383            return false;
384        };
385        val != default
386    }
387
388    fn count_fields(&self) -> usize {
389        self.disable_function_url as usize
390            + self.enable_function_url as usize
391            + self.layer.as_ref().is_some_and(|l| !l.is_empty()) as usize
392            + self.tracing.is_some() as usize
393            + self.role.is_some() as usize
394            + self.memory.is_some() as usize
395            + self.timeout.is_some() as usize
396            + self.runtime.is_some() as usize
397            + self.description.is_some() as usize
398            + self.log_retention.is_some() as usize
399            + self.vpc.is_some() as usize
400            + self
401                .env_options
402                .as_ref()
403                .map_or(0, |env| env.count_fields())
404    }
405
406    fn serialize_fields<S>(
407        &self,
408        state: &mut <S as serde::Serializer>::SerializeStruct,
409    ) -> Result<(), S::Error>
410    where
411        S: serde::Serializer,
412    {
413        if self.disable_function_url {
414            state.serialize_field("disable_function_url", &true)?;
415        }
416
417        if self.enable_function_url {
418            state.serialize_field("enable_function_url", &true)?;
419        }
420
421        if let Some(memory) = &self.memory {
422            state.serialize_field("memory", &memory)?;
423        }
424
425        if let Some(timeout) = &self.timeout {
426            state.serialize_field("timeout", &timeout)?;
427        }
428
429        if let Some(runtime) = &self.runtime {
430            state.serialize_field("runtime", &runtime)?;
431        }
432
433        if let Some(tracing) = &self.tracing {
434            state.serialize_field("tracing", &tracing)?;
435        }
436
437        if let Some(role) = &self.role {
438            state.serialize_field("role", &role)?;
439        }
440
441        if let Some(layer) = &self.layer {
442            if !layer.is_empty() {
443                state.serialize_field("layer", &layer)?;
444            }
445        }
446
447        if let Some(description) = &self.description {
448            state.serialize_field("description", &description)?;
449        }
450
451        if let Some(log_retention) = &self.log_retention {
452            state.serialize_field("log_retention", &log_retention)?;
453        }
454
455        if let Some(vpc) = &self.vpc {
456            state.serialize_field("vpc", vpc)?;
457        }
458
459        if let Some(env_options) = &self.env_options {
460            env_options.serialize_fields::<S>(state)?;
461        }
462
463        Ok(())
464    }
465}
466
467#[derive(Args, Clone, Debug, Default, Deserialize, Serialize)]
468pub struct VpcConfig {
469    /// Subnet IDs to associate the deployed function with a VPC
470    #[arg(long, value_delimiter = ',')]
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub subnet_ids: Option<Vec<String>>,
473
474    /// Security Group IDs to associate the deployed function
475    #[arg(long, value_delimiter = ',')]
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub security_group_ids: Option<Vec<String>>,
478
479    /// Allow outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets
480    #[arg(long)]
481    #[serde(default, skip_serializing_if = "is_false")]
482    pub ipv6_allowed_for_dual_stack: bool,
483}
484
485fn is_false(b: &bool) -> bool {
486    !b
487}
488
489impl VpcConfig {
490    pub fn should_update(&self) -> bool {
491        let Ok(val) = serde_json::to_value(self) else {
492            return false;
493        };
494        let Ok(default) = serde_json::to_value(VpcConfig::default()) else {
495            return false;
496        };
497        val != default
498    }
499}
500
501fn extract_tags(tags: &Vec<String>) -> HashMap<String, String> {
502    let mut map = HashMap::new();
503
504    for var in tags {
505        let mut split = var.splitn(2, '=');
506        if let (Some(k), Some(v)) = (split.next(), split.next()) {
507            map.insert(k.to_string(), v.to_string());
508        }
509    }
510
511    map
512}
513
514#[cfg(test)]
515mod tests {
516    use crate::{
517        cargo::load_metadata,
518        config::{ConfigOptions, load_config_without_cli_flags},
519        lambda::Timeout,
520        tests::fixture_metadata,
521    };
522
523    use super::*;
524
525    #[test]
526    fn test_extract_tags() {
527        let tags = vec!["organization=aws".to_string(), "team=lambda".to_string()];
528        let map = extract_tags(&tags);
529        assert_eq!(map.get("organization"), Some(&"aws".to_string()));
530        assert_eq!(map.get("team"), Some(&"lambda".to_string()));
531    }
532
533    #[test]
534    fn test_lambda_environment() {
535        let deploy = Deploy::default();
536        let env = deploy.lambda_environment().unwrap();
537        assert_eq!(env, None);
538
539        let deploy = Deploy {
540            base_env: HashMap::from([("FOO".to_string(), "BAR".to_string())]),
541            ..Default::default()
542        };
543        let env = deploy.lambda_environment().unwrap().unwrap();
544        assert_eq!(env.variables().unwrap().len(), 1);
545        assert_eq!(
546            env.variables().unwrap().get("FOO"),
547            Some(&"BAR".to_string())
548        );
549
550        let deploy = Deploy {
551            function_config: FunctionDeployConfig {
552                env_options: Some(EnvOptions {
553                    env_var: Some(vec!["FOO=BAR".to_string()]),
554                    ..Default::default()
555                }),
556                ..Default::default()
557            },
558            ..Default::default()
559        };
560        let env = deploy.lambda_environment().unwrap().unwrap();
561        assert_eq!(env.variables().unwrap().len(), 1);
562        assert_eq!(
563            env.variables().unwrap().get("FOO"),
564            Some(&"BAR".to_string())
565        );
566
567        let deploy = Deploy {
568            function_config: FunctionDeployConfig {
569                env_options: Some(EnvOptions {
570                    env_var: Some(vec!["FOO=BAR".to_string()]),
571                    ..Default::default()
572                }),
573                ..Default::default()
574            },
575            base_env: HashMap::from([("BAZ".to_string(), "QUX".to_string())]),
576            ..Default::default()
577        };
578        let env = deploy.lambda_environment().unwrap().unwrap();
579        assert_eq!(env.variables().unwrap().len(), 2);
580        assert_eq!(
581            env.variables().unwrap().get("BAZ"),
582            Some(&"QUX".to_string())
583        );
584        assert_eq!(
585            env.variables().unwrap().get("FOO"),
586            Some(&"BAR".to_string())
587        );
588
589        let temp_file = tempfile::NamedTempFile::new().unwrap();
590        let path = temp_file.path();
591        std::fs::write(path, "FOO=BAR\nBAZ=QUX").unwrap();
592
593        let deploy = Deploy {
594            function_config: FunctionDeployConfig {
595                env_options: Some(EnvOptions {
596                    env_file: Some(path.to_path_buf()),
597                    ..Default::default()
598                }),
599                ..Default::default()
600            },
601            base_env: HashMap::from([("QUUX".to_string(), "QUUX".to_string())]),
602            ..Default::default()
603        };
604        let env = deploy.lambda_environment().unwrap().unwrap();
605        assert_eq!(env.variables().unwrap().len(), 3);
606        assert_eq!(
607            env.variables().unwrap().get("BAZ"),
608            Some(&"QUX".to_string())
609        );
610        assert_eq!(
611            env.variables().unwrap().get("FOO"),
612            Some(&"BAR".to_string())
613        );
614        assert_eq!(
615            env.variables().unwrap().get("QUUX"),
616            Some(&"QUUX".to_string())
617        );
618    }
619
620    #[test]
621    fn test_load_config_from_workspace() {
622        let options = ConfigOptions {
623            name: Some("crate-3".to_string()),
624            admerge: true,
625            ..Default::default()
626        };
627
628        let metadata = load_metadata(fixture_metadata("workspace-package")).unwrap();
629        let config = load_config_without_cli_flags(&metadata, &options).unwrap();
630        assert_eq!(
631            config.deploy.function_config.timeout,
632            Some(Timeout::new(120))
633        );
634        assert_eq!(config.deploy.function_config.memory, Some(10240.into()));
635
636        let tags = config.deploy.lambda_tags().unwrap();
637        assert_eq!(tags.len(), 2);
638        assert_eq!(tags.get("organization"), Some(&"aws".to_string()));
639        assert_eq!(tags.get("team"), Some(&"lambda".to_string()));
640
641        assert_eq!(
642            config.deploy.include,
643            Some(vec!["src/bin/main.rs".to_string()])
644        );
645
646        assert_eq!(
647            config.deploy.function_config.env_options.unwrap().env_var,
648            Some(vec!["APP_ENV=production".to_string()])
649        );
650
651        assert_eq!(config.deploy.function_config.log_retention, Some(14));
652    }
653}