aws-smithy-http-server 0.66.4

Server runtime for Smithy Rust Server Framework.
Documentation
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use http::uri;
use lambda_http::{Request, RequestExt};
use std::{
    fmt::Debug,
    task::{Context, Poll},
};
use tower::Service;

type ServiceRequest = http::Request<crate::body::BoxBodySync>;

/// A [`Service`] that takes a `lambda_http::Request` and converts
/// it to `http::Request<BoxBody>`.
///
/// **This version is only guaranteed to be compatible with
/// [`lambda_http`](https://docs.rs/lambda_http) ^1.** Please ensure that your service crate's
/// `Cargo.toml` depends on a compatible version.
///
/// [`Service`]: tower::Service
#[derive(Debug, Clone)]
pub struct LambdaHandler<S> {
    service: S,
}

impl<S> LambdaHandler<S> {
    pub fn new(service: S) -> Self {
        Self { service }
    }
}

impl<S> Service<Request> for LambdaHandler<S>
where
    S: Service<ServiceRequest>,
{
    type Error = S::Error;
    type Response = S::Response;
    type Future = S::Future;

    #[inline]
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, event: Request) -> Self::Future {
        self.service.call(convert_event(event))
    }
}

/// Converts a `lambda_http::Request` into a `http::Request<crate::body::BoxBodySync>`
/// Issue: <https://github.com/smithy-lang/smithy-rs/issues/1125>
///
/// While converting the event the [API Gateway Stage] portion of the URI
/// is removed from the uri that gets returned as a new `http::Request`.
///
/// [API Gateway Stage]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html
fn convert_event(request: Request) -> ServiceRequest {
    let raw_path: &str = request.extensions().raw_http_path();
    let path: &str = request.uri().path();

    let (parts, body) = if !raw_path.is_empty() && raw_path != path {
        let mut path = raw_path.to_owned(); // Clone only when we need to strip out the stage.
        let (mut parts, body) = request.into_parts();

        let uri_parts: uri::Parts = parts.uri.into();
        let path_and_query = uri_parts
            .path_and_query
            .expect("request URI does not have `PathAndQuery`");

        if let Some(query) = path_and_query.query() {
            path.push('?');
            path.push_str(query);
        }

        parts.uri = uri::Uri::builder()
            .authority(uri_parts.authority.expect("request URI does not have authority set"))
            .scheme(uri_parts.scheme.expect("request URI does not have scheme set"))
            .path_and_query(path)
            .build()
            .expect("unable to construct new URI");

        (parts, body)
    } else {
        request.into_parts()
    };

    let body = match body {
        lambda_http::Body::Empty => crate::body::empty_sync(),
        lambda_http::Body::Text(s) => crate::body::to_boxed_sync(s),
        lambda_http::Body::Binary(v) => crate::body::to_boxed_sync(v),
        _ => {
            tracing::error!("Unknown `lambda_http::Body` variant encountered, falling back to empty body");
            crate::body::empty_sync()
        }
    };

    http::Request::from_parts(parts, body)
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use lambda_http::RequestExt;

    /// Test utility to collect all bytes from a body.
    async fn collect_bytes<B>(body: B) -> Result<Bytes, crate::Error>
    where
        B: http_body::Body,
        B::Error: Into<crate::error::BoxError>,
    {
        use http_body_util::BodyExt;
        let collected = body.collect().await.map_err(crate::Error::new)?;
        Ok(collected.to_bytes())
    }

    #[test]
    fn traits() {
        use crate::test_helpers::*;

        assert_send::<LambdaHandler<()>>();
        assert_sync::<LambdaHandler<()>>();
    }

    #[test]
    fn raw_http_path() {
        // lambda_http::Request doesn't have a fn `builder`
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/prod/resources/1")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();

        // the lambda event will have a raw path which is the path without stage name in it
        let event =
            lambda_http::Request::from_parts(parts, lambda_http::Body::Empty).with_raw_http_path("/resources/1");
        let request = convert_event(event);

        assert_eq!(request.uri().path(), "/resources/1");
    }

    #[tokio::test]
    async fn body_conversion_empty() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);
        let request = convert_event(event);
        let bytes = collect_bytes(request.into_body()).await.unwrap();
        assert_eq!(bytes.len(), 0);
    }

    #[tokio::test]
    async fn body_conversion_text() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Text("hello world".to_string()));
        let request = convert_event(event);
        let bytes = collect_bytes(request.into_body()).await.unwrap();
        assert_eq!(bytes, "hello world");
    }

    #[tokio::test]
    async fn body_conversion_binary() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Binary(vec![1, 2, 3, 4, 5]));
        let request = convert_event(event);
        let bytes = collect_bytes(request.into_body()).await.unwrap();
        assert_eq!(bytes.as_ref(), &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn uri_with_query_string() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/prod/resources/1?foo=bar&baz=qux")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event =
            lambda_http::Request::from_parts(parts, lambda_http::Body::Empty).with_raw_http_path("/resources/1");
        let request = convert_event(event);

        assert_eq!(request.uri().path(), "/resources/1");
        assert_eq!(request.uri().query(), Some("foo=bar&baz=qux"));
    }

    #[test]
    fn uri_without_stage_stripping() {
        // When raw_http_path is empty or matches the path, no stripping should occur
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/resources/1")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);
        let request = convert_event(event);

        assert_eq!(request.uri().path(), "/resources/1");
    }

    #[test]
    fn headers_are_preserved() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .header("content-type", "application/json")
            .header("x-custom-header", "custom-value")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);
        let request = convert_event(event);

        assert_eq!(request.headers().get("content-type").unwrap(), "application/json");
        assert_eq!(request.headers().get("x-custom-header").unwrap(), "custom-value");
    }

    #[test]
    fn extensions_are_preserved() {
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .body(())
            .expect("unable to build Request");
        let (mut parts, _) = event.into_parts();

        // Add a test extension
        #[derive(Debug, Clone, PartialEq)]
        struct TestExtension(String);
        parts.extensions.insert(TestExtension("test-value".to_string()));

        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);
        let request = convert_event(event);

        let ext = request.extensions().get::<TestExtension>();
        assert!(ext.is_some());
        assert_eq!(ext.unwrap(), &TestExtension("test-value".to_string()));
    }

    #[test]
    fn method_is_preserved() {
        let event = http::Request::builder()
            .method("POST")
            .uri("https://id.execute-api.us-east-1.amazonaws.com/test")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);
        let request = convert_event(event);

        assert_eq!(request.method(), http::Method::POST);
    }

    #[tokio::test]
    async fn lambda_handler_service_integration() {
        use tower::ServiceExt;

        // Create a simple service that echoes the URI path
        let inner_service = tower::service_fn(|req: ServiceRequest| async move {
            let path = req.uri().path().to_string();
            let response = http::Response::builder()
                .status(200)
                .body(crate::body::to_boxed(path))
                .unwrap();
            Ok::<_, std::convert::Infallible>(response)
        });

        let mut lambda_handler = LambdaHandler::new(inner_service);

        // Create a lambda request
        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/prod/test/path")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty).with_raw_http_path("/test/path");

        // Call the service
        let response = lambda_handler.ready().await.unwrap().call(event).await.unwrap();

        // Verify response
        assert_eq!(response.status(), 200);
        let body_bytes = collect_bytes(response.into_body()).await.unwrap();
        assert_eq!(body_bytes, "/test/path");
    }

    #[tokio::test]
    async fn lambda_handler_with_request_body() {
        use tower::ServiceExt;

        // Create a service that processes the request body
        let inner_service = tower::service_fn(|req: ServiceRequest| async move {
            let body_bytes = collect_bytes(req.into_body()).await.unwrap();
            let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();

            let response_body = format!("Received: {body_str}");
            let response = http::Response::builder()
                .status(200)
                .header("content-type", "text/plain")
                .body(crate::body::to_boxed(response_body))
                .unwrap();
            Ok::<_, std::convert::Infallible>(response)
        });

        let mut lambda_handler = LambdaHandler::new(inner_service);

        // Create a lambda request with JSON body
        let event = http::Request::builder()
            .method("POST")
            .uri("https://id.execute-api.us-east-1.amazonaws.com/api/process")
            .header("content-type", "application/json")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Text(r#"{"key":"value"}"#.to_string()));

        // Call the service
        let response = lambda_handler.ready().await.unwrap().call(event).await.unwrap();

        // Verify response
        assert_eq!(response.status(), 200);
        assert_eq!(response.headers().get("content-type").unwrap(), "text/plain");
        let body_bytes = collect_bytes(response.into_body()).await.unwrap();
        assert_eq!(body_bytes, r#"Received: {"key":"value"}"#);
    }

    #[tokio::test]
    async fn lambda_handler_response_headers() {
        use tower::ServiceExt;

        // Create a service that returns custom headers
        let inner_service = tower::service_fn(|_req: ServiceRequest| async move {
            let response = http::Response::builder()
                .status(201)
                .header("x-custom-header", "custom-value")
                .header("content-type", "application/json")
                .header("x-request-id", "12345")
                .body(crate::body::to_boxed(r#"{"status":"created"}"#))
                .unwrap();
            Ok::<_, std::convert::Infallible>(response)
        });

        let mut lambda_handler = LambdaHandler::new(inner_service);

        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/api/create")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);

        // Call the service
        let response = lambda_handler.ready().await.unwrap().call(event).await.unwrap();

        // Verify all response components
        assert_eq!(response.status(), 201);
        assert_eq!(response.headers().get("x-custom-header").unwrap(), "custom-value");
        assert_eq!(response.headers().get("content-type").unwrap(), "application/json");
        assert_eq!(response.headers().get("x-request-id").unwrap(), "12345");

        let body_bytes = collect_bytes(response.into_body()).await.unwrap();
        assert_eq!(body_bytes, r#"{"status":"created"}"#);
    }

    #[tokio::test]
    async fn lambda_handler_error_response() {
        use tower::ServiceExt;

        // Create a service that returns an error status
        let inner_service = tower::service_fn(|_req: ServiceRequest| async move {
            let response = http::Response::builder()
                .status(404)
                .header("content-type", "application/json")
                .body(crate::body::to_boxed(r#"{"error":"not found"}"#))
                .unwrap();
            Ok::<_, std::convert::Infallible>(response)
        });

        let mut lambda_handler = LambdaHandler::new(inner_service);

        let event = http::Request::builder()
            .uri("https://id.execute-api.us-east-1.amazonaws.com/api/missing")
            .body(())
            .expect("unable to build Request");
        let (parts, _) = event.into_parts();
        let event = lambda_http::Request::from_parts(parts, lambda_http::Body::Empty);

        // Call the service
        let response = lambda_handler.ready().await.unwrap().call(event).await.unwrap();

        // Verify error response
        assert_eq!(response.status(), 404);
        let body_bytes = collect_bytes(response.into_body()).await.unwrap();
        assert_eq!(body_bytes, r#"{"error":"not found"}"#);
    }
}