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
//! Conditionally dispatch requests to the inner service based on the result of
//! a predicate.
//!
//! Unlike [filter](https://docs.rs/tower/latest/tower/filter/index.html) mod in
//! tower, this let you return a custom [`response`](http::response::Response) to user when the request is rejected.
//!
//! # Example
//!```
//! # use axum::routing::{get, Router};
//! # use axum::response::IntoResponse;
//! # use axum::body::Body;
//! # use axum::headers::{authorization::Basic, Authorization, HeaderMapExt};
//! # use axum_help::filter::FilterExLayer;
//! # use http::{Request, StatusCode};
//! #
//! # fn main() {
//!     Router::new()
//!         .route("/get", get(|| async { "get works" }))
//!         .layer(FilterExLayer::new(|request: Request<Body>| {
//!             if let Some(_auth) = request.headers().typed_get::<Authorization<Basic>>() {
//!                 // TODO: do something
//!                 Ok(request)
//!            } else {
//!                Err(StatusCode::UNAUTHORIZED.into_response())
//!            }
//!         }));
//! # }
//!```
//!
use future::{AsyncResponseFuture, ResponseFuture};
use http::{Request, Response};
pub use layer::{AsyncFilterExLayer, FilterExLayer};
pub use predicate::{AsyncPredicate, Predicate};
use std::{
    marker::PhantomData,
    task::{Context, Poll},
};
use tower::{util::Either, Service};

mod future;
mod layer;
mod predicate;

/// Conditionally dispatch requests to the inner service based on a [predicate].
///
/// [predicate]: Predicate
#[derive(Debug)]
pub struct FilterEx<T, U, B> {
    inner: T,
    predicate: U,
    p: PhantomData<B>,
}

impl<T: Clone, U: Clone, B> Clone for FilterEx<T, U, B> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            predicate: self.predicate.clone(),
            p: PhantomData,
        }
    }
}

impl<T, U, B> FilterEx<T, U, B> {
    /// Returns a new [FilterEx] service wrapping `inner`
    pub fn new(inner: T, predicate: U) -> Self {
        Self {
            inner,
            predicate,
            p: PhantomData,
        }
    }

    /// Returns a new [Layer](tower::Layer) that wraps services with a [FilterEx] service
    /// with the given [Predicate]
    ///
    pub fn layer(predicate: U) -> FilterExLayer<U, B> {
        FilterExLayer::new(predicate)
    }

    /// Check a `Request` value against thie filter's predicate
    pub fn check<R>(&mut self, request: R) -> Result<U::Request, U::Response>
    where
        U: Predicate<R, B>,
    {
        self.predicate.check(request)
    }

    /// Get a reference to the inner service
    pub fn get_ref(&self) -> &T {
        &self.inner
    }

    /// Get a mutable reference to the inner service
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    /// Consume `self`, returning the inner service
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T, U, ReqBody, ResBody> Service<Request<ReqBody>> for FilterEx<T, U, ResBody>
where
    T: Service<U::Request, Response = Response<ResBody>>,
    U: Predicate<Request<ReqBody>, ResBody, Response = Response<ResBody>>,
{
    type Response = T::Response;
    type Error = T::Error;
    type Future = ResponseFuture<T::Future, ResBody>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        match self.predicate.check(req) {
            Ok(req) => ResponseFuture::Future {
                future: self.inner.call(req),
            },
            Err(response) => ResponseFuture::Error {
                response: Some(response),
            },
        }
    }
}

/// Conditionally dispatch requests to the inner service based on an
/// asynchronous [predicate](AsyncPredicate)
///
#[derive(Debug)]
pub struct AsyncFilterEx<T, U, B> {
    inner: T,
    predicate: U,
    p: PhantomData<B>,
}

impl<T, U, B> AsyncFilterEx<T, U, B> {
    /// Returns a new [AsyncFilterEx] service wrapping `inner`.
    pub fn new(inner: T, predicate: U) -> Self {
        Self {
            inner,
            predicate,
            p: PhantomData,
        }
    }

    /// Returns a new [Layer](tower::Layer) that wraps services with a [AsyncFilterEx] service
    /// with the given [AsyncPredicate]
    ///
    pub fn layer(predicate: U) -> AsyncFilterExLayer<U, B> {
        AsyncFilterExLayer::new(predicate)
    }

    /// Check a `Request` value against thie filter's predicate
    pub async fn check<R>(&mut self, request: R) -> Result<U::Request, U::Response>
    where
        U: AsyncPredicate<R, B>,
    {
        self.predicate.check(request).await
    }

    /// Get a reference to the inner service
    pub fn get_ref(&self) -> &T {
        &self.inner
    }

    /// Get a mutable reference to the inner service
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    /// Consume `self`, returning the inner service
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T, U, ReqBody, ResBody> Service<Request<ReqBody>> for AsyncFilterEx<T, U, ResBody>
where
    T: Service<U::Request, Response = Response<ResBody>> + Clone,
    U: AsyncPredicate<Request<ReqBody>, ResBody, Response = Response<ResBody>>,
{
    type Response = T::Response;
    type Error = Either<U::Response, T::Error>;
    type Future = AsyncResponseFuture<U, T, Request<ReqBody>, ResBody>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx).map_err(|e| Either::B(e))
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        use std::mem;

        let inner = self.inner.clone();
        // In case the inner service has state that's driven to readiness and
        // not tracked by clones (such as `Buffer`), pass the version we have
        // already called `poll_ready` on into the future, and leave its clone
        // behind.
        let inner = mem::replace(&mut self.inner, inner);

        // Check the request
        let check = self.predicate.check(req);

        AsyncResponseFuture::new(check, inner)
    }
}