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
use aws_smithy_types::retry::{RetryConfig, RetryMode};
use cargo_lambda_build::{find_binary_archive, zip_binary, BinaryArchive};
use cargo_lambda_interactive::progress::Progress;
use cargo_lambda_metadata::cargo::main_binary;
use cargo_lambda_remote::{
aws_sdk_lambda::model::{Architecture, Runtime},
RemoteConfig,
};
use clap::{Args, ValueHint};
use miette::{IntoDiagnostic, Result, WrapErr};
use serde::Serialize;
use serde_json::ser::to_string_pretty;
use std::{collections::HashMap, fs::read, path::PathBuf, time::Duration};
use strum_macros::{Display, EnumString};
mod extensions;
mod functions;
mod roles;
#[derive(Clone, Debug, Display, EnumString)]
#[strum(ascii_case_insensitive)]
enum OutputFormat {
Text,
Json,
}
#[derive(Serialize)]
#[serde(untagged)]
enum DeployResult {
Extension(extensions::DeployOutput),
Function(functions::DeployOutput),
}
impl std::fmt::Display for DeployResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DeployResult::Extension(o) => o.fmt(f),
DeployResult::Function(o) => o.fmt(f),
}
}
}
#[derive(Args, Clone, Debug)]
#[command(
name = "deploy",
after_help = "Full command documentation: https://www.cargo-lambda.info/commands/deploy.html"
)]
pub struct Deploy {
#[command(flatten)]
remote_config: RemoteConfig,
#[command(flatten)]
function_config: functions::FunctionDeployConfig,
#[arg(short, long, value_hint = ValueHint::DirPath)]
lambda_dir: Option<PathBuf>,
#[arg(long, value_name = "PATH", default_value = "Cargo.toml")]
pub manifest_path: PathBuf,
#[arg(long)]
pub binary_name: Option<String>,
#[arg(long)]
pub binary_path: Option<PathBuf>,
#[arg(long)]
pub s3_bucket: Option<String>,
#[arg(long)]
extension: bool,
#[arg(long, value_delimiter = ',', default_value = "provided.al2")]
compatible_runtimes: Vec<String>,
#[arg(short, long, default_value_t = OutputFormat::Text)]
output_format: OutputFormat,
#[arg(long)]
tag: Option<Vec<String>>,
#[arg(long, value_delimiter = ',')]
tags: Option<Vec<String>>,
#[arg(value_name = "NAME")]
name: Option<String>,
}
impl Deploy {
#[tracing::instrument(skip(self), target = "cargo_lambda")]
pub async fn run(&self) -> Result<()> {
tracing::trace!(options = ?self, "deploying project");
if self.function_config.enable_function_url && self.function_config.disable_function_url {
return Err(miette::miette!("invalid options: --enable-function-url and --disable-function-url cannot be set together"));
}
let progress = Progress::start("loading binary data");
let (name, archive) = match self.load_archive() {
Ok(arc) => arc,
Err(err) => {
progress.finish_and_clear();
return Err(err);
}
};
let retry = RetryConfig::standard()
.with_retry_mode(RetryMode::Adaptive)
.with_max_attempts(3)
.with_initial_backoff(Duration::from_secs(5));
let sdk_config = self.remote_config.sdk_config(Some(retry)).await;
let architecture = Architecture::from(archive.architecture.as_str());
let compatible_runtimes = self
.compatible_runtimes
.iter()
.map(|runtime| Runtime::from(runtime.as_str()))
.collect::<Vec<_>>();
let binary_data = read(&archive.path)
.into_diagnostic()
.wrap_err("failed to read binary archive")?;
let mut tags = self.tags.clone();
if tags.is_none() {
tags = self.tag.clone();
}
let result = if self.extension {
extensions::deploy(
&name,
&self.manifest_path,
&sdk_config,
binary_data,
architecture,
compatible_runtimes,
&self.s3_bucket,
&tags,
&progress,
)
.await
} else {
let binary_name = self.binary_name.clone().unwrap_or_else(|| name.clone());
functions::deploy(
&name,
&binary_name,
&self.manifest_path,
&self.function_config,
&self.remote_config,
&sdk_config,
&self.s3_bucket,
&tags,
binary_data,
architecture,
&progress,
)
.await
};
progress.finish_and_clear();
let output = result?;
match &self.output_format {
OutputFormat::Text => println!("{output}"),
OutputFormat::Json => {
let text = to_string_pretty(&output)
.into_diagnostic()
.wrap_err("failed to serialize output into json")?;
println!("{text}")
}
}
Ok(())
}
fn load_archive(&self) -> Result<(String, BinaryArchive)> {
let arc = match &self.binary_path {
Some(bp) if bp.is_dir() => return Err(miette::miette!("invalid file {:?}", bp)),
Some(bp) => {
let name = match &self.name {
Some(name) => name.clone(),
None => bp
.file_name()
.and_then(|s| s.to_str())
.map(String::from)
.ok_or_else(|| miette::miette!("invalid binary path {:?}", bp))?,
};
let destination = bp
.parent()
.ok_or_else(|| miette::miette!("invalid binary path {:?}", bp))?;
let parent = if self.extension {
Some("extensions")
} else {
None
};
let arc = zip_binary(&name, bp, destination, parent)?;
(name, arc)
}
None => {
let name = match &self.name {
Some(name) => name.clone(),
None => main_binary(&self.manifest_path)?,
};
let binary_name = self.binary_name.as_deref().unwrap_or(&name);
let arc = find_binary_archive(binary_name, &self.lambda_dir, self.extension)?;
(name, arc)
}
};
Ok(arc)
}
}
pub(crate) 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
}