forked from aws/aws-lambda-rust-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequests.rs
More file actions
262 lines (224 loc) · 9.31 KB
/
Copy pathrequests.rs
File metadata and controls
262 lines (224 loc) · 9.31 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
use crate::{types::ToStreamErrorTrailer, Diagnostic, Error, FunctionResponse, IntoFunctionResponse};
use bytes::Bytes;
use http::{header::CONTENT_TYPE, Method, Request, Uri};
use lambda_runtime_api_client::{body::Body, build_request};
use serde::Serialize;
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use tokio_stream::{Stream, StreamExt};
pub(crate) trait IntoRequest {
fn into_req(self) -> Result<Request<Body>, Error>;
}
// /runtime/invocation/next
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct NextEventRequest;
impl IntoRequest for NextEventRequest {
fn into_req(self) -> Result<Request<Body>, Error> {
let req = build_request()
.method(Method::GET)
.uri(Uri::from_static("/2018-06-01/runtime/invocation/next"))
.body(Default::default())?;
Ok(req)
}
}
// /runtime/invocation/{AwsRequestId}/response
pub(crate) struct EventCompletionRequest<'a, R, B, S, D, E>
where
R: IntoFunctionResponse<B, S>,
B: Serialize,
S: Stream<Item = Result<D, E>> + Unpin + Send + 'static,
D: Into<Bytes> + Send,
E: Into<Error> + Send + Debug,
{
pub(crate) request_id: &'a str,
pub(crate) body: R,
pub(crate) _unused_b: PhantomData<B>,
pub(crate) _unused_s: PhantomData<S>,
}
impl<'a, R, B, D, E, S> EventCompletionRequest<'a, R, B, S, D, E>
where
R: IntoFunctionResponse<B, S>,
B: Serialize,
S: Stream<Item = Result<D, E>> + Unpin + Send + 'static,
D: Into<Bytes> + Send,
E: Into<Error> + Send + Debug,
{
/// Initialize a new EventCompletionRequest
pub(crate) fn new(request_id: &'a str, body: R) -> EventCompletionRequest<'a, R, B, S, D, E> {
EventCompletionRequest {
request_id,
body,
_unused_b: PhantomData::<B>,
_unused_s: PhantomData::<S>,
}
}
}
impl<R, B, S, D, E> IntoRequest for EventCompletionRequest<'_, R, B, S, D, E>
where
R: IntoFunctionResponse<B, S>,
B: Serialize,
S: Stream<Item = Result<D, E>> + Unpin + Send + 'static,
D: Into<Bytes> + Send,
E: Into<Error> + Send + Debug,
{
fn into_req(self) -> Result<Request<Body>, Error> {
match self.body.into_response() {
FunctionResponse::BufferedResponse(body) => {
let uri = format!("/2018-06-01/runtime/invocation/{}/response", self.request_id);
let uri = Uri::from_str(&uri)?;
let body = serde_json::to_vec(&body)?;
let body = Body::from(body);
let req = build_request().method(Method::POST).uri(uri).body(body)?;
Ok(req)
}
FunctionResponse::StreamingResponse(mut response) => {
let uri = format!("/2018-06-01/runtime/invocation/{}/response", self.request_id);
let uri = Uri::from_str(&uri)?;
let mut builder = build_request().method(Method::POST).uri(uri);
let req_headers = builder.headers_mut().unwrap();
req_headers.insert("Transfer-Encoding", "chunked".parse()?);
req_headers.insert("Lambda-Runtime-Function-Response-Mode", "streaming".parse()?);
// Report midstream errors using error trailers.
// See the details in Lambda Developer Doc: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html#runtimes-custom-response-streaming
req_headers.append("Trailer", "Lambda-Runtime-Function-Error-Type".parse()?);
req_headers.append("Trailer", "Lambda-Runtime-Function-Error-Body".parse()?);
req_headers.insert(
"Content-Type",
"application/vnd.awslambda.http-integration-response".parse()?,
);
// default Content-Type
let preloud_headers = &mut response.metadata_prelude.headers;
preloud_headers
.entry(CONTENT_TYPE)
.or_insert("application/octet-stream".parse()?);
let metadata_prelude = serde_json::to_string(&response.metadata_prelude)?;
tracing::trace!(?metadata_prelude);
let (mut tx, rx) = Body::channel();
tokio::spawn(async move {
if tx.send_data(metadata_prelude.into()).await.is_err() {
tracing::error!("Error sending metadata prelude, response channel closed");
return;
}
if tx.send_data("\u{0}".repeat(8).into()).await.is_err() {
tracing::error!("Error sending metadata prelude delimiter, response channel closed");
return;
}
while let Some(chunk) = response.stream.next().await {
let chunk = match chunk {
Ok(chunk) => chunk.into(),
Err(err) => err.into().to_tailer().into(),
};
if tx.send_data(chunk).await.is_err() {
tracing::error!("Error sending response body chunk, response channel closed");
return;
}
}
});
let req = builder.body(rx)?;
Ok(req)
}
}
}
}
#[test]
fn test_event_completion_request() {
let req = EventCompletionRequest::new("id", "hello, world!");
let req = req.into_req().unwrap();
let expected = Uri::from_static("/2018-06-01/runtime/invocation/id/response");
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri(), &expected);
assert!(match req.headers().get("User-Agent") {
Some(header) => header.to_str().unwrap().starts_with("aws-lambda-rust/"),
None => false,
});
}
// /runtime/invocation/{AwsRequestId}/error
pub(crate) struct EventErrorRequest<'a> {
pub(crate) request_id: &'a str,
pub(crate) diagnostic: Diagnostic,
}
impl<'a> EventErrorRequest<'a> {
pub(crate) fn new(request_id: &'a str, diagnostic: impl Into<Diagnostic>) -> EventErrorRequest<'a> {
EventErrorRequest {
request_id,
diagnostic: diagnostic.into(),
}
}
}
impl IntoRequest for EventErrorRequest<'_> {
fn into_req(self) -> Result<Request<Body>, Error> {
let uri = format!("/2018-06-01/runtime/invocation/{}/error", self.request_id);
let uri = Uri::from_str(&uri)?;
let body = serde_json::to_vec(&self.diagnostic)?;
let body = Body::from(body);
let req = build_request()
.method(Method::POST)
.uri(uri)
.header("lambda-runtime-function-error-type", "unhandled")
.body(body)?;
Ok(req)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_next_event_request() {
let req = NextEventRequest;
let req = req.into_req().unwrap();
assert_eq!(req.method(), Method::GET);
assert_eq!(req.uri(), &Uri::from_static("/2018-06-01/runtime/invocation/next"));
assert!(match req.headers().get("User-Agent") {
Some(header) => header.to_str().unwrap().starts_with("aws-lambda-rust/"),
None => false,
});
}
#[test]
fn test_event_error_request() {
let req = EventErrorRequest {
request_id: "id",
diagnostic: Diagnostic {
error_type: "InvalidEventDataError".into(),
error_message: "Error parsing event data".into(),
},
};
let req = req.into_req().unwrap();
let expected = Uri::from_static("/2018-06-01/runtime/invocation/id/error");
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri(), &expected);
assert!(match req.headers().get("User-Agent") {
Some(header) => header.to_str().unwrap().starts_with("aws-lambda-rust/"),
None => false,
});
}
#[tokio::test]
async fn streaming_send_data_error_is_ignored() {
use crate::StreamResponse;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
// Track if a panic occurred in any spawned task
let panicked = Arc::new(AtomicBool::new(false));
let panicked_clone = panicked.clone();
// Set a custom panic hook to detect panics in spawned tasks
let old_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |_| {
panicked_clone.store(true, Ordering::SeqCst);
}));
let stream = tokio_stream::iter(vec![Ok::<Bytes, Error>(Bytes::from_static(b"chunk"))]);
let stream_response: StreamResponse<_> = stream.into();
let response = FunctionResponse::StreamingResponse(stream_response);
let req: EventCompletionRequest<'_, _, (), _, _, _> = EventCompletionRequest::new("id", response);
let http_req = req.into_req().expect("into_req should succeed");
// immediate drop simulates client disconnection
drop(http_req);
// give the spawned task time to run and potentially panic
tokio::time::sleep(Duration::from_millis(10)).await;
// Restore the old panic hook
std::panic::set_hook(old_hook);
assert!(
!panicked.load(Ordering::SeqCst),
"spawned task panicked - send_data errors should be ignored, not unwrapped"
);
}
}