-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathmain.rs
More file actions
89 lines (70 loc) · 2.27 KB
/
Copy pathmain.rs
File metadata and controls
89 lines (70 loc) · 2.27 KB
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
// This example requires the following input to succeed:
// { "command": "do something" }
use lambda_runtime::{service_fn, tracing, Diagnostic, Error, LambdaEvent};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Request {
command: String,
}
#[derive(Serialize)]
struct Response {
req_id: String,
msg: String,
}
#[derive(Debug)]
struct HandlerError(String);
impl std::fmt::Display for HandlerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<HandlerError> for Diagnostic {
fn from(e: HandlerError) -> Diagnostic {
Diagnostic {
error_type: "HandlerError".into(),
error_message: e.0,
}
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
// required to enable CloudWatch error logging by the runtime
tracing::init_default_subscriber();
let max_concurrency = std::env::var("AWS_LAMBDA_MAX_CONCURRENCY").unwrap_or_else(|_| "not set".to_string());
tracing::info!(AWS_LAMBDA_MAX_CONCURRENCY = %max_concurrency, "starting concurrent handler");
let func = service_fn(my_handler);
if let Err(err) = lambda_runtime::run_concurrent(func).await {
tracing::error!(error = %err, "run error");
return Err(err);
}
Ok(())
}
pub(crate) async fn my_handler(event: LambdaEvent<Request>) -> Result<Response, HandlerError> {
let command = event.payload.command;
if command == "fail" {
return Err(HandlerError("simulated handler error".into()));
}
let resp = Response {
req_id: event.context.request_id,
msg: format!("Command {command} executed."),
};
Ok(resp)
}
#[cfg(test)]
mod tests {
use crate::{my_handler, Request};
use lambda_runtime::{Context, LambdaEvent};
#[tokio::test]
async fn response_is_good_for_simple_input() {
let id = "ID";
let mut context = Context::default();
context.request_id = id.to_string();
let payload = Request {
command: "X".to_string(),
};
let event = LambdaEvent { payload, context };
let result = my_handler(event).await.unwrap();
assert_eq!(result.msg, "Command X executed.");
assert_eq!(result.req_id, id.to_string());
}
}