-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathapi_client.rs
More file actions
314 lines (266 loc) · 11.3 KB
/
Copy pathapi_client.rs
File metadata and controls
314 lines (266 loc) · 11.3 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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::LambdaInvocation;
use futures::{future::BoxFuture, ready, FutureExt, TryFutureExt};
use hyper::body::Incoming;
use lambda_runtime_api_client::{body::Body, BoxError, Client};
use pin_project::pin_project;
use std::{future::Future, pin::Pin, sync::Arc, task};
use tower::Service;
use tracing::error;
/// Tower service that sends a Lambda Runtime API response to the Lambda Runtime HTTP API using
/// a previously initialized client.
///
/// This type is only meant for internal use in the Lambda runtime crate. It neither augments the
/// inner service's request type nor its error type. However, this service returns an empty
/// response `()` as the Lambda request has been completed.
pub struct RuntimeApiClientService<S> {
inner: S,
client: Arc<Client>,
}
impl<S> RuntimeApiClientService<S> {
pub fn new(inner: S, client: Arc<Client>) -> Self {
Self { inner, client }
}
}
impl<S> Service<LambdaInvocation> for RuntimeApiClientService<S>
where
S: Service<LambdaInvocation, Error = BoxError>,
S::Future: Future<Output = Result<http::Request<Body>, BoxError>>,
{
type Response = ();
type Error = S::Error;
type Future = RuntimeApiClientFuture<S::Future>;
fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: LambdaInvocation) -> Self::Future {
let request_fut = self.inner.call(req);
let client = self.client.clone();
RuntimeApiClientFuture::First(request_fut, client)
}
}
impl<S> Clone for RuntimeApiClientService<S>
where
S: Clone,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
client: self.client.clone(),
}
}
}
#[pin_project(project = RuntimeApiClientFutureProj)]
pub enum RuntimeApiClientFuture<F> {
First(#[pin] F, Arc<Client>),
Second(#[pin] BoxFuture<'static, Result<http::Response<Incoming>, BoxError>>),
}
impl<F> Future for RuntimeApiClientFuture<F>
where
F: Future<Output = Result<http::Request<Body>, BoxError>>,
{
type Output = Result<(), BoxError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
// NOTE: We loop here to directly poll the second future once the first has finished.
task::Poll::Ready(loop {
match self.as_mut().project() {
RuntimeApiClientFutureProj::First(fut, client) => match ready!(fut.poll(cx)) {
Ok(ok) => {
// NOTE: We use 'client.call_boxed' here to obtain a future with static
// lifetime. Otherwise, this future would need to be self-referential...
let next_fut = client
.call(ok)
.map_err(|err| {
error!(error = ?err, "failed to send request to Lambda Runtime API");
err
})
.boxed();
self.set(RuntimeApiClientFuture::Second(next_fut));
}
Err(err) => {
log_or_print!(
tracing: tracing::error!(error = ?err, "failed to build Lambda Runtime API request"),
fallback: eprintln!("failed to build Lambda Runtime API request: {err:?}")
);
break Err(err);
}
},
RuntimeApiClientFutureProj::Second(fut) => match ready!(fut.poll(cx)) {
Ok(resp) if !resp.status().is_success() => {
let status = resp.status();
// TODO
// we should consume the response body of the call in order to give a more specific message.
// https://github.com/aws/aws-lambda-rust-runtime/issues/1110
log_or_print!(
tracing: tracing::error!(status = %status, "Lambda Runtime API returned non-200 response"),
fallback: eprintln!("Lambda Runtime API returned non-200 response: status={status}")
);
// Adding more information on top of 410 Gone, to make it more clear since we cannot access the body of the message
if status == 410 {
log_or_print!(
tracing: tracing::error!("Lambda function timeout!"),
fallback: eprintln!("Lambda function timeout!")
);
}
// Return Ok to maintain existing contract - runtime continues despite API errors
break Ok(());
}
Ok(_) => break Ok(()),
Err(err) => {
log_or_print!(
tracing: tracing::error!(error = ?err, "Lambda Runtime API request failed"),
fallback: eprintln!("Lambda Runtime API request failed: {err:?}")
);
break Err(err);
}
},
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::StatusCode;
use http_body_util::Full;
use hyper::body::Bytes;
use lambda_runtime_api_client::body::Body;
use std::convert::Infallible;
use tokio::net::TcpListener;
use tracing_test::traced_test;
async fn start_mock_server(status: StatusCode) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}", addr);
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let io = hyper_util::rt::TokioIo::new(stream);
let service = hyper::service::service_fn(move |_req| async move {
Ok::<_, Infallible>(
http::Response::builder()
.status(status)
.body(Full::new(Bytes::from("test response")))
.unwrap(),
)
});
let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
.serve_connection(io, service)
.await;
});
// Give the server a moment to start
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
url
}
#[tokio::test]
#[traced_test]
async fn test_successful_response() {
let url = start_mock_server(StatusCode::OK).await;
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint(url.parse().unwrap())
.build()
.unwrap(),
);
let request_fut =
async { Ok::<_, BoxError>(http::Request::builder().uri("/test").body(Body::empty()).unwrap()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
assert!(result.is_ok());
// No error logs should be present
assert!(!logs_contain("Lambda Runtime API returned non-200 response"));
}
#[tokio::test]
#[traced_test]
async fn test_410_timeout_error() {
let url = start_mock_server(StatusCode::GONE).await;
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint(url.parse().unwrap())
.build()
.unwrap(),
);
let request_fut =
async { Ok::<_, BoxError>(http::Request::builder().uri("/test").body(Body::empty()).unwrap()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
// Returns Ok to maintain contract, but logs the error
assert!(result.is_ok());
// Verify the error was logged
assert!(logs_contain("Lambda Runtime API returned non-200 response"));
assert!(logs_contain("Lambda function timeout!"));
}
#[tokio::test]
#[traced_test]
async fn test_500_error() {
let url = start_mock_server(StatusCode::INTERNAL_SERVER_ERROR).await;
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint(url.parse().unwrap())
.build()
.unwrap(),
);
let request_fut =
async { Ok::<_, BoxError>(http::Request::builder().uri("/test").body(Body::empty()).unwrap()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
// Returns Ok to maintain contract, but logs the error
assert!(result.is_ok());
// Verify the error was logged with status code
assert!(logs_contain("Lambda Runtime API returned non-200 response"));
}
#[tokio::test]
#[traced_test]
async fn test_404_error() {
let url = start_mock_server(StatusCode::NOT_FOUND).await;
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint(url.parse().unwrap())
.build()
.unwrap(),
);
let request_fut =
async { Ok::<_, BoxError>(http::Request::builder().uri("/test").body(Body::empty()).unwrap()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
// Returns Ok to maintain contract, but logs the error
assert!(result.is_ok());
// Verify the error was logged
assert!(logs_contain("Lambda Runtime API returned non-200 response"));
}
#[tokio::test]
#[traced_test]
async fn test_request_build_error() {
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint("http://localhost:9001".parse().unwrap())
.build()
.unwrap(),
);
let request_fut = async { Err::<http::Request<Body>, BoxError>("Request build error".into()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.to_string().contains("Request build error"));
// Verify the error was logged
assert!(logs_contain("failed to build Lambda Runtime API request"));
}
#[tokio::test]
#[traced_test]
async fn test_network_error() {
// Use an invalid endpoint that will fail to connect
let client = Arc::new(
lambda_runtime_api_client::Client::builder()
.with_endpoint("http://127.0.0.1:1".parse().unwrap()) // Port 1 should be unreachable
.build()
.unwrap(),
);
let request_fut =
async { Ok::<_, BoxError>(http::Request::builder().uri("/test").body(Body::empty()).unwrap()) };
let future = RuntimeApiClientFuture::First(request_fut, client);
let result = future.await;
// Network errors should propagate as Err
assert!(result.is_err());
// Verify the error was logged
assert!(logs_contain("Lambda Runtime API request failed"));
}
}