aws_smithy_http_server/request/connect_info.rs
1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The [`ConnectInfo`] struct is included in [`http::Request`]s when
7//! [`IntoMakeServiceWithConnectInfo`](crate::routing::IntoMakeServiceWithConnectInfo) is used. [`ConnectInfo`]'s
8//! [`FromParts`] implementation allows it to be extracted from the [`http::Request`].
9//!
10//! The [`example service`](https://github.com/smithy-lang/smithy-rs/blob/main/examples/pokemon-service/src/main.rs)
11//! illustrates the use of [`IntoMakeServiceWithConnectInfo`](crate::routing::IntoMakeServiceWithConnectInfo)
12//! and [`ConnectInfo`] with a service builder.
13
14use http::request::Parts;
15use thiserror::Error;
16
17use crate::{body::BoxBody, response::IntoResponse};
18
19use super::{internal_server_error, FromParts};
20
21/// The [`ConnectInfo`] was not found in the [`http::Request`] extensions.
22///
23/// Use [`IntoMakeServiceWithConnectInfo`](crate::routing::IntoMakeServiceWithConnectInfo) to ensure it's present.
24#[non_exhaustive]
25#[derive(Debug, Error)]
26#[error(
27 "`ConnectInfo` is not present in the `http::Request` extensions - consider using `aws_smithy_http_server::routing::IntoMakeServiceWithConnectInfo`"
28)]
29pub struct MissingConnectInfo;
30
31impl<Protocol> IntoResponse<Protocol> for MissingConnectInfo {
32 fn into_response(self) -> http::Response<BoxBody> {
33 internal_server_error()
34 }
35}
36
37/// Extractor for getting connection information produced by a [`Connected`](crate::routing::Connected).
38///
39/// Note this extractor requires the existence of [`ConnectInfo<T>`] in the [`http::Extensions`]. This is
40/// automatically inserted by the [`IntoMakeServiceWithConnectInfo`](crate::routing::IntoMakeServiceWithConnectInfo)
41/// middleware, which can be applied using the `into_make_service_with_connect_info` method on your generated service.
42#[derive(Clone, Debug)]
43pub struct ConnectInfo<T>(
44 /// The type produced via [`Connected`](crate::routing::Connected).
45 pub T,
46);
47
48impl<P, T> FromParts<P> for ConnectInfo<T>
49where
50 T: Send + Sync + 'static,
51{
52 type Rejection = MissingConnectInfo;
53
54 fn from_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
55 parts.extensions.remove().ok_or(MissingConnectInfo)
56 }
57}