navree_http/extract/mod.rs
1//! Extractors: how a handler's arguments are read from the request.
2//!
3//! A handler is an `async fn` whose arguments each implement
4//! [`FromRequestParts`] (they read the head: path, query, headers,
5//! extensions), except the last, which may implement [`FromRequest`] and
6//! read the body. An extractor that fails ends the request with its
7//! rejection, rendered as an [`AppError`](crate::AppError) in the JSON error
8//! format.
9//!
10//! | Extractor | Reads | Rejection |
11//! |---|---|---|
12//! | [`Path<T>`](crate::Path) | the route's parameters, by name or position | 400 `Invalid URL: ...`; 500 when `T` does not fit the route |
13//! | [`Query<T>`](crate::Query), [`RawQuery`] | the query string | 400 `Failed to deserialize query string: ...` |
14//! | [`Form<T>`](crate::Form) | an `application/x-www-form-urlencoded` body (the query string for `GET` and `HEAD`) | 415, 413, 400 |
15//! | [`Json<T>`](crate::Json) | an `application/json` (or `+json`) body | 415, 413, 400 |
16//! | [`Multipart`] | a `multipart/form-data` body, part by part, within [`MultipartLimits`] | 400, then 413, 408 and 400 while reading ([`MultipartError`]) |
17//! | [`WebSocketUpgrade`](crate::ws::WebSocketUpgrade) | a WebSocket handshake | 400, 405, 426 |
18//! | [`Extension<T>`](crate::Extension) | a value the pipeline put in the request | 500 |
19//! | [`Scoped<T>`](crate::Scoped) | a provider of the app, for this request | 500 |
20//! | [`ClientIp`], [`CurrentPrincipal`](crate::CurrentPrincipal), [`PathParams`](crate::routing::PathParams) | what the pipeline found | 401 for a guest (`CurrentPrincipal`) |
21//! | [`Request`], [`Body`](crate::body::Body) | the whole request, or its body unread (only as the last argument) | never |
22//! | `HeaderMap`, `Method`, `Uri`, `Version`, `Extensions`, `Parts` (from `http`) | a copy of that part of the request | never |
23//! | `Bytes`, `String` | the body, whole, within the route's [`BodyLimit`](crate::body::BodyLimit) (only as the last argument) | 413, 408, 400; 400 for a `String` that is not UTF-8 |
24//! | `Option<T>` | `T`, or `None` when it is absent (for `T` implementing [`OptionalFromRequestParts`] / [`OptionalFromRequest`]) | `T`'s, when present but invalid |
25//! | `Result<T, T::Rejection>` | `T` or its rejection, for the handler to decide | never |
26
27use std::convert::Infallible;
28use std::future::Future;
29
30use http::request::Parts;
31
32use crate::response::IntoResponse;
33
34mod client;
35mod extension;
36mod form;
37mod json;
38mod media;
39mod multipart;
40mod path;
41mod plain;
42mod query;
43pub mod rejection;
44mod scoped;
45pub mod urlencoded;
46
47pub use client::ClientIp;
48pub(crate) use client::{IpNetwork, ProxyTrust};
49pub use extension::Extension;
50pub use form::Form;
51pub use json::Json;
52pub use multipart::{Field, Multipart, MultipartLimits};
53pub use path::Path;
54pub use query::{Query, RawQuery};
55pub use rejection::MultipartError;
56pub use scoped::Scoped;
57
58/// A request, as handlers and extractors see it.
59pub type Request<B = crate::body::Body> = http::Request<B>;
60
61/// An extractor that reads the request head.
62///
63/// ```
64/// use http::request::Parts;
65/// use navree_http::AppError;
66/// use navree_http::extract::FromRequestParts;
67///
68/// /// The `X-Tenant` header.
69/// struct Tenant(String);
70///
71/// impl FromRequestParts for Tenant {
72/// type Rejection = AppError;
73///
74/// async fn from_request_parts(parts: &mut Parts) -> Result<Self, AppError> {
75/// parts
76/// .headers
77/// .get("x-tenant")
78/// .and_then(|value| value.to_str().ok())
79/// .map(|tenant| Tenant(tenant.to_owned()))
80/// .ok_or_else(|| AppError::bad_request("The X-Tenant header is missing."))
81/// }
82/// }
83/// ```
84pub trait FromRequestParts: Sized + Send {
85 /// What a failed extraction answers.
86 type Rejection: IntoResponse;
87
88 /// Reads the extractor from the request head.
89 fn from_request_parts(
90 parts: &mut Parts,
91 ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
92}
93
94/// An extractor that consumes the request (reads the body): only a handler's
95/// last argument. `M` tells body extractors ([`via::ViaRequest`], the
96/// default) from head extractors used last ([`via::ViaParts`]).
97pub trait FromRequest<M = via::ViaRequest>: Sized + Send {
98 /// What a failed extraction answers.
99 type Rejection: IntoResponse;
100
101 /// Reads the extractor from the request.
102 fn from_request(request: Request)
103 -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
104}
105
106impl<T: FromRequestParts> FromRequest<via::ViaParts> for T {
107 type Rejection = T::Rejection;
108
109 async fn from_request(request: Request) -> Result<Self, Self::Rejection> {
110 let (mut parts, _body) = request.into_parts();
111 T::from_request_parts(&mut parts).await
112 }
113}
114
115/// A head extractor that may be absent: `Option<T>` is `None` then, and
116/// still fails when the value is there but invalid.
117pub trait OptionalFromRequestParts: Sized + Send {
118 /// What a failed extraction answers.
119 type Rejection: IntoResponse;
120
121 /// Reads the extractor, `None` when the request does not carry it.
122 fn from_request_parts(
123 parts: &mut Parts,
124 ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send;
125}
126
127/// A body extractor that may be absent (`Option<Json<T>>` is `None` without
128/// a `Content-Type`).
129pub trait OptionalFromRequest<M = via::ViaRequest>: Sized + Send {
130 /// What a failed extraction answers.
131 type Rejection: IntoResponse;
132
133 /// Reads the extractor, `None` when the request does not carry it.
134 fn from_request(
135 request: Request,
136 ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send;
137}
138
139impl FromRequest for Request {
140 type Rejection = Infallible;
141
142 async fn from_request(request: Request) -> Result<Self, Infallible> {
143 Ok(request)
144 }
145}
146
147impl FromRequest for crate::body::Body {
148 type Rejection = Infallible;
149
150 async fn from_request(request: Request) -> Result<Self, Infallible> {
151 Ok(request.into_body())
152 }
153}
154
155impl<T: OptionalFromRequestParts> FromRequestParts for Option<T> {
156 type Rejection = T::Rejection;
157
158 async fn from_request_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
159 T::from_request_parts(parts).await
160 }
161}
162
163impl<T: OptionalFromRequest> FromRequest for Option<T> {
164 type Rejection = T::Rejection;
165
166 async fn from_request(request: Request) -> Result<Self, Self::Rejection> {
167 T::from_request(request).await
168 }
169}
170
171impl<T> FromRequestParts for Result<T, T::Rejection>
172where
173 T: FromRequestParts,
174 T::Rejection: Send,
175{
176 type Rejection = Infallible;
177
178 async fn from_request_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
179 Ok(T::from_request_parts(parts).await)
180 }
181}
182
183impl<T> FromRequest for Result<T, T::Rejection>
184where
185 T: FromRequest,
186 T::Rejection: Send,
187{
188 type Rejection = Infallible;
189
190 async fn from_request(request: Request) -> Result<Self, Self::Rejection> {
191 Ok(T::from_request(request).await)
192 }
193}
194
195/// Markers for [`FromRequest`]'s `M`; they only steer type inference.
196pub mod via {
197 /// A body extractor ([`FromRequest`](super::FromRequest) itself).
198 #[derive(Debug)]
199 pub enum ViaRequest {}
200
201 /// A head extractor used as the last argument.
202 #[derive(Debug)]
203 pub enum ViaParts {}
204}