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
use crate::request::ApiGatewayV2;
use core::convert::TryFrom;
use core::future::Future;
use std::pin::Pin;
use lamedh_runtime::{
run as lambda_runtime_run, Context as LambdaContext, Error as LambdaError,
Handler as LambdaHandler,
};
pub async fn run_actix_on_lambda<F, I, S, B>(factory: F) -> Result<(), LambdaError>
where
F: Fn() -> I + Send + Clone + 'static,
I: actix_service::IntoServiceFactory<S, actix_http::Request>,
S: actix_service::ServiceFactory<
actix_http::Request,
Config = actix_web::dev::AppConfig,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
> + 'static,
S::InitError: std::fmt::Debug,
B: actix_web::body::MessageBody,
{
let srv = factory().into_factory();
let new_svc = srv
.new_service(actix_web::dev::AppConfig::default())
.await
.unwrap();
lambda_runtime_run(ActixHandler(new_svc)).await?;
Ok(())
}
struct ActixHandler<S, B>(S)
where
S: actix_service::Service<
actix_http::Request,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
> + 'static,
B: actix_web::body::MessageBody;
impl<S, B> LambdaHandler<ApiGatewayV2<'_>, serde_json::Value> for ActixHandler<S, B>
where
S: actix_service::Service<
actix_http::Request,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
> + 'static,
B: actix_web::body::MessageBody,
{
type Error = actix_web::Error;
type Fut = Pin<Box<dyn Future<Output = Result<serde_json::Value, Self::Error>> + 'static>>;
fn call(&mut self, event: ApiGatewayV2, _context: LambdaContext) -> Self::Fut {
use serde_json::json;
let actix_request = actix_http::Request::try_from(event);
let svc_call = actix_request.map(|req| self.0.call(req));
let fut = async move {
match svc_call {
Ok(svc_fut) => {
if let Ok(response) = svc_fut.await {
api_gateway_response_from_actix_web(response).await
} else {
Ok(json!({
"isBase64Encoded": false,
"statusCode": 500u16,
"headers": { "content-type": "text/plain"},
"body": "Internal Server Error"
}))
}
}
Err(_request_err) => {
Ok(json!({
"isBase64Encoded": false,
"statusCode": 400u16,
"headers": { "content-type": "text/plain"},
"body": "Bad Request"
}))
}
}
};
Box::pin(fut)
}
}
impl TryFrom<ApiGatewayV2<'_>> for actix_http::Request {
type Error = LambdaError;
fn try_from(event: ApiGatewayV2) -> Result<Self, Self::Error> {
use actix_web::cookie::Cookie;
use actix_web::http::Method;
use std::borrow::Cow;
use std::net::IpAddr;
use std::str::FromStr;
let path_and_query: Cow<str> = if event.raw_query_string.is_empty() {
event.raw_path
} else {
format!("{}?{}", event.raw_path, event.raw_query_string).into()
};
let method = Method::try_from(&event.request_context.http.method as &str)?;
let source_ip = IpAddr::from_str(&event.request_context.http.source_ip as &str)?;
let req = actix_web::test::TestRequest::with_uri(&path_and_query)
.method(method)
.peer_addr(std::net::SocketAddr::from((source_ip, 0u16)));
let req = if let Some(cookies) = event.cookies {
cookies.iter().fold(req, |req, cookie| {
if let Ok(cookie_decoded) = Cookie::parse_encoded(cookie as &str) {
req.cookie(cookie_decoded)
} else {
req
}
})
} else {
req
};
let req = event
.headers
.iter()
.fold(req, |req, (k, v)| req.insert_header((k as &str, v as &str)));
let req = if let Some(eventbody) = event.body {
if event.is_base64_encoded {
let binarybody = base64::decode(&eventbody as &str)?;
req.set_payload(binarybody)
} else {
req.set_payload((&eventbody as &str).to_string())
}
} else {
req
};
Ok(req.to_request())
}
}
async fn api_gateway_response_from_actix_web<B: actix_web::body::MessageBody>(
mut response: actix_web::dev::ServiceResponse<B>,
) -> Result<serde_json::Value, actix_web::Error> {
use serde_json::json;
let status_code = response.status().as_u16();
let mut headers = serde_json::Map::new();
for (k, v) in response.headers() {
if let Ok(value_str) = v.to_str() {
headers.insert(k.as_str().to_string(), json!(value_str));
}
}
let body_bytes = actix_web::body::to_bytes(response.take_body()).await?;
Ok(json!({
"isBase64Encoded": true,
"statusCode": status_code,
"headers": headers,
"body": base64::encode(body_bytes.to_vec())
}))
}