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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! HTTP body utilities.
//!
//! This module provides body handling utilities for HTTP 1.x using the
//! `http-body` and `http-body-util` crates.

use crate::error::{BoxError, Error};
use bytes::Bytes;

// Used in the codegen in trait bounds.
#[doc(hidden)]
pub use http_body::Body as HttpBody;

// ============================================================================
// BoxBody - Type-Erased Body
// ============================================================================

/// The primary body type returned by the generated `smithy-rs` service.
///
/// This is a type-erased body that wraps `UnsyncBoxBody` from `http-body-util`.
/// It is `Send` but not `Sync`, making it suitable for most HTTP handlers.
pub type BoxBody = http_body_util::combinators::UnsyncBoxBody<Bytes, Error>;

/// A thread-safe body type for operations that require `Sync`.
///
/// This is used specifically for event streaming operations and lambda handlers
/// that need thread safety guarantees.
pub type BoxBodySync = http_body_util::combinators::BoxBody<Bytes, Error>;

// ============================================================================
// Body Construction Functions
// ============================================================================

// `boxed` is used in the codegen of the implementation of the operation `Handler` trait.
/// Convert an HTTP body implementing [`http_body::Body`] into a [`BoxBody`].
pub fn boxed<B>(body: B) -> BoxBody
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
    B::Error: Into<BoxError>,
{
    use http_body_util::BodyExt;

    try_downcast(body).unwrap_or_else(|body| body.map_err(Error::new).boxed_unsync())
}

/// Convert an HTTP body implementing [`http_body::Body`] into a [`BoxBodySync`].
pub fn boxed_sync<B>(body: B) -> BoxBodySync
where
    B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
    B::Error: Into<BoxError>,
{
    use http_body_util::BodyExt;
    body.map_err(Error::new).boxed()
}

#[doc(hidden)]
pub(crate) fn try_downcast<T, K>(k: K) -> Result<T, K>
where
    T: 'static,
    K: Send + 'static,
{
    let mut k = Some(k);
    if let Some(k) = <dyn std::any::Any>::downcast_mut::<Option<T>>(&mut k) {
        Ok(k.take().unwrap())
    } else {
        Err(k.unwrap())
    }
}

/// Create an empty body.
pub fn empty() -> BoxBody {
    boxed(http_body_util::Empty::<Bytes>::new())
}

/// Create an empty sync body.
pub fn empty_sync() -> BoxBodySync {
    boxed_sync(http_body_util::Empty::<Bytes>::new())
}

/// Convert bytes or similar types into a [`BoxBody`].
///
/// This simplifies codegen a little bit.
#[doc(hidden)]
pub fn to_boxed<B>(body: B) -> BoxBody
where
    B: Into<Bytes>,
{
    boxed(http_body_util::Full::new(body.into()))
}

/// Convert bytes or similar types into a [`BoxBodySync`].
///
/// This simplifies codegen a little bit.
#[doc(hidden)]
pub fn to_boxed_sync<B>(body: B) -> BoxBodySync
where
    B: Into<Bytes>,
{
    boxed_sync(http_body_util::Full::new(body.into()))
}

/// Create a body from bytes.
pub fn from_bytes(bytes: Bytes) -> BoxBody {
    boxed(http_body_util::Full::new(bytes))
}

// ============================================================================
// Stream Wrapping for Event Streaming
// ============================================================================

/// Wrap a stream of byte chunks into a BoxBody.
///
/// This is used for event streaming support. The stream should produce `Result<O, E>`
/// where `O` can be converted into `Bytes` and `E` can be converted into an error.
///
/// In hyper 0.x, `Body::wrap_stream` was available directly on the body type.
/// In hyper 1.x, the `stream` feature was removed, and the official approach is to use
/// `http_body_util::StreamBody` to convert streams into bodies, which is what this
/// function provides as a convenient wrapper.
///
/// For scenarios requiring `Sync` (e.g., lambda handlers), use [`wrap_stream_sync`] instead.
pub fn wrap_stream<S, O, E>(stream: S) -> BoxBody
where
    S: futures_util::Stream<Item = Result<O, E>> + Send + 'static,
    O: Into<Bytes> + 'static,
    E: Into<BoxError> + 'static,
{
    use futures_util::TryStreamExt;
    use http_body_util::StreamBody;

    // Convert the stream of Result<O, E> into a stream of Result<Frame<Bytes>, Error>
    let frame_stream = stream
        .map_ok(|chunk| http_body::Frame::data(chunk.into()))
        .map_err(|e| Error::new(e.into()));

    boxed(StreamBody::new(frame_stream))
}

/// Wrap a stream of byte chunks into a BoxBodySync.
///
/// This is the thread-safe variant of [`wrap_stream`], used for event streaming operations
/// that require `Sync` bounds, such as lambda handlers.
///
/// The stream should produce `Result<O, E>` where `O` can be converted into `Bytes` and
/// `E` can be converted into an error.
pub fn wrap_stream_sync<S, O, E>(stream: S) -> BoxBodySync
where
    S: futures_util::Stream<Item = Result<O, E>> + Send + Sync + 'static,
    O: Into<Bytes> + 'static,
    E: Into<BoxError> + 'static,
{
    use futures_util::TryStreamExt;
    use http_body_util::StreamBody;

    // Convert the stream of Result<O, E> into a stream of Result<Frame<Bytes>, Error>
    let frame_stream = stream
        .map_ok(|chunk| http_body::Frame::data(chunk.into()))
        .map_err(|e| Error::new(e.into()));

    boxed_sync(StreamBody::new(frame_stream))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Collect all bytes from a body (test utility).
    ///
    /// This uses `http_body_util::BodyExt::collect()` to read all body chunks
    /// into a single `Bytes` buffer.
    async fn collect_bytes<B>(body: B) -> Result<Bytes, Error>
    where
        B: HttpBody,
        B::Error: Into<BoxError>,
    {
        use http_body_util::BodyExt;

        let collected = body.collect().await.map_err(Error::new)?;
        Ok(collected.to_bytes())
    }

    #[tokio::test]
    async fn test_empty_body() {
        let body = empty();
        let bytes = collect_bytes(body).await.unwrap();
        assert_eq!(bytes.len(), 0);
    }

    #[tokio::test]
    async fn test_from_bytes() {
        let data = Bytes::from("hello world");
        let body = from_bytes(data.clone());
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, data);
    }

    #[tokio::test]
    async fn test_to_boxed_string() {
        let s = "hello world";
        let body = to_boxed(s);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from(s));
    }

    #[tokio::test]
    async fn test_to_boxed_vec() {
        let vec = vec![1u8, 2, 3, 4, 5];
        let body = to_boxed(vec.clone());
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected.as_ref(), vec.as_slice());
    }

    #[tokio::test]
    async fn test_boxed() {
        use http_body_util::Full;
        let full_body = Full::new(Bytes::from("test data"));
        let boxed_body: BoxBody = boxed(full_body);
        let collected = collect_bytes(boxed_body).await.unwrap();
        assert_eq!(collected, Bytes::from("test data"));
    }

    #[tokio::test]
    async fn test_boxed_sync() {
        use http_body_util::Full;
        let full_body = Full::new(Bytes::from("sync test"));
        let boxed_body: BoxBodySync = boxed_sync(full_body);
        let collected = collect_bytes(boxed_body).await.unwrap();
        assert_eq!(collected, Bytes::from("sync test"));
    }

    #[tokio::test]
    async fn test_wrap_stream_single_chunk() {
        use futures_util::stream;

        let data = Bytes::from("single chunk");
        let stream = stream::iter(vec![Ok::<_, std::io::Error>(data.clone())]);

        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, data);
    }

    #[tokio::test]
    async fn test_wrap_stream_multiple_chunks() {
        use futures_util::stream;

        let chunks = vec![
            Ok::<_, std::io::Error>(Bytes::from("chunk1")),
            Ok(Bytes::from("chunk2")),
            Ok(Bytes::from("chunk3")),
        ];
        let expected = Bytes::from("chunk1chunk2chunk3");

        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, expected);
    }

    #[tokio::test]
    async fn test_wrap_stream_empty() {
        use futures_util::stream;

        let stream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::new())]);

        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected.len(), 0);
    }

    #[tokio::test]
    async fn test_wrap_stream_error() {
        use futures_util::stream;

        let chunks = vec![
            Ok::<_, std::io::Error>(Bytes::from("chunk1")),
            Err(std::io::Error::other("test error")),
        ];

        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let result = collect_bytes(body).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_wrap_stream_various_types() {
        use futures_util::stream;

        // Test that Into<Bytes> works for various types

        // Test with &str
        let chunks = vec![Ok::<_, std::io::Error>("string slice"), Ok("another string")];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("string sliceanother string"));

        // Test with String
        let chunks = vec![
            Ok::<_, std::io::Error>(String::from("owned ")),
            Ok(String::from("strings")),
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("owned strings"));

        // Test with Vec<u8>
        let chunks = vec![
            Ok::<_, std::io::Error>(vec![72u8, 101, 108, 108, 111]), // "Hello"
            Ok(vec![32u8, 87, 111, 114, 108, 100]),                  // " World"
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("Hello World"));

        // Test with &[u8]
        let chunks = vec![
            Ok::<_, std::io::Error>(&[98u8, 121, 116, 101] as &[u8]), // "byte"
            Ok(&[115u8, 33] as &[u8]),                                // "s!"
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("bytes!"));

        // Test with custom struct implementing Into<Bytes>
        struct CustomChunk {
            data: String,
        }

        impl From<CustomChunk> for Bytes {
            fn from(chunk: CustomChunk) -> Bytes {
                Bytes::from(chunk.data)
            }
        }

        let chunks = vec![
            Ok::<_, std::io::Error>(CustomChunk { data: "custom ".into() }),
            Ok(CustomChunk { data: "struct".into() }),
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("custom struct"));
    }

    #[tokio::test]
    async fn test_wrap_stream_custom_stream_type() {
        use bytes::Bytes;
        use std::pin::Pin;
        use std::task::{Context, Poll};

        // Custom stream type that implements futures_util::Stream
        struct CustomStream {
            chunks: Vec<Result<Bytes, std::io::Error>>,
        }

        impl CustomStream {
            fn new(chunks: Vec<Result<Bytes, std::io::Error>>) -> Self {
                Self { chunks }
            }
        }

        impl futures_util::Stream for CustomStream {
            type Item = Result<Bytes, std::io::Error>;

            fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
                if self.chunks.is_empty() {
                    Poll::Ready(None)
                } else {
                    Poll::Ready(Some(self.chunks.remove(0)))
                }
            }
        }

        let stream = CustomStream::new(vec![Ok(Bytes::from("custom ")), Ok(Bytes::from("stream"))]);

        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("custom stream"));
    }

    #[tokio::test]
    async fn test_wrap_stream_custom_error_type() {
        use bytes::Bytes;
        use futures_util::stream;

        // Custom error type that implements Into<BoxError>
        #[derive(Debug, Clone)]
        struct CustomError {
            message: String,
        }

        impl std::fmt::Display for CustomError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "CustomError: {}", self.message)
            }
        }

        impl std::error::Error for CustomError {}

        // Test successful case with custom error type
        let chunks = vec![
            Ok::<_, CustomError>(Bytes::from("custom ")),
            Ok(Bytes::from("error type")),
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, Bytes::from("custom error type"));

        // Test error case with custom error type
        let chunks = vec![
            Ok::<_, CustomError>(Bytes::from("data")),
            Err(CustomError {
                message: "custom error".into(),
            }),
        ];
        let stream = stream::iter(chunks);
        let body = wrap_stream(stream);
        let result = collect_bytes(body).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_wrap_stream_incremental_consumption() {
        use bytes::Bytes;
        use http_body_util::BodyExt;
        use std::pin::Pin;
        use std::task::{Context, Poll};

        struct IncrementalStream {
            chunks: Vec<Result<Bytes, std::io::Error>>,
        }

        impl IncrementalStream {
            fn new(chunks: Vec<Result<Bytes, std::io::Error>>) -> Self {
                Self { chunks }
            }
        }

        impl futures_util::Stream for IncrementalStream {
            type Item = Result<Bytes, std::io::Error>;

            fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
                if self.chunks.is_empty() {
                    Poll::Ready(None)
                } else {
                    Poll::Ready(Some(self.chunks.remove(0)))
                }
            }
        }

        let stream = IncrementalStream::new(vec![
            Ok(Bytes::from("chunk1")),
            Ok(Bytes::from("chunk2")),
            Ok(Bytes::from("chunk3")),
        ]);

        let mut body = wrap_stream(stream);

        let frame1 = body.frame().await.unwrap().unwrap();
        assert!(frame1.is_data());
        assert_eq!(frame1.into_data().unwrap(), Bytes::from("chunk1"));

        let frame2 = body.frame().await.unwrap().unwrap();
        assert!(frame2.is_data());
        assert_eq!(frame2.into_data().unwrap(), Bytes::from("chunk2"));

        let frame3 = body.frame().await.unwrap().unwrap();
        assert!(frame3.is_data());
        assert_eq!(frame3.into_data().unwrap(), Bytes::from("chunk3"));

        let frame4 = body.frame().await;
        assert!(frame4.is_none());
    }

    #[tokio::test]
    async fn test_wrap_stream_sync_single_chunk() {
        use futures_util::stream;

        let data = Bytes::from("sync single chunk");
        let stream = stream::iter(vec![Ok::<_, std::io::Error>(data.clone())]);

        let body = wrap_stream_sync(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, data);
    }

    #[tokio::test]
    async fn test_wrap_stream_sync_multiple_chunks() {
        use futures_util::stream;

        let chunks = vec![
            Ok::<_, std::io::Error>(Bytes::from("sync1")),
            Ok(Bytes::from("sync2")),
            Ok(Bytes::from("sync3")),
        ];
        let expected = Bytes::from("sync1sync2sync3");

        let stream = stream::iter(chunks);
        let body = wrap_stream_sync(stream);
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, expected);
    }

    #[tokio::test]
    async fn test_empty_sync_body() {
        let body = empty_sync();
        let bytes = collect_bytes(body).await.unwrap();
        assert_eq!(bytes.len(), 0);
    }

    #[tokio::test]
    async fn test_to_boxed_sync() {
        let data = Bytes::from("sync boxed data");
        let body = to_boxed_sync(data.clone());
        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, data);
    }

    // Compile-time tests to ensure Send/Sync bounds are correct
    // Following the pattern used by hyper and axum
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}

    fn _assert_send_sync_bounds() {
        // BoxBodySync must be both Send and Sync
        _assert_send::<BoxBodySync>();
        _assert_sync::<BoxBodySync>();

        // BoxBody must be Send (but is intentionally NOT Sync - it's UnsyncBoxBody)
        _assert_send::<BoxBody>();
    }

    #[tokio::test]
    async fn test_wrap_stream_sync_produces_sync_body() {
        use futures_util::stream;

        let data = Bytes::from("test sync");
        let stream = stream::iter(vec![Ok::<_, std::io::Error>(data.clone())]);

        let body = wrap_stream_sync(stream);

        // Compile-time check: ensure the body is Sync
        fn check_sync<T: Sync>(_: &T) {}
        check_sync(&body);

        let collected = collect_bytes(body).await.unwrap();
        assert_eq!(collected, data);
    }

    #[test]
    fn test_empty_sync_is_sync() {
        let body = empty_sync();
        fn check_sync<T: Sync>(_: &T) {}
        check_sync(&body);
    }

    #[test]
    fn test_boxed_sync_is_sync() {
        use http_body_util::Full;
        let body = boxed_sync(Full::new(Bytes::from("test")));
        fn check_sync<T: Sync>(_: &T) {}
        check_sync(&body);
    }
}