1 use super::Handler;
2 use crate::response::Response;
3 use http::Request;
4 use std::{
5 convert::Infallible,
6 fmt,
7 marker::PhantomData,
8 task::{Context, Poll},
9 };
10 use tower_service::Service;
11
12 pub(crate) struct IntoServiceStateInExtension<H, T, S, B> {
13 handler: H,
14 _marker: PhantomData<fn() -> (T, S, B)>,
15 }
16
17 #[test]
traits()18 fn traits() {
19 use crate::test_helpers::*;
20 assert_send::<IntoServiceStateInExtension<(), NotSendSync, (), NotSendSync>>();
21 assert_sync::<IntoServiceStateInExtension<(), NotSendSync, (), NotSendSync>>();
22 }
23
24 impl<H, T, S, B> IntoServiceStateInExtension<H, T, S, B> {
new(handler: H) -> Self25 pub(crate) fn new(handler: H) -> Self {
26 Self {
27 handler,
28 _marker: PhantomData,
29 }
30 }
31 }
32
33 impl<H, T, S, B> fmt::Debug for IntoServiceStateInExtension<H, T, S, B> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 f.debug_struct("IntoServiceStateInExtension")
36 .finish_non_exhaustive()
37 }
38 }
39
40 impl<H, T, S, B> Clone for IntoServiceStateInExtension<H, T, S, B>
41 where
42 H: Clone,
43 {
clone(&self) -> Self44 fn clone(&self) -> Self {
45 Self {
46 handler: self.handler.clone(),
47 _marker: PhantomData,
48 }
49 }
50 }
51
52 impl<H, T, S, B> Service<Request<B>> for IntoServiceStateInExtension<H, T, S, B>
53 where
54 H: Handler<T, S, B> + Clone + Send + 'static,
55 B: Send + 'static,
56 S: Send + Sync + 'static,
57 {
58 type Response = Response;
59 type Error = Infallible;
60 type Future = super::future::IntoServiceFuture<H::Future>;
61
62 #[inline]
poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>63 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
64 // `IntoServiceStateInExtension` can only be constructed from async functions which are always ready, or
65 // from `Layered` which buffers in `<Layered as Handler>::call` and is therefore
66 // also always ready.
67 Poll::Ready(Ok(()))
68 }
69
call(&mut self, mut req: Request<B>) -> Self::Future70 fn call(&mut self, mut req: Request<B>) -> Self::Future {
71 use futures_util::future::FutureExt;
72
73 let state = req
74 .extensions_mut()
75 .remove::<S>()
76 .expect("state extension missing. This is a bug in axum, please file an issue");
77
78 let handler = self.handler.clone();
79 let future = Handler::call(handler, req, state);
80 let future = future.map(Ok as _);
81
82 super::future::IntoServiceFuture::new(future)
83 }
84 }
85