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
use cargo_lambda_remote::{
aws_sdk_lambda::{types::Blob, Client as LambdaClient},
RemoteConfig,
};
use clap::{Args, ValueHint};
use miette::{IntoDiagnostic, Result, WrapErr};
use reqwest::{Client, StatusCode};
use serde_json::{from_str, to_string_pretty, value::Value};
use std::{
convert::TryFrom,
fs::{create_dir_all, read_to_string, File},
io::copy,
net::IpAddr,
path::PathBuf,
str::{from_utf8, FromStr},
};
use strum_macros::{Display, EnumString};
mod error;
use error::*;
pub const DEFAULT_PACKAGE_FUNCTION: &str = "@package-bootstrap@";
#[derive(Args, Clone, Debug)]
#[clap(name = "invoke")]
pub struct Invoke {
#[clap(short = 'a', long, default_value = "127.0.0.1")]
invoke_address: String,
#[clap(short = 'p', long, default_value = "9000")]
invoke_port: u16,
#[clap(long, parse(from_os_str), value_hint = ValueHint::FilePath)]
data_file: Option<PathBuf>,
#[clap(long)]
data_ascii: Option<String>,
#[clap(long)]
data_example: Option<String>,
#[clap(long)]
remote: bool,
#[clap(flatten)]
remote_config: RemoteConfig,
#[clap(long, default_value_t = OutputFormat::Text)]
output_format: OutputFormat,
#[clap(default_value = DEFAULT_PACKAGE_FUNCTION)]
function_name: String,
}
#[derive(Clone, Debug, Display, EnumString)]
#[strum(ascii_case_insensitive)]
enum OutputFormat {
Text,
Json,
}
impl Invoke {
#[tracing::instrument(skip(self), target = "cargo_lambda")]
pub async fn run(&self) -> Result<()> {
tracing::trace!(options = ?self, "invoking function");
let data = if let Some(file) = &self.data_file {
read_to_string(file)
.into_diagnostic()
.wrap_err("error reading data file")?
} else if let Some(data) = &self.data_ascii {
data.clone()
} else if let Some(example) = &self.data_example {
let name = format!("example-{example}.json");
let cache = dirs::cache_dir()
.map(|p| p.join("cargo-lambda").join("invoke-fixtures").join(&name));
match cache {
Some(cache) if cache.exists() => read_to_string(cache)
.into_diagnostic()
.wrap_err("error reading data file")?,
_ => download_example(&name, cache).await?,
}
} else {
return Err(InvokeError::MissingPayload.into());
};
let text = if self.remote {
self.invoke_remote(&data).await?
} else {
self.invoke_local(&data).await?
};
let text = match &self.output_format {
OutputFormat::Text => text,
OutputFormat::Json => {
let obj: Value = from_str(&text)
.into_diagnostic()
.wrap_err("failed to serialize response into json")?;
to_string_pretty(&obj)
.into_diagnostic()
.wrap_err("failed to format json output")?
}
};
println!("{text}");
Ok(())
}
async fn invoke_remote(&self, data: &str) -> Result<String> {
if self.function_name == DEFAULT_PACKAGE_FUNCTION {
return Err(InvokeError::InvalidFunctionName.into());
}
let sdk_config = self.remote_config.sdk_config(None).await;
let client = LambdaClient::new(&sdk_config);
let resp = client
.invoke()
.function_name(&self.function_name)
.set_qualifier(self.remote_config.alias.clone())
.payload(Blob::new(data.as_bytes()))
.send()
.await
.into_diagnostic()
.wrap_err("failed to invoke remote function")?;
if let Some(payload) = resp.payload {
let blob = payload.into_inner();
let data = from_utf8(&blob)
.into_diagnostic()
.wrap_err("failed to read response payload")?;
if resp.function_error.is_some() {
let err = RemoteInvokeError::try_from(data)?;
Err(err.into())
} else {
Ok(data.into())
}
} else {
Ok("OK".into())
}
}
async fn invoke_local(&self, data: &str) -> Result<String> {
let host = parse_invoke_ip_address(&self.invoke_address)?;
let url = format!(
"http://{}:{}/2015-03-31/functions/{}/invocations",
&host, self.invoke_port, &self.function_name
);
let client = Client::new();
let resp = client
.post(url)
.body(data.to_string())
.send()
.await
.into_diagnostic()
.wrap_err("error sending request to the runtime emulator")?;
let success = resp.status() == StatusCode::OK;
let payload = resp
.text()
.await
.into_diagnostic()
.wrap_err("error reading response body")?;
if success {
Ok(payload)
} else {
let err = RemoteInvokeError::try_from(payload.as_str())?;
Err(err.into())
}
}
}
async fn download_example(name: &str, cache: Option<PathBuf>) -> Result<String> {
let target = format!("https://github.com/LegNeato/aws-lambda-events/raw/master/aws_lambda_events/src/generated/fixtures/{name}");
let response = reqwest::get(&target)
.await
.into_diagnostic()
.wrap_err("error dowloading example data")?;
if response.status() != StatusCode::OK {
Err(InvokeError::ExampleDownloadFailed(target, response).into())
} else {
let content = response
.text()
.await
.into_diagnostic()
.wrap_err("error reading example data")?;
if let Some(cache) = cache {
create_dir_all(cache.parent().unwrap()).into_diagnostic()?;
let mut dest = File::create(cache).into_diagnostic()?;
copy(&mut content.as_bytes(), &mut dest).into_diagnostic()?;
}
Ok(content)
}
}
fn parse_invoke_ip_address(address: &str) -> Result<String> {
let invoke_address = IpAddr::from_str(address).map_err(|e| miette::miette!(e))?;
let invoke_address = match invoke_address {
IpAddr::V4(address) => address.to_string(),
IpAddr::V6(address) => format!("[{}]", address),
};
Ok(invoke_address)
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn test_download_example() {
let data = download_example("example-apigw-request.json", None)
.await
.expect("failed to download json");
assert!(data.contains("\"path\": \"/hello/world\""));
}
}