actix / actix-extras
Showing 18 of 34 files from the diff.

@@ -118,16 +118,14 @@
Loading
118 118
    }
119 119
}
120 120
121 -
impl<S, B, T, F, O> Transform<S> for HttpAuthentication<T, F>
121 +
impl<S, B, T, F, O> Transform<S, ServiceRequest> for HttpAuthentication<T, F>
122 122
where
123 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
124 -
        + 'static,
123 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
125 124
    S::Future: 'static,
126 125
    F: Fn(ServiceRequest, T) -> O + 'static,
127 126
    O: Future<Output = Result<ServiceRequest, Error>> + 'static,
128 127
    T: AuthExtractor + 'static,
129 128
{
130 -
    type Request = ServiceRequest;
131 129
    type Response = ServiceResponse<B>;
132 130
    type Error = Error;
133 131
    type Transform = AuthenticationMiddleware<S, F, T>;
@@ -153,25 +151,23 @@
Loading
153 151
    _extractor: PhantomData<T>,
154 152
}
155 153
156 -
impl<S, B, F, T, O> Service for AuthenticationMiddleware<S, F, T>
154 +
impl<S, B, F, T, O> Service<ServiceRequest> for AuthenticationMiddleware<S, F, T>
157 155
where
158 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
159 -
        + 'static,
156 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
160 157
    S::Future: 'static,
161 158
    F: Fn(ServiceRequest, T) -> O + 'static,
162 159
    O: Future<Output = Result<ServiceRequest, Error>> + 'static,
163 160
    T: AuthExtractor + 'static,
164 161
{
165 -
    type Request = ServiceRequest;
166 162
    type Response = ServiceResponse<B>;
167 163
    type Error = S::Error;
168 164
    type Future = LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>>;
169 165
170 -
    fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
166 +
    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
171 167
        self.service.borrow_mut().poll_ready(ctx)
172 168
    }
173 169
174 -
    fn call(&mut self, req: Self::Request) -> Self::Future {
170 +
    fn call(&self, req: ServiceRequest) -> Self::Future {
175 171
        let process_fn = Arc::clone(&self.process_fn);
176 172
177 173
        let service = Rc::clone(&self.service);
@@ -251,15 +247,14 @@
Loading
251 247
    use actix_service::{into_service, Service};
252 248
    use actix_web::error;
253 249
    use actix_web::test::TestRequest;
254 -
    use futures_util::join;
255 250
256 251
    /// This is a test for https://github.com/actix/actix-extras/issues/10
257 252
    #[actix_rt::test]
258 253
    async fn test_middleware_panic() {
259 -
        let mut middleware = AuthenticationMiddleware {
254 +
        let middleware = AuthenticationMiddleware {
260 255
            service: Rc::new(RefCell::new(into_service(
261 256
                |_: ServiceRequest| async move {
262 -
                    actix_rt::time::delay_for(std::time::Duration::from_secs(1)).await;
257 +
                    actix_rt::time::sleep(std::time::Duration::from_secs(1)).await;
263 258
                    Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
264 259
                },
265 260
            ))),
@@ -267,22 +262,24 @@
Loading
267 262
            _extractor: PhantomData,
268 263
        };
269 264
270 -
        let req = TestRequest::with_header("Authorization", "Bearer 1").to_srv_request();
265 +
        let req = TestRequest::get()
266 +
            .append_header(("Authorization", "Bearer 1"))
267 +
            .to_srv_request();
271 268
272 -
        let f = middleware.call(req);
269 +
        let f = middleware.call(req).await;
273 270
274 -
        let res = futures_util::future::lazy(|cx| middleware.poll_ready(cx));
271 +
        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
275 272
276 -
        assert!(join!(f, res).0.is_err());
273 +
        assert!(f.is_err());
277 274
    }
278 275
279 276
    /// This is a test for https://github.com/actix/actix-extras/issues/10
280 277
    #[actix_rt::test]
281 278
    async fn test_middleware_panic_several_orders() {
282 -
        let mut middleware = AuthenticationMiddleware {
279 +
        let middleware = AuthenticationMiddleware {
283 280
            service: Rc::new(RefCell::new(into_service(
284 281
                |_: ServiceRequest| async move {
285 -
                    actix_rt::time::delay_for(std::time::Duration::from_secs(1)).await;
282 +
                    actix_rt::time::sleep(std::time::Duration::from_secs(1)).await;
286 283
                    Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
287 284
                },
288 285
            ))),
@@ -290,24 +287,28 @@
Loading
290 287
            _extractor: PhantomData,
291 288
        };
292 289
293 -
        let req = TestRequest::with_header("Authorization", "Bearer 1").to_srv_request();
290 +
        let req = TestRequest::get()
291 +
            .append_header(("Authorization", "Bearer 1"))
292 +
            .to_srv_request();
294 293
295 -
        let f1 = middleware.call(req);
294 +
        let f1 = middleware.call(req).await;
296 295
297 -
        let req = TestRequest::with_header("Authorization", "Bearer 1").to_srv_request();
296 +
        let req = TestRequest::get()
297 +
            .append_header(("Authorization", "Bearer 1"))
298 +
            .to_srv_request();
298 299
299 -
        let f2 = middleware.call(req);
300 +
        let f2 = middleware.call(req).await;
300 301
301 -
        let req = TestRequest::with_header("Authorization", "Bearer 1").to_srv_request();
302 +
        let req = TestRequest::get()
303 +
            .append_header(("Authorization", "Bearer 1"))
304 +
            .to_srv_request();
302 305
303 -
        let f3 = middleware.call(req);
306 +
        let f3 = middleware.call(req).await;
304 307
305 -
        let res = futures_util::future::lazy(|cx| middleware.poll_ready(cx));
308 +
        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
306 309
307 -
        let result = join!(f1, f2, f3, res);
308 -
309 -
        assert!(result.0.is_err());
310 -
        assert!(result.1.is_err());
311 -
        assert!(result.2.is_err());
310 +
        assert!(f1.is_err());
311 +
        assert!(f2.is_err());
312 +
        assert!(f3.is_err());
312 313
    }
313 314
}

@@ -54,7 +54,7 @@
Loading
54 54
    fn error_response(&self) -> HttpResponse {
55 55
        HttpResponse::build(self.status_code)
56 56
            // TODO: Get rid of the `.clone()`
57 -
            .set(WwwAuthenticate(self.challenge.clone()))
57 +
            .insert_header(WwwAuthenticate(self.challenge.clone()))
58 58
            .finish()
59 59
    }
60 60

@@ -1,150 +1,98 @@
Loading
1 1
use std::collections::VecDeque;
2 -
use std::io;
2 +
use std::net::SocketAddr;
3 3
4 -
use actix::actors::resolver::{Connect, Resolver};
5 -
use actix::prelude::*;
6 -
use actix_utils::oneshot;
7 -
use backoff::backoff::Backoff;
8 -
use backoff::ExponentialBackoff;
9 -
use futures_util::FutureExt;
10 -
use log::{error, info, warn};
11 -
use redis_async::error::Error as RespError;
12 -
use redis_async::resp::{RespCodec, RespValue};
13 -
use tokio::io::{split, WriteHalf};
14 -
use tokio::net::TcpStream;
15 -
use tokio_util::codec::FramedRead;
4 +
use redis_async::client::{paired_connect, PairedConnection};
5 +
use redis_async::resp::RespValue;
6 +
use tokio::sync::Mutex;
7 +
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
8 +
use trust_dns_resolver::TokioAsyncResolver as AsyncResolver;
16 9
17 10
use crate::Error;
18 11
19 -
/// Command for send data to Redis
20 -
#[derive(Debug)]
21 -
pub struct Command(pub RespValue);
22 -
23 -
impl Message for Command {
24 -
    type Result = Result<RespValue, Error>;
25 -
}
26 -
27 -
/// Redis comminucation actor
28 -
pub struct RedisActor {
12 +
pub struct RedisClient {
29 13
    addr: String,
30 -
    backoff: ExponentialBackoff,
31 -
    cell: Option<actix::io::FramedWrite<RespValue, WriteHalf<TcpStream>, RespCodec>>,
32 -
    queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
14 +
    connection: Mutex<Option<PairedConnection>>,
33 15
}
34 16
35 -
impl RedisActor {
36 -
    /// Start new `Supervisor` with `RedisActor`.
37 -
    pub fn start<S: Into<String>>(addr: S) -> Addr<RedisActor> {
38 -
        let addr = addr.into();
39 -
40 -
        let backoff = ExponentialBackoff {
41 -
            max_elapsed_time: None,
42 -
            ..Default::default()
43 -
        };
44 -
45 -
        Supervisor::start(|_| RedisActor {
46 -
            addr,
47 -
            cell: None,
48 -
            backoff,
49 -
            queue: VecDeque::new(),
50 -
        })
17 +
impl RedisClient {
18 +
    pub fn new(addr: impl Into<String>) -> Self {
19 +
        Self {
20 +
            addr: addr.into(),
21 +
            connection: Mutex::new(None),
22 +
        }
51 23
    }
52 -
}
53 -
54 -
impl Actor for RedisActor {
55 -
    type Context = Context<Self>;
56 -
57 -
    fn started(&mut self, ctx: &mut Context<Self>) {
58 -
        Resolver::from_registry()
59 -
            .send(Connect::host(self.addr.as_str()))
60 -
            .into_actor(self)
61 -
            .map(|res, act, ctx| match res {
62 -
                Ok(res) => match res {
63 -
                    Ok(stream) => {
64 -
                        info!("Connected to redis server: {}", act.addr);
65 -
66 -
                        let (r, w) = split(stream);
67 24
68 -
                        // configure write side of the connection
69 -
                        let framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
70 -
                        act.cell = Some(framed);
71 -
72 -
                        // read side of the connection
73 -
                        ctx.add_stream(FramedRead::new(r, RespCodec));
25 +
    async fn get_connection(&self) -> Result<PairedConnection, Error> {
26 +
        let mut connection = self.connection.lock().await;
27 +
        if let Some(ref connection) = *connection {
28 +
            return Ok(connection.clone());
29 +
        }
74 30
75 -
                        act.backoff.reset();
76 -
                    }
77 -
                    Err(err) => {
78 -
                        error!("Can not connect to redis server: {}", err);
79 -
                        // re-connect with backoff time.
80 -
                        // we stop current context, supervisor will restart it.
81 -
                        if let Some(timeout) = act.backoff.next_backoff() {
82 -
                            ctx.run_later(timeout, |_, ctx| ctx.stop());
83 -
                        }
84 -
                    }
85 -
                },
86 -
                Err(err) => {
87 -
                    error!("Can not connect to redis server: {}", err);
88 -
                    // re-connect with backoff time.
89 -
                    // we stop current context, supervisor will restart it.
90 -
                    if let Some(timeout) = act.backoff.next_backoff() {
91 -
                        ctx.run_later(timeout, |_, ctx| ctx.stop());
92 -
                    }
31 +
        let mut addrs = resolve(&self.addr).await?;
32 +
        loop {
33 +
            // try to connect
34 +
            let socket_addr = addrs.pop_front().ok_or_else(|| {
35 +
                log::warn!("Cannot connect to {}.", self.addr);
36 +
                Error::NotConnected
37 +
            })?;
38 +
            match paired_connect(socket_addr).await {
39 +
                Ok(conn) => {
40 +
                    *connection = Some(conn.clone());
41 +
                    return Ok(conn);
93 42
                }
94 -
            })
95 -
            .wait(ctx);
96 -
    }
97 -
}
98 -
99 -
impl Supervised for RedisActor {
100 -
    fn restarting(&mut self, _: &mut Self::Context) {
101 -
        self.cell.take();
102 -
        for tx in self.queue.drain(..) {
103 -
            let _ = tx.send(Err(Error::Disconnected));
43 +
                Err(err) => log::warn!(
44 +
                    "Attempt to connect to {} as {} failed: {}.",
45 +
                    self.addr,
46 +
                    socket_addr,
47 +
                    err
48 +
                ),
49 +
            }
104 50
        }
105 51
    }
106 -
}
107 52
108 -
impl actix::io::WriteHandler<io::Error> for RedisActor {
109 -
    fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
110 -
        warn!("Redis connection dropped: {} error: {}", self.addr, err);
111 -
        Running::Stop
53 +
    pub async fn send(&self, req: RespValue) -> Result<RespValue, Error> {
54 +
        let res = self.get_connection().await?.send(req).await?;
55 +
        Ok(res)
112 56
    }
113 57
}
114 58
115 -
impl StreamHandler<Result<RespValue, RespError>> for RedisActor {
116 -
    fn handle(&mut self, msg: Result<RespValue, RespError>, ctx: &mut Self::Context) {
117 -
        match msg {
118 -
            Err(e) => {
119 -
                if let Some(tx) = self.queue.pop_front() {
120 -
                    let _ = tx.send(Err(e.into()));
121 -
                }
122 -
                ctx.stop();
123 -
            }
124 -
            Ok(val) => {
125 -
                if let Some(tx) = self.queue.pop_front() {
126 -
                    let _ = tx.send(Ok(val));
127 -
                }
128 -
            }
129 -
        }
130 -
    }
59 +
fn parse_addr(addr: &str, default_port: u16) -> Option<(&str, u16)> {
60 +
    // split the string by ':' and convert the second part to u16
61 +
    let mut parts_iter = addr.splitn(2, ':');
62 +
    let host = parts_iter.next()?;
63 +
    let port_str = parts_iter.next().unwrap_or("");
64 +
    let port: u16 = port_str.parse().unwrap_or(default_port);
65 +
    Some((host, port))
131 66
}
132 67
133 -
impl Handler<Command> for RedisActor {
134 -
    type Result = ResponseFuture<Result<RespValue, Error>>;
68 +
async fn resolve(addr: &str) -> Result<VecDeque<SocketAddr>, Error> {
69 +
    // try to parse as a regular SocketAddr first
70 +
    if let Ok(addr) = addr.parse::<SocketAddr>() {
71 +
        let mut addrs = VecDeque::new();
72 +
        addrs.push_back(addr);
73 +
        return Ok(addrs);
74 +
    }
135 75
136 -
    fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
137 -
        let (tx, rx) = oneshot::channel();
138 -
        if let Some(ref mut cell) = self.cell {
139 -
            self.queue.push_back(tx);
140 -
            cell.write(msg.0);
141 -
        } else {
142 -
            let _ = tx.send(Err(Error::NotConnected));
143 -
        }
76 +
    let (host, port) = parse_addr(addr, 6379).ok_or(Error::InvalidAddress)?;
144 77
145 -
        Box::pin(rx.map(|res| match res {
146 -
            Ok(res) => res,
147 -
            Err(_) => Err(Error::Disconnected),
148 -
        }))
149 -
    }
78 +
    // we need to do dns resolution
79 +
    let resolver = AsyncResolver::tokio_from_system_conf()
80 +
        .or_else(|err| {
81 +
            log::warn!("Cannot create system DNS resolver: {}", err);
82 +
            AsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default())
83 +
        })
84 +
        .map_err(|err| {
85 +
            log::error!("Cannot create DNS resolver: {}", err);
86 +
            Error::ResolveError
87 +
        })?;
88 +
89 +
    let addrs = resolver
90 +
        .lookup_ip(host)
91 +
        .await
92 +
        .map_err(|_| Error::ResolveError)?
93 +
        .into_iter()
94 +
        .map(|ip| SocketAddr::new(ip, port))
95 +
        .collect();
96 +
97 +
    Ok(addrs)
150 98
}

@@ -91,8 +91,8 @@
Loading
91 91
impl<S: Scheme> IntoHeaderValue for Authorization<S> {
92 92
    type Error = <S as IntoHeaderValue>::Error;
93 93
94 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
95 -
        self.0.try_into()
94 +
    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
95 +
        self.0.try_into_value()
96 96
    }
97 97
}
98 98

@@ -1,42 +1,31 @@
Loading
1 1
#[macro_use]
2 2
extern crate redis_async;
3 3
4 -
use actix_redis::{Command, Error, RedisActor, RespValue};
4 +
use actix_redis::{Error, RedisClient, RespValue};
5 5
6 6
#[actix_rt::test]
7 7
async fn test_error_connect() {
8 -
    let addr = RedisActor::start("localhost:54000");
9 -
    let _addr2 = addr.clone();
8 +
    let addr = RedisClient::new("localhost:54000");
10 9
11 -
    let res = addr.send(Command(resp_array!["GET", "test"])).await;
10 +
    let res = addr.send(resp_array!["GET", "test"]).await;
12 11
    match res {
13 -
        Ok(Err(Error::NotConnected)) => (),
12 +
        Err(Error::NotConnected) => (),
14 13
        _ => panic!("Should not happen {:?}", res),
15 14
    }
16 15
}
17 16
18 17
#[actix_rt::test]
19 -
async fn test_redis() {
18 +
async fn test_redis() -> Result<(), Error> {
20 19
    env_logger::init();
21 20
22 -
    let addr = RedisActor::start("127.0.0.1:6379");
23 -
    let res = addr
24 -
        .send(Command(resp_array!["SET", "test", "value"]))
25 -
        .await;
21 +
    let addr = RedisClient::new("127.0.0.1:6379");
26 22
27 -
    match res {
28 -
        Ok(Ok(resp)) => {
29 -
            assert_eq!(resp, RespValue::SimpleString("OK".to_owned()));
30 -
31 -
            let res = addr.send(Command(resp_array!["GET", "test"])).await;
32 -
            match res {
33 -
                Ok(Ok(resp)) => {
34 -
                    println!("RESP: {:?}", resp);
35 -
                    assert_eq!(resp, RespValue::BulkString((&b"value"[..]).into()));
36 -
                }
37 -
                _ => panic!("Should not happen {:?}", res),
38 -
            }
39 -
        }
40 -
        _ => panic!("Should not happen {:?}", res),
41 -
    }
23 +
    let resp = addr.send(resp_array!["SET", "test", "value"]).await?;
24 +
25 +
    assert_eq!(resp, RespValue::SimpleString("OK".to_owned()));
26 +
27 +
    let resp = addr.send(resp_array!["GET", "test"]).await?;
28 +
    println!("RESP: {:?}", resp);
29 +
    assert_eq!(resp, RespValue::BulkString((&b"value"[..]).into()));
30 +
    Ok(())
42 31
}

@@ -27,7 +27,7 @@
Loading
27 27
impl<C: Challenge> IntoHeaderValue for WwwAuthenticate<C> {
28 28
    type Error = <C as IntoHeaderValue>::Error;
29 29
30 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
31 -
        self.0.try_into()
30 +
    fn try_into_value(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
31 +
        self.0.try_into_value()
32 32
    }
33 33
}

@@ -235,8 +235,8 @@
Loading
235 235
            .unwrap();
236 236
237 237
        let req = TestRequest::get()
238 -
            .header(header::ORIGIN, "https://www.unknown.com")
239 -
            .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "DNT")
238 +
            .insert_header((header::ORIGIN, "https://www.unknown.com"))
239 +
            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "DNT"))
240 240
            .to_srv_request();
241 241
242 242
        assert!(cors.inner.validate_origin(req.head()).is_err());
@@ -257,34 +257,37 @@
Loading
257 257
            .await
258 258
            .unwrap();
259 259
260 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
260 +
        let req = TestRequest::default()
261 261
            .method(Method::OPTIONS)
262 -
            .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed")
262 +
            .insert_header(("Origin", "https://www.example.com"))
263 +
            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed"))
263 264
            .to_srv_request();
264 265
265 266
        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
266 267
        assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
267 -
        let resp = test::call_service(&mut cors, req).await;
268 +
        let resp = test::call_service(&cors, req).await;
268 269
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
269 270
270 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
271 -
            .header(header::ACCESS_CONTROL_REQUEST_METHOD, "put")
271 +
        let req = TestRequest::default()
272 272
            .method(Method::OPTIONS)
273 +
            .insert_header(("Origin", "https://www.example.com"))
274 +
            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "put"))
273 275
            .to_srv_request();
274 276
275 277
        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
276 278
        assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
277 279
278 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
279 -
            .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
280 -
            .header(
280 +
        let req = TestRequest::default()
281 +
            .method(Method::OPTIONS)
282 +
            .insert_header(("Origin", "https://www.example.com"))
283 +
            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
284 +
            .insert_header((
281 285
                header::ACCESS_CONTROL_REQUEST_HEADERS,
282 286
                "AUTHORIZATION,ACCEPT",
283 -
            )
284 -
            .method(Method::OPTIONS)
287 +
            ))
285 288
            .to_srv_request();
286 289
287 -
        let resp = test::call_service(&mut cors, req).await;
290 +
        let resp = test::call_service(&cors, req).await;
288 291
        assert_eq!(
289 292
            Some(&b"*"[..]),
290 293
            resp.headers()
@@ -319,16 +322,17 @@
Loading
319 322
320 323
        Rc::get_mut(&mut cors.inner).unwrap().preflight = false;
321 324
322 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
323 -
            .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
324 -
            .header(
325 +
        let req = TestRequest::default()
326 +
            .method(Method::OPTIONS)
327 +
            .insert_header(("Origin", "https://www.example.com"))
328 +
            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
329 +
            .insert_header((
325 330
                header::ACCESS_CONTROL_REQUEST_HEADERS,
326 331
                "AUTHORIZATION,ACCEPT",
327 -
            )
328 -
            .method(Method::OPTIONS)
332 +
            ))
329 333
            .to_srv_request();
330 334
331 -
        let resp = test::call_service(&mut cors, req).await;
335 +
        let resp = test::call_service(&cors, req).await;
332 336
        assert_eq!(resp.status(), StatusCode::OK);
333 337
    }
334 338
}

@@ -223,15 +223,13 @@
Loading
223 223
    }
224 224
}
225 225
226 -
impl<S, T, B> Transform<S> for IdentityService<T>
226 +
impl<S, T, B> Transform<S, ServiceRequest> for IdentityService<T>
227 227
where
228 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
229 -
        + 'static,
228 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
230 229
    S::Future: 'static,
231 230
    T: IdentityPolicy,
232 231
    B: 'static,
233 232
{
234 -
    type Request = ServiceRequest;
235 233
    type Response = ServiceResponse<B>;
236 234
    type Error = Error;
237 235
    type InitError = ();
@@ -261,24 +259,22 @@
Loading
261 259
    }
262 260
}
263 261
264 -
impl<S, T, B> Service for IdentityServiceMiddleware<S, T>
262 +
impl<S, T, B> Service<ServiceRequest> for IdentityServiceMiddleware<S, T>
265 263
where
266 264
    B: 'static,
267 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
268 -
        + 'static,
265 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
269 266
    S::Future: 'static,
270 267
    T: IdentityPolicy,
271 268
{
272 -
    type Request = ServiceRequest;
273 269
    type Response = ServiceResponse<B>;
274 270
    type Error = Error;
275 271
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
276 272
277 -
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
273 +
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
278 274
        self.service.borrow_mut().poll_ready(cx)
279 275
    }
280 276
281 -
    fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
277 +
    fn call(&self, mut req: ServiceRequest) -> Self::Future {
282 278
        let srv = self.service.clone();
283 279
        let backend = self.backend.clone();
284 280
        let fut = self.backend.from_request(&mut req);
@@ -637,7 +633,7 @@
Loading
637 633
638 634
    #[actix_rt::test]
639 635
    async fn test_identity() {
640 -
        let mut srv = test::init_service(
636 +
        let srv = test::init_service(
641 637
            App::new()
642 638
                .wrap(IdentityService::new(
643 639
                    CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
@@ -668,18 +664,16 @@
Loading
668 664
        )
669 665
        .await;
670 666
        let resp =
671 -
            test::call_service(&mut srv, TestRequest::with_uri("/index").to_request())
672 -
                .await;
667 +
            test::call_service(&srv, TestRequest::with_uri("/index").to_request()).await;
673 668
        assert_eq!(resp.status(), StatusCode::OK);
674 669
675 670
        let resp =
676 -
            test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
677 -
                .await;
671 +
            test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
678 672
        assert_eq!(resp.status(), StatusCode::OK);
679 673
        let c = resp.response().cookies().next().unwrap().to_owned();
680 674
681 675
        let resp = test::call_service(
682 -
            &mut srv,
676 +
            &srv,
683 677
            TestRequest::with_uri("/index")
684 678
                .cookie(c.clone())
685 679
                .to_request(),
@@ -688,7 +682,7 @@
Loading
688 682
        assert_eq!(resp.status(), StatusCode::CREATED);
689 683
690 684
        let resp = test::call_service(
691 -
            &mut srv,
685 +
            &srv,
692 686
            TestRequest::with_uri("/logout")
693 687
                .cookie(c.clone())
694 688
                .to_request(),
@@ -701,7 +695,7 @@
Loading
701 695
    #[actix_rt::test]
702 696
    async fn test_identity_max_age_time() {
703 697
        let duration = Duration::days(1);
704 -
        let mut srv = test::init_service(
698 +
        let srv = test::init_service(
705 699
            App::new()
706 700
                .wrap(IdentityService::new(
707 701
                    CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
@@ -718,8 +712,7 @@
Loading
718 712
        )
719 713
        .await;
720 714
        let resp =
721 -
            test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
722 -
                .await;
715 +
            test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
723 716
        assert_eq!(resp.status(), StatusCode::OK);
724 717
        assert!(resp.headers().contains_key(header::SET_COOKIE));
725 718
        let c = resp.response().cookies().next().unwrap().to_owned();
@@ -728,7 +721,7 @@
Loading
728 721
729 722
    #[actix_rt::test]
730 723
    async fn test_http_only_same_site() {
731 -
        let mut srv = test::init_service(
724 +
        let srv = test::init_service(
732 725
            App::new()
733 726
                .wrap(IdentityService::new(
734 727
                    CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
@@ -746,8 +739,7 @@
Loading
746 739
        .await;
747 740
748 741
        let resp =
749 -
            test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
750 -
                .await;
742 +
            test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
751 743
752 744
        assert_eq!(resp.status(), StatusCode::OK);
753 745
        assert!(resp.headers().contains_key(header::SET_COOKIE));
@@ -760,7 +752,7 @@
Loading
760 752
    #[actix_rt::test]
761 753
    async fn test_identity_max_age() {
762 754
        let seconds = 60;
763 -
        let mut srv = test::init_service(
755 +
        let srv = test::init_service(
764 756
            App::new()
765 757
                .wrap(IdentityService::new(
766 758
                    CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
@@ -777,8 +769,7 @@
Loading
777 769
        )
778 770
        .await;
779 771
        let resp =
780 -
            test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
781 -
                .await;
772 +
            test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
782 773
        assert_eq!(resp.status(), StatusCode::OK);
783 774
        assert!(resp.headers().contains_key(header::SET_COOKIE));
784 775
        let c = resp.response().cookies().next().unwrap().to_owned();
@@ -790,7 +781,7 @@
Loading
790 781
    >(
791 782
        f: F,
792 783
    ) -> impl actix_service::Service<
793 -
        Request = actix_http::Request,
784 +
        actix_http::Request,
794 785
        Response = ServiceResponse<actix_web::body::Body>,
795 786
        Error = Error,
796 787
    > {
@@ -925,19 +916,19 @@
Loading
925 916
926 917
    #[actix_rt::test]
927 918
    async fn test_identity_legacy_cookie_is_set() {
928 -
        let mut srv = create_identity_server(|c| c).await;
919 +
        let srv = create_identity_server(|c| c).await;
929 920
        let mut resp =
930 -
            test::call_service(&mut srv, TestRequest::with_uri("/").to_request()).await;
921 +
            test::call_service(&srv, TestRequest::with_uri("/").to_request()).await;
931 922
        assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN);
932 923
        assert_logged_in(resp, None).await;
933 924
    }
934 925
935 926
    #[actix_rt::test]
936 927
    async fn test_identity_legacy_cookie_works() {
937 -
        let mut srv = create_identity_server(|c| c).await;
928 +
        let srv = create_identity_server(|c| c).await;
938 929
        let cookie = legacy_login_cookie(COOKIE_LOGIN);
939 930
        let mut resp = test::call_service(
940 -
            &mut srv,
931 +
            &srv,
941 932
            TestRequest::with_uri("/")
942 933
                .cookie(cookie.clone())
943 934
                .to_request(),
@@ -949,11 +940,10 @@
Loading
949 940
950 941
    #[actix_rt::test]
951 942
    async fn test_identity_legacy_cookie_rejected_if_visit_timestamp_needed() {
952 -
        let mut srv =
953 -
            create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
943 +
        let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
954 944
        let cookie = legacy_login_cookie(COOKIE_LOGIN);
955 945
        let mut resp = test::call_service(
956 -
            &mut srv,
946 +
            &srv,
957 947
            TestRequest::with_uri("/")
958 948
                .cookie(cookie.clone())
959 949
                .to_request(),
@@ -970,11 +960,10 @@
Loading
970 960
971 961
    #[actix_rt::test]
972 962
    async fn test_identity_legacy_cookie_rejected_if_login_timestamp_needed() {
973 -
        let mut srv =
974 -
            create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
963 +
        let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
975 964
        let cookie = legacy_login_cookie(COOKIE_LOGIN);
976 965
        let mut resp = test::call_service(
977 -
            &mut srv,
966 +
            &srv,
978 967
            TestRequest::with_uri("/")
979 968
                .cookie(cookie.clone())
980 969
                .to_request(),
@@ -991,11 +980,10 @@
Loading
991 980
992 981
    #[actix_rt::test]
993 982
    async fn test_identity_cookie_rejected_if_login_timestamp_needed() {
994 -
        let mut srv =
995 -
            create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
983 +
        let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
996 984
        let cookie = login_cookie(COOKIE_LOGIN, None, Some(SystemTime::now()));
997 985
        let mut resp = test::call_service(
998 -
            &mut srv,
986 +
            &srv,
999 987
            TestRequest::with_uri("/")
1000 988
                .cookie(cookie.clone())
1001 989
                .to_request(),
@@ -1012,11 +1000,10 @@
Loading
1012 1000
1013 1001
    #[actix_rt::test]
1014 1002
    async fn test_identity_cookie_rejected_if_visit_timestamp_needed() {
1015 -
        let mut srv =
1016 -
            create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
1003 +
        let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
1017 1004
        let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
1018 1005
        let mut resp = test::call_service(
1019 -
            &mut srv,
1006 +
            &srv,
1020 1007
            TestRequest::with_uri("/")
1021 1008
                .cookie(cookie.clone())
1022 1009
                .to_request(),
@@ -1033,15 +1020,14 @@
Loading
1033 1020
1034 1021
    #[actix_rt::test]
1035 1022
    async fn test_identity_cookie_rejected_if_login_timestamp_too_old() {
1036 -
        let mut srv =
1037 -
            create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
1023 +
        let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
1038 1024
        let cookie = login_cookie(
1039 1025
            COOKIE_LOGIN,
1040 1026
            Some(SystemTime::now() - Duration::days(180)),
1041 1027
            None,
1042 1028
        );
1043 1029
        let mut resp = test::call_service(
1044 -
            &mut srv,
1030 +
            &srv,
1045 1031
            TestRequest::with_uri("/")
1046 1032
                .cookie(cookie.clone())
1047 1033
                .to_request(),
@@ -1058,15 +1044,14 @@
Loading
1058 1044
1059 1045
    #[actix_rt::test]
1060 1046
    async fn test_identity_cookie_rejected_if_visit_timestamp_too_old() {
1061 -
        let mut srv =
1062 -
            create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
1047 +
        let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
1063 1048
        let cookie = login_cookie(
1064 1049
            COOKIE_LOGIN,
1065 1050
            None,
1066 1051
            Some(SystemTime::now() - Duration::days(180)),
1067 1052
        );
1068 1053
        let mut resp = test::call_service(
1069 -
            &mut srv,
1054 +
            &srv,
1070 1055
            TestRequest::with_uri("/")
1071 1056
                .cookie(cookie.clone())
1072 1057
                .to_request(),
@@ -1083,11 +1068,10 @@
Loading
1083 1068
1084 1069
    #[actix_rt::test]
1085 1070
    async fn test_identity_cookie_not_updated_on_login_deadline() {
1086 -
        let mut srv =
1087 -
            create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
1071 +
        let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
1088 1072
        let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
1089 1073
        let mut resp = test::call_service(
1090 -
            &mut srv,
1074 +
            &srv,
1091 1075
            TestRequest::with_uri("/")
1092 1076
                .cookie(cookie.clone())
1093 1077
                .to_request(),
@@ -1100,7 +1084,7 @@
Loading
1100 1084
    // https://github.com/actix/actix-web/issues/1263
1101 1085
    #[actix_rt::test]
1102 1086
    async fn test_identity_cookie_updated_on_visit_deadline() {
1103 -
        let mut srv = create_identity_server(|c| {
1087 +
        let srv = create_identity_server(|c| {
1104 1088
            c.visit_deadline(Duration::days(90))
1105 1089
                .login_deadline(Duration::days(90))
1106 1090
        })
@@ -1108,7 +1092,7 @@
Loading
1108 1092
        let timestamp = SystemTime::now() - Duration::days(1);
1109 1093
        let cookie = login_cookie(COOKIE_LOGIN, Some(timestamp), Some(timestamp));
1110 1094
        let mut resp = test::call_service(
1111 -
            &mut srv,
1095 +
            &srv,
1112 1096
            TestRequest::with_uri("/")
1113 1097
                .cookie(cookie.clone())
1114 1098
                .to_request(),
@@ -1146,22 +1130,22 @@
Loading
1146 1130
            }
1147 1131
        }
1148 1132
1149 -
        let mut srv = IdentityServiceMiddleware {
1133 +
        let srv = IdentityServiceMiddleware {
1150 1134
            backend: Rc::new(Ident),
1151 1135
            service: Rc::new(RefCell::new(into_service(
1152 1136
                |_: ServiceRequest| async move {
1153 -
                    actix_rt::time::delay_for(std::time::Duration::from_secs(100)).await;
1137 +
                    actix_rt::time::sleep(std::time::Duration::from_secs(100)).await;
1154 1138
                    Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
1155 1139
                },
1156 1140
            ))),
1157 1141
        };
1158 1142
1159 -
        let mut srv2 = srv.clone();
1143 +
        let srv2 = srv.clone();
1160 1144
        let req = TestRequest::default().to_srv_request();
1161 1145
        actix_rt::spawn(async move {
1162 1146
            let _ = srv2.call(req).await;
1163 1147
        });
1164 -
        actix_rt::time::delay_for(std::time::Duration::from_millis(50)).await;
1148 +
        actix_rt::time::sleep(std::time::Duration::from_millis(50)).await;
1165 1149
1166 1150
        let _ = lazy(|cx| srv.poll_ready(cx)).await;
1167 1151
    }

@@ -25,7 +25,7 @@
Loading
25 25
///     let challenge = Basic::with_realm("Restricted area");
26 26
///
27 27
///     HttpResponse::Unauthorized()
28 -
///         .set(WwwAuthenticate(challenge))
28 +
///         .insert_header(WwwAuthenticate(challenge))
29 29
///         .finish()
30 30
/// }
31 31
/// ```
@@ -106,7 +106,7 @@
Loading
106 106
impl IntoHeaderValue for Basic {
107 107
    type Error = InvalidHeaderValue;
108 108
109 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
109 +
    fn try_into_value(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
110 110
        HeaderValue::from_maybe_shared(self.to_bytes())
111 111
    }
112 112
}
@@ -120,7 +120,7 @@
Loading
120 120
    fn test_plain_into_header_value() {
121 121
        let challenge = Basic { realm: None };
122 122
123 -
        let value = challenge.try_into();
123 +
        let value = challenge.try_into_value();
124 124
        assert!(value.is_ok());
125 125
        let value = value.unwrap();
126 126
        assert_eq!(value, "Basic");
@@ -132,7 +132,7 @@
Loading
132 132
            realm: Some("Restricted area".into()),
133 133
        };
134 134
135 -
        let value = challenge.try_into();
135 +
        let value = challenge.try_into_value();
136 136
        assert!(value.is_ok());
137 137
        let value = value.unwrap();
138 138
        assert_eq!(value, "Basic realm=\"Restricted area\"");

@@ -97,7 +97,7 @@
Loading
97 97
impl IntoHeaderValue for Basic {
98 98
    type Error = InvalidHeaderValue;
99 99
100 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
100 +
    fn try_into_value(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
101 101
        let mut credentials = BytesMut::with_capacity(
102 102
            self.user_id.len()
103 103
                + 1 // ':'
@@ -187,7 +187,7 @@
Loading
187 187
            password: Some("open sesame".into()),
188 188
        };
189 189
190 -
        let result = basic.try_into();
190 +
        let result = basic.try_into_value();
191 191
        assert!(result.is_ok());
192 192
        assert_eq!(
193 193
            result.unwrap(),

@@ -76,7 +76,7 @@
Loading
76 76
impl IntoHeaderValue for Bearer {
77 77
    type Error = InvalidHeaderValue;
78 78
79 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
79 +
    fn try_into_value(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
80 80
        let mut buffer = BytesMut::with_capacity(7 + self.token.len());
81 81
        buffer.put(&b"Bearer "[..]);
82 82
        buffer.extend_from_slice(self.token.as_bytes());
@@ -128,7 +128,7 @@
Loading
128 128
    fn test_into_header_value() {
129 129
        let bearer = Bearer::new("mF_9.B5f-4.1JqM");
130 130
131 -
        let result = bearer.try_into();
131 +
        let result = bearer.try_into_value();
132 132
        assert!(result.is_ok());
133 133
        assert_eq!(
134 134
            result.unwrap(),

@@ -145,7 +145,7 @@
Loading
145 145
            match TryInto::<Uri>::try_into(origin) {
146 146
                Ok(_) if origin == "*" => {
147 147
                    error!("Wildcard in `allowed_origin` is not allowed. Use `send_wildcard`.");
148 -
                    self.error = Some(Either::B(CorsError::WildcardOrigin));
148 +
                    self.error = Some(Either::Right(CorsError::WildcardOrigin));
149 149
                }
150 150
151 151
                Ok(_) => {
@@ -162,7 +162,7 @@
Loading
162 162
                }
163 163
164 164
                Err(err) => {
165 -
                    self.error = Some(Either::A(err.into()));
165 +
                    self.error = Some(Either::Left(err.into()));
166 166
                }
167 167
            }
168 168
        }
@@ -224,7 +224,7 @@
Loading
224 224
                    }
225 225
226 226
                    Err(err) => {
227 -
                        self.error = Some(Either::A(err.into()));
227 +
                        self.error = Some(Either::Left(err.into()));
228 228
                        break;
229 229
                    }
230 230
                }
@@ -266,7 +266,7 @@
Loading
266 266
                    }
267 267
                }
268 268
269 -
                Err(err) => self.error = Some(Either::A(err.into())),
269 +
                Err(err) => self.error = Some(Either::Left(err.into())),
270 270
            }
271 271
        }
272 272
@@ -303,7 +303,7 @@
Loading
303 303
                        }
304 304
                    }
305 305
                    Err(err) => {
306 -
                        self.error = Some(Either::A(err.into()));
306 +
                        self.error = Some(Either::Left(err.into()));
307 307
                        break;
308 308
                    }
309 309
                }
@@ -351,7 +351,7 @@
Loading
351 351
                    }
352 352
                }
353 353
                Err(err) => {
354 -
                    self.error = Some(Either::A(err.into()));
354 +
                    self.error = Some(Either::Left(err.into()));
355 355
                    break;
356 356
                }
357 357
            }
@@ -483,13 +483,12 @@
Loading
483 483
    }
484 484
}
485 485
486 -
impl<S, B> Transform<S> for Cors
486 +
impl<S, B> Transform<S, ServiceRequest> for Cors
487 487
where
488 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
488 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
489 489
    S::Future: 'static,
490 490
    B: 'static,
491 491
{
492 -
    type Request = ServiceRequest;
493 492
    type Response = ServiceResponse<B>;
494 493
    type Error = Error;
495 494
    type InitError = ();
@@ -499,8 +498,8 @@
Loading
499 498
    fn new_transform(&self, service: S) -> Self::Future {
500 499
        if let Some(ref err) = self.error {
501 500
            match err {
502 -
                Either::A(err) => error!("{}", err),
503 -
                Either::B(err) => error!("{}", err),
501 +
                Either::Left(err) => error!("{}", err),
502 +
                Either::Right(err) => error!("{}", err),
504 503
            }
505 504
506 505
            return future::err(());
@@ -592,15 +591,16 @@
Loading
592 591
593 592
    #[actix_rt::test]
594 593
    async fn restrictive_defaults() {
595 -
        let mut cors = Cors::default()
594 +
        let cors = Cors::default()
596 595
            .new_transform(test::ok_service())
597 596
            .await
598 597
            .unwrap();
599 598
600 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
599 +
        let req = TestRequest::default()
600 +
            .insert_header(("Origin", "https://www.example.com"))
601 601
            .to_srv_request();
602 602
603 -
        let resp = test::call_service(&mut cors, req).await;
603 +
        let resp = test::call_service(&cors, req).await;
604 604
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
605 605
    }
606 606

@@ -31,7 +31,7 @@
Loading
31 31
///         .finish();
32 32
///
33 33
///     HttpResponse::Unauthorized()
34 -
///         .set(WwwAuthenticate(challenge))
34 +
///         .insert_header(WwwAuthenticate(challenge))
35 35
///         .finish()
36 36
/// }
37 37
/// ```
@@ -133,7 +133,7 @@
Loading
133 133
impl IntoHeaderValue for Bearer {
134 134
    type Error = InvalidHeaderValue;
135 135
136 -
    fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
136 +
    fn try_into_value(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
137 137
        HeaderValue::from_maybe_shared(self.to_bytes())
138 138
    }
139 139
}

@@ -26,7 +26,7 @@
Loading
26 26
27 27
#[actix_rt::test]
28 28
async fn test_not_allowed_origin_fn() {
29 -
    let mut cors = Cors::default()
29 +
    let cors = Cors::default()
30 30
        .allowed_origin("https://www.example.com")
31 31
        .allowed_origin_fn(|origin, req| {
32 32
            assert_eq!(&origin, req.headers.get(header::ORIGIN).unwrap());
@@ -42,11 +42,11 @@
Loading
42 42
        .unwrap();
43 43
44 44
    {
45 -
        let req = TestRequest::with_header("Origin", "https://www.example.com")
46 -
            .method(Method::GET)
45 +
        let req = TestRequest::get()
46 +
            .insert_header(("Origin", "https://www.example.com"))
47 47
            .to_srv_request();
48 48
49 -
        let resp = test::call_service(&mut cors, req).await;
49 +
        let resp = test::call_service(&cors, req).await;
50 50
51 51
        assert_eq!(
52 52
            Some(&b"https://www.example.com"[..]),
@@ -57,11 +57,11 @@
Loading
57 57
    }
58 58
59 59
    {
60 -
        let req = TestRequest::with_header("Origin", "https://www.known.com")
61 -
            .method(Method::GET)
60 +
        let req = TestRequest::get()
61 +
            .insert_header(("Origin", "https://www.known.com"))
62 62
            .to_srv_request();
63 63
64 -
        let resp = test::call_service(&mut cors, req).await;
64 +
        let resp = test::call_service(&cors, req).await;
65 65
66 66
        assert_eq!(
67 67
            None,
@@ -72,7 +72,7 @@
Loading
72 72
73 73
#[actix_rt::test]
74 74
async fn test_allowed_origin_fn() {
75 -
    let mut cors = Cors::default()
75 +
    let cors = Cors::default()
76 76
        .allowed_origin("https://www.example.com")
77 77
        .allowed_origin_fn(|origin, req| {
78 78
            assert_eq!(&origin, req.headers.get(header::ORIGIN).unwrap());
@@ -87,11 +87,11 @@
Loading
87 87
        .await
88 88
        .unwrap();
89 89
90 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
91 -
        .method(Method::GET)
90 +
    let req = TestRequest::get()
91 +
        .insert_header(("Origin", "https://www.example.com"))
92 92
        .to_srv_request();
93 93
94 -
    let resp = test::call_service(&mut cors, req).await;
94 +
    let resp = test::call_service(&cors, req).await;
95 95
96 96
    assert_eq!(
97 97
        "https://www.example.com",
@@ -101,11 +101,11 @@
Loading
101 101
            .unwrap()
102 102
    );
103 103
104 -
    let req = TestRequest::with_header("Origin", "https://www.unknown.com")
105 -
        .method(Method::GET)
104 +
    let req = TestRequest::get()
105 +
        .insert_header(("Origin", "https://www.unknown.com"))
106 106
        .to_srv_request();
107 107
108 -
    let resp = test::call_service(&mut cors, req).await;
108 +
    let resp = test::call_service(&cors, req).await;
109 109
110 110
    assert_eq!(
111 111
        Some(&b"https://www.unknown.com"[..]),
@@ -119,7 +119,7 @@
Loading
119 119
async fn test_allowed_origin_fn_with_environment() {
120 120
    let regex = Regex::new("https:.+\\.unknown\\.com").unwrap();
121 121
122 -
    let mut cors = Cors::default()
122 +
    let cors = Cors::default()
123 123
        .allowed_origin("https://www.example.com")
124 124
        .allowed_origin_fn(move |origin, req| {
125 125
            assert_eq!(&origin, req.headers.get(header::ORIGIN).unwrap());
@@ -134,11 +134,11 @@
Loading
134 134
        .await
135 135
        .unwrap();
136 136
137 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
138 -
        .method(Method::GET)
137 +
    let req = TestRequest::get()
138 +
        .insert_header(("Origin", "https://www.example.com"))
139 139
        .to_srv_request();
140 140
141 -
    let resp = test::call_service(&mut cors, req).await;
141 +
    let resp = test::call_service(&cors, req).await;
142 142
143 143
    assert_eq!(
144 144
        "https://www.example.com",
@@ -148,11 +148,11 @@
Loading
148 148
            .unwrap()
149 149
    );
150 150
151 -
    let req = TestRequest::with_header("Origin", "https://www.unknown.com")
152 -
        .method(Method::GET)
151 +
    let req = TestRequest::get()
152 +
        .insert_header(("Origin", "https://www.unknown.com"))
153 153
        .to_srv_request();
154 154
155 -
    let resp = test::call_service(&mut cors, req).await;
155 +
    let resp = test::call_service(&cors, req).await;
156 156
157 157
    assert_eq!(
158 158
        Some(&b"https://www.unknown.com"[..]),
@@ -164,7 +164,7 @@
Loading
164 164
165 165
#[actix_rt::test]
166 166
async fn test_multiple_origins_preflight() {
167 -
    let mut cors = Cors::default()
167 +
    let cors = Cors::default()
168 168
        .allowed_origin("https://example.com")
169 169
        .allowed_origin("https://example.org")
170 170
        .allowed_methods(vec![Method::GET])
@@ -172,12 +172,13 @@
Loading
172 172
        .await
173 173
        .unwrap();
174 174
175 -
    let req = TestRequest::with_header("Origin", "https://example.com")
176 -
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "GET")
175 +
    let req = TestRequest::default()
176 +
        .insert_header(("Origin", "https://example.com"))
177 +
        .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "GET"))
177 178
        .method(Method::OPTIONS)
178 179
        .to_srv_request();
179 180
180 -
    let resp = test::call_service(&mut cors, req).await;
181 +
    let resp = test::call_service(&cors, req).await;
181 182
    assert_eq!(
182 183
        Some(&b"https://example.com"[..]),
183 184
        resp.headers()
@@ -185,12 +186,13 @@
Loading
185 186
            .map(HeaderValue::as_bytes)
186 187
    );
187 188
188 -
    let req = TestRequest::with_header("Origin", "https://example.org")
189 -
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "GET")
189 +
    let req = TestRequest::default()
190 +
        .insert_header(("Origin", "https://example.org"))
191 +
        .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "GET"))
190 192
        .method(Method::OPTIONS)
191 193
        .to_srv_request();
192 194
193 -
    let resp = test::call_service(&mut cors, req).await;
195 +
    let resp = test::call_service(&cors, req).await;
194 196
    assert_eq!(
195 197
        Some(&b"https://example.org"[..]),
196 198
        resp.headers()
@@ -201,7 +203,7 @@
Loading
201 203
202 204
#[actix_rt::test]
203 205
async fn test_multiple_origins() {
204 -
    let mut cors = Cors::default()
206 +
    let cors = Cors::default()
205 207
        .allowed_origin("https://example.com")
206 208
        .allowed_origin("https://example.org")
207 209
        .allowed_methods(vec![Method::GET])
@@ -209,11 +211,11 @@
Loading
209 211
        .await
210 212
        .unwrap();
211 213
212 -
    let req = TestRequest::with_header("Origin", "https://example.com")
213 -
        .method(Method::GET)
214 +
    let req = TestRequest::get()
215 +
        .insert_header(("Origin", "https://example.com"))
214 216
        .to_srv_request();
215 217
216 -
    let resp = test::call_service(&mut cors, req).await;
218 +
    let resp = test::call_service(&cors, req).await;
217 219
    assert_eq!(
218 220
        Some(&b"https://example.com"[..]),
219 221
        resp.headers()
@@ -221,11 +223,11 @@
Loading
221 223
            .map(HeaderValue::as_bytes)
222 224
    );
223 225
224 -
    let req = TestRequest::with_header("Origin", "https://example.org")
225 -
        .method(Method::GET)
226 +
    let req = TestRequest::get()
227 +
        .insert_header(("Origin", "https://example.org"))
226 228
        .to_srv_request();
227 229
228 -
    let resp = test::call_service(&mut cors, req).await;
230 +
    let resp = test::call_service(&cors, req).await;
229 231
    assert_eq!(
230 232
        Some(&b"https://example.org"[..]),
231 233
        resp.headers()
@@ -237,7 +239,7 @@
Loading
237 239
#[actix_rt::test]
238 240
async fn test_response() {
239 241
    let exposed_headers = vec![header::AUTHORIZATION, header::ACCEPT];
240 -
    let mut cors = Cors::default()
242 +
    let cors = Cors::default()
241 243
        .allow_any_origin()
242 244
        .send_wildcard()
243 245
        .disable_preflight()
@@ -250,10 +252,11 @@
Loading
250 252
        .await
251 253
        .unwrap();
252 254
253 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
255 +
    let req = TestRequest::default()
256 +
        .insert_header(("Origin", "https://www.example.com"))
254 257
        .method(Method::OPTIONS)
255 258
        .to_srv_request();
256 -
    let resp = test::call_service(&mut cors, req).await;
259 +
    let resp = test::call_service(&cors, req).await;
257 260
    assert_eq!(
258 261
        Some(&b"*"[..]),
259 262
        resp.headers()
@@ -283,7 +286,7 @@
Loading
283 286
    }
284 287
285 288
    let exposed_headers = vec![header::AUTHORIZATION, header::ACCEPT];
286 -
    let mut cors = Cors::default()
289 +
    let cors = Cors::default()
287 290
        .allow_any_origin()
288 291
        .send_wildcard()
289 292
        .disable_preflight()
@@ -294,22 +297,25 @@
Loading
294 297
        .allowed_header(header::CONTENT_TYPE)
295 298
        .new_transform(fn_service(|req: ServiceRequest| {
296 299
            ok(req.into_response({
297 -
                HttpResponse::Ok().header(header::VARY, "Accept").finish()
300 +
                HttpResponse::Ok()
301 +
                    .insert_header((header::VARY, "Accept"))
302 +
                    .finish()
298 303
            }))
299 304
        }))
300 305
        .await
301 306
        .unwrap();
302 307
303 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
308 +
    let req = TestRequest::default()
309 +
        .insert_header(("Origin", "https://www.example.com"))
304 310
        .method(Method::OPTIONS)
305 311
        .to_srv_request();
306 -
    let resp = test::call_service(&mut cors, req).await;
312 +
    let resp = test::call_service(&cors, req).await;
307 313
    assert_eq!(
308 314
        Some(&b"Accept, Origin"[..]),
309 315
        resp.headers().get(header::VARY).map(HeaderValue::as_bytes)
310 316
    );
311 317
312 -
    let mut cors = Cors::default()
318 +
    let cors = Cors::default()
313 319
        .disable_vary_header()
314 320
        .allowed_methods(vec!["POST"])
315 321
        .allowed_origin("https://www.example.com")
@@ -318,11 +324,12 @@
Loading
318 324
        .await
319 325
        .unwrap();
320 326
321 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
327 +
    let req = TestRequest::default()
328 +
        .insert_header(("Origin", "https://www.example.com"))
322 329
        .method(Method::OPTIONS)
323 -
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
330 +
        .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
324 331
        .to_srv_request();
325 -
    let resp = test::call_service(&mut cors, req).await;
332 +
    let resp = test::call_service(&cors, req).await;
326 333
    let origins_str = resp
327 334
        .headers()
328 335
        .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
@@ -332,39 +339,40 @@
Loading
332 339
333 340
#[actix_rt::test]
334 341
async fn test_validate_origin() {
335 -
    let mut cors = Cors::default()
342 +
    let cors = Cors::default()
336 343
        .allowed_origin("https://www.example.com")
337 344
        .new_transform(test::ok_service())
338 345
        .await
339 346
        .unwrap();
340 347
341 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
342 -
        .method(Method::GET)
348 +
    let req = TestRequest::get()
349 +
        .insert_header(("Origin", "https://www.example.com"))
343 350
        .to_srv_request();
344 351
345 -
    let resp = test::call_service(&mut cors, req).await;
352 +
    let resp = test::call_service(&cors, req).await;
346 353
    assert_eq!(resp.status(), StatusCode::OK);
347 354
}
348 355
349 356
#[actix_rt::test]
350 357
async fn test_no_origin_response() {
351 -
    let mut cors = Cors::permissive()
358 +
    let cors = Cors::permissive()
352 359
        .disable_preflight()
353 360
        .new_transform(test::ok_service())
354 361
        .await
355 362
        .unwrap();
356 363
357 364
    let req = TestRequest::default().method(Method::GET).to_srv_request();
358 -
    let resp = test::call_service(&mut cors, req).await;
365 +
    let resp = test::call_service(&cors, req).await;
359 366
    assert!(resp
360 367
        .headers()
361 368
        .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
362 369
        .is_none());
363 370
364 -
    let req = TestRequest::with_header("Origin", "https://www.example.com")
371 +
    let req = TestRequest::default()
372 +
        .insert_header(("Origin", "https://www.example.com"))
365 373
        .method(Method::OPTIONS)
366 374
        .to_srv_request();
367 -
    let resp = test::call_service(&mut cors, req).await;
375 +
    let resp = test::call_service(&cors, req).await;
368 376
    assert_eq!(
369 377
        Some(&b"https://www.example.com"[..]),
370 378
        resp.headers()
@@ -375,21 +383,22 @@
Loading
375 383
376 384
#[actix_rt::test]
377 385
async fn validate_origin_allows_all_origins() {
378 -
    let mut cors = Cors::permissive()
386 +
    let cors = Cors::permissive()
379 387
        .new_transform(test::ok_service())
380 388
        .await
381 389
        .unwrap();
382 390
383 -
    let req =
384 -
        TestRequest::with_header("Origin", "https://www.example.com").to_srv_request();
391 +
    let req = TestRequest::default()
392 +
        .insert_header(("Origin", "https://www.example.com"))
393 +
        .to_srv_request();
385 394
386 -
    let resp = test::call_service(&mut cors, req).await;
395 +
    let resp = test::call_service(&cors, req).await;
387 396
    assert_eq!(resp.status(), StatusCode::OK);
388 397
}
389 398
390 399
#[actix_rt::test]
391 400
async fn test_allow_any_origin_any_method_any_header() {
392 -
    let mut cors = Cors::default()
401 +
    let cors = Cors::default()
393 402
        .allow_any_origin()
394 403
        .allow_any_method()
395 404
        .allow_any_header()
@@ -397,12 +406,13 @@
Loading
397 406
        .await
398 407
        .unwrap();
399 408
400 -
    let req = TestRequest::with_header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
401 -
        .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type")
402 -
        .header(header::ORIGIN, "https://www.example.com")
409 +
    let req = TestRequest::default()
410 +
        .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
411 +
        .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type"))
412 +
        .insert_header((header::ORIGIN, "https://www.example.com"))
403 413
        .method(Method::OPTIONS)
404 414
        .to_srv_request();
405 415
406 -
    let resp = test::call_service(&mut cors, req).await;
416 +
    let resp = test::call_service(&cors, req).await;
407 417
    assert_eq!(resp.status(), StatusCode::OK);
408 418
}

@@ -17,7 +17,7 @@
Loading
17 17
use actix_web::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
18 18
use actix_web::web::BytesMut;
19 19
use actix_web::{FromRequest, HttpMessage, HttpRequest, HttpResponse, Responder};
20 -
use futures_util::future::{ready, FutureExt, LocalBoxFuture, Ready};
20 +
use futures_util::future::{FutureExt, LocalBoxFuture};
21 21
use futures_util::StreamExt;
22 22
23 23
#[derive(Debug, Display)]
@@ -137,21 +137,16 @@
Loading
137 137
}
138 138
139 139
impl<T: Message + Default> Responder for ProtoBuf<T> {
140 -
    type Error = Error;
141 -
    type Future = Ready<Result<HttpResponse, Error>>;
142 -
143 -
    fn respond_to(self, _: &HttpRequest) -> Self::Future {
140 +
    fn respond_to(self, _: &HttpRequest) -> HttpResponse {
144 141
        let mut buf = Vec::new();
145 -
        ready(
146 -
            self.0
147 -
                .encode(&mut buf)
148 -
                .map_err(|e| Error::from(ProtoBufPayloadError::Serialize(e)))
149 -
                .map(|()| {
150 -
                    HttpResponse::Ok()
151 -
                        .content_type("application/protobuf")
152 -
                        .body(buf)
153 -
                }),
154 -
        )
142 +
        match self.0.encode(&mut buf) {
143 +
            Ok(()) => HttpResponse::Ok()
144 +
                .content_type("application/protobuf")
145 +
                .body(buf),
146 +
            Err(err) => HttpResponse::from_error(Error::from(
147 +
                ProtoBufPayloadError::Serialize(err),
148 +
            )),
149 +
        }
155 150
    }
156 151
}
157 152
@@ -255,7 +250,7 @@
Loading
255 250
256 251
impl ProtoBufResponseBuilder for HttpResponseBuilder {
257 252
    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
258 -
        self.header(CONTENT_TYPE, "application/protobuf");
253 +
        self.append_header((CONTENT_TYPE, "application/protobuf"));
259 254
260 255
        let mut body = Vec::new();
261 256
        value
@@ -313,16 +308,16 @@
Loading
313 308
        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
314 309
        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
315 310
316 -
        let (req, mut pl) =
317 -
            TestRequest::with_header(header::CONTENT_TYPE, "application/text")
318 -
                .to_http_parts();
311 +
        let (req, mut pl) = TestRequest::get()
312 +
            .append_header((header::CONTENT_TYPE, "application/text"))
313 +
            .to_http_parts();
319 314
        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
320 315
        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
321 316
322 -
        let (req, mut pl) =
323 -
            TestRequest::with_header(header::CONTENT_TYPE, "application/protobuf")
324 -
                .header(header::CONTENT_LENGTH, "10000")
325 -
                .to_http_parts();
317 +
        let (req, mut pl) = TestRequest::get()
318 +
            .append_header((header::CONTENT_TYPE, "application/protobuf"))
319 +
            .append_header((header::CONTENT_LENGTH, "10000"))
320 +
            .to_http_parts();
326 321
        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl)
327 322
            .limit(100)
328 323
            .await;

@@ -9,7 +9,7 @@
Loading
9 9
use actix_web::dev::{ServiceRequest, ServiceResponse};
10 10
use actix_web::http::{header::SET_COOKIE, HeaderValue};
11 11
use actix_web::{Error, HttpMessage, ResponseError};
12 -
use derive_more::{Display, From};
12 +
use derive_more::Display;
13 13
use futures_util::future::{ok, FutureExt, LocalBoxFuture, Ready};
14 14
use serde_json::error::Error as JsonError;
15 15
use time::{Duration, OffsetDateTime};
@@ -17,7 +17,7 @@
Loading
17 17
use crate::{Session, SessionStatus};
18 18
19 19
/// Errors that can occur during handling cookie session
20 -
#[derive(Debug, From, Display)]
20 +
#[derive(Debug, Display)]
21 21
pub enum CookieSessionError {
22 22
    /// Size of the serialized session is greater than 4000 bytes.
23 23
    #[display(fmt = "Size of the serialized session is greater than 4000 bytes.")]
@@ -290,13 +290,12 @@
Loading
290 290
    }
291 291
}
292 292
293 -
impl<S, B: 'static> Transform<S> for CookieSession
293 +
impl<S, B: 'static> Transform<S, ServiceRequest> for CookieSession
294 294
where
295 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
295 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>>,
296 296
    S::Future: 'static,
297 297
    S::Error: 'static,
298 298
{
299 -
    type Request = ServiceRequest;
300 299
    type Response = ServiceResponse<B>;
301 300
    type Error = S::Error;
302 301
    type InitError = ();
@@ -317,18 +316,17 @@
Loading
317 316
    inner: Rc<CookieSessionInner>,
318 317
}
319 318
320 -
impl<S, B: 'static> Service for CookieSessionMiddleware<S>
319 +
impl<S, B: 'static> Service<ServiceRequest> for CookieSessionMiddleware<S>
321 320
where
322 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
321 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>>,
323 322
    S::Future: 'static,
324 323
    S::Error: 'static,
325 324
{
326 -
    type Request = ServiceRequest;
327 325
    type Response = ServiceResponse<B>;
328 326
    type Error = S::Error;
329 327
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
330 328
331 -
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
329 +
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
332 330
        self.service.poll_ready(cx)
333 331
    }
334 332
@@ -337,7 +335,7 @@
Loading
337 335
    /// session state changes, then set-cookie is returned in response.  As
338 336
    /// a user logs out, call session.purge() to set SessionStatus accordingly
339 337
    /// and this will trigger removal of the session cookie in the response.
340 -
    fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
338 +
    fn call(&self, mut req: ServiceRequest) -> Self::Future {
341 339
        let inner = self.inner.clone();
342 340
        let (is_new, state) = self.inner.load(&req);
343 341
        let prolong_expiration = self.inner.expires_in.is_some();
@@ -387,7 +385,7 @@
Loading
387 385
388 386
    #[actix_rt::test]
389 387
    async fn cookie_session() {
390 -
        let mut app = test::init_service(
388 +
        let app = test::init_service(
391 389
            App::new()
392 390
                .wrap(CookieSession::signed(&[0; 32]).secure(false))
393 391
                .service(web::resource("/").to(|ses: Session| async move {
@@ -407,7 +405,7 @@
Loading
407 405
408 406
    #[actix_rt::test]
409 407
    async fn private_cookie() {
410 -
        let mut app = test::init_service(
408 +
        let app = test::init_service(
411 409
            App::new()
412 410
                .wrap(CookieSession::private(&[0; 32]).secure(false))
413 411
                .service(web::resource("/").to(|ses: Session| async move {
@@ -427,7 +425,7 @@
Loading
427 425
428 426
    #[actix_rt::test]
429 427
    async fn lazy_cookie() {
430 -
        let mut app = test::init_service(
428 +
        let app = test::init_service(
431 429
            App::new()
432 430
                .wrap(CookieSession::signed(&[0; 32]).secure(false).lazy(true))
433 431
                .service(web::resource("/count").to(|ses: Session| async move {
@@ -453,7 +451,7 @@
Loading
453 451
454 452
    #[actix_rt::test]
455 453
    async fn cookie_session_extractor() {
456 -
        let mut app = test::init_service(
454 +
        let app = test::init_service(
457 455
            App::new()
458 456
                .wrap(CookieSession::signed(&[0; 32]).secure(false))
459 457
                .service(web::resource("/").to(|ses: Session| async move {
@@ -473,7 +471,7 @@
Loading
473 471
474 472
    #[actix_rt::test]
475 473
    async fn basics() {
476 -
        let mut app = test::init_service(
474 +
        let app = test::init_service(
477 475
            App::new()
478 476
                .wrap(
479 477
                    CookieSession::signed(&[0; 32])
@@ -508,13 +506,13 @@
Loading
508 506
        let request = test::TestRequest::with_uri("/test/")
509 507
            .cookie(cookie)
510 508
            .to_request();
511 -
        let body = test::read_response(&mut app, request).await;
509 +
        let body = test::read_response(&app, request).await;
512 510
        assert_eq!(body, Bytes::from_static(b"counter: 100"));
513 511
    }
514 512
515 513
    #[actix_rt::test]
516 514
    async fn prolong_expiration() {
517 -
        let mut app = test::init_service(
515 +
        let app = test::init_service(
518 516
            App::new()
519 517
                .wrap(CookieSession::signed(&[0; 32]).secure(false).expires_in(60))
520 518
                .service(web::resource("/").to(|ses: Session| async move {
@@ -538,7 +536,7 @@
Loading
538 536
            .expires()
539 537
            .expect("Expiration is set");
540 538
541 -
        actix_rt::time::delay_for(std::time::Duration::from_secs(1)).await;
539 +
        actix_rt::time::sleep(std::time::Duration::from_secs(1)).await;
542 540
543 541
        let request = test::TestRequest::with_uri("/test/").to_request();
544 542
        let response = app.call(request).await.unwrap();

@@ -3,7 +3,6 @@
Loading
3 3
use std::task::{Context, Poll};
4 4
use std::{collections::HashMap, iter, rc::Rc};
5 5
6 -
use actix::prelude::*;
7 6
use actix_service::{Service, Transform};
8 7
use actix_session::{Session, SessionStatus};
9 8
use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
@@ -16,7 +15,7 @@
Loading
16 15
use redis_async::resp_array;
17 16
use time::{self, Duration, OffsetDateTime};
18 17
19 -
use crate::redis::{Command, RedisActor};
18 +
use crate::redis::RedisClient;
20 19
21 20
/// Use redis as session storage.
22 21
///
@@ -36,7 +35,7 @@
Loading
36 35
            key: Key::derive_from(key),
37 36
            cache_keygen: Box::new(|key: &str| format!("session:{}", &key)),
38 37
            ttl: "7200".to_owned(),
39 -
            addr: RedisActor::start(addr),
38 +
            redis_client: RedisClient::new(addr),
40 39
            name: "actix-session".to_owned(),
41 40
            path: "/".to_owned(),
42 41
            domain: None,
@@ -113,14 +112,12 @@
Loading
113 112
    }
114 113
}
115 114
116 -
impl<S, B> Transform<S> for RedisSession
115 +
impl<S, B> Transform<S, ServiceRequest> for RedisSession
117 116
where
118 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
119 -
        + 'static,
117 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
120 118
    S::Future: 'static,
121 119
    B: 'static,
122 120
{
123 -
    type Request = ServiceRequest;
124 121
    type Response = ServiceResponse<B>;
125 122
    type Error = S::Error;
126 123
    type InitError = ();
@@ -141,25 +138,23 @@
Loading
141 138
    inner: Rc<Inner>,
142 139
}
143 140
144 -
impl<S, B> Service for RedisSessionMiddleware<S>
141 +
impl<S, B> Service<ServiceRequest> for RedisSessionMiddleware<S>
145 142
where
146 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
147 -
        + 'static,
143 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
148 144
    S::Future: 'static,
149 145
    B: 'static,
150 146
{
151 -
    type Request = ServiceRequest;
152 147
    type Response = ServiceResponse<B>;
153 148
    type Error = Error;
154 149
    #[allow(clippy::type_complexity)]
155 150
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
156 151
157 -
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
152 +
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
158 153
        self.service.borrow_mut().poll_ready(cx)
159 154
    }
160 155
161 -
    fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
162 -
        let mut srv = self.service.clone();
156 +
    fn call(&self, mut req: ServiceRequest) -> Self::Future {
157 +
        let srv = self.service.clone();
163 158
        let inner = self.inner.clone();
164 159
165 160
        Box::pin(async move {
@@ -215,7 +210,7 @@
Loading
215 210
    key: Key,
216 211
    cache_keygen: Box<dyn Fn(&str) -> String>,
217 212
    ttl: String,
218 -
    addr: Addr<RedisActor>,
213 +
    redis_client: RedisClient,
219 214
    name: String,
220 215
    path: String,
221 216
    domain: Option<String>,
@@ -256,13 +251,11 @@
Loading
256 251
            }
257 252
        };
258 253
259 -
        let res = self
260 -
            .addr
261 -
            .send(Command(resp_array!["GET", cache_key]))
254 +
        let val = self
255 +
            .redis_client
256 +
            .send(resp_array!["GET", cache_key])
262 257
            .await?;
263 258
264 -
        let val = res.map_err(error::ErrorInternalServerError)?;
265 -
266 259
        match val {
267 260
            RespValue::Error(err) => {
268 261
                return Err(error::ErrorInternalServerError(err));
@@ -294,6 +287,7 @@
Loading
294 287
        } else {
295 288
            let value: String = iter::repeat(())
296 289
                .map(|()| OsRng.sample(Alphanumeric))
290 +
                .map(char::from)
297 291
                .take(32)
298 292
                .collect();
299 293
@@ -331,12 +325,9 @@
Loading
331 325
            Ok(body) => body,
332 326
        };
333 327
334 -
        let cmd = Command(resp_array!["SET", cache_key, body, "EX", &self.ttl]);
335 -
336 -
        self.addr
337 -
            .send(cmd)
338 -
            .await?
339 -
            .map_err(error::ErrorInternalServerError)?;
328 +
        self.redis_client
329 +
            .send(resp_array!["SET", cache_key, body, "EX", &self.ttl])
330 +
            .await?;
340 331
341 332
        if let Some(jar) = jar {
342 333
            for cookie in jar.delta() {
@@ -352,17 +343,16 @@
Loading
352 343
    async fn clear_cache(&self, key: String) -> Result<(), Error> {
353 344
        let cache_key = (self.cache_keygen)(&key);
354 345
355 -
        match self.addr.send(Command(resp_array!["DEL", cache_key])).await {
356 -
            Err(e) => Err(Error::from(e)),
357 -
            Ok(res) => {
358 -
                match res {
359 -
                    // redis responds with number of deleted records
360 -
                    Ok(RespValue::Integer(x)) if x > 0 => Ok(()),
361 -
                    _ => Err(error::ErrorInternalServerError(
362 -
                        "failed to remove session from cache",
363 -
                    )),
364 -
                }
365 -
            }
346 +
        match self
347 +
            .redis_client
348 +
            .send(resp_array!["DEL", cache_key])
349 +
            .await?
350 +
        {
351 +
            // redis responds with number of deleted records
352 +
            RespValue::Integer(x) if x > 0 => Ok(()),
353 +
            _ => Err(error::ErrorInternalServerError(
354 +
                "failed to remove session from cache",
355 +
            )),
366 356
        }
367 357
    }
368 358
@@ -406,7 +396,7 @@
Loading
406 396
            .unwrap_or(Some(0))
407 397
            .unwrap_or(0);
408 398
409 -
        Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
399 +
        Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
410 400
    }
411 401
412 402
    async fn do_something(session: Session) -> Result<HttpResponse> {
@@ -417,7 +407,7 @@
Loading
417 407
            .map_or(1, |inner| inner + 1);
418 408
        session.set("counter", counter)?;
419 409
420 -
        Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
410 +
        Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
421 411
    }
422 412
423 413
    #[derive(Deserialize)]
@@ -438,7 +428,7 @@
Loading
438 428
            .unwrap_or(Some(0))
439 429
            .unwrap_or(0);
440 430
441 -
        Ok(HttpResponse::Ok().json(IndexResponse {
431 +
        Ok(HttpResponse::Ok().json(&IndexResponse {
442 432
            user_id: Some(id),
443 433
            counter,
444 434
        }))

@@ -42,34 +42,34 @@
Loading
42 42
        let mut res = HttpResponse::Ok();
43 43
44 44
        if let Some(origin) = inner.access_control_allow_origin(req.head()) {
45 -
            res.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
45 +
            res.insert_header((header::ACCESS_CONTROL_ALLOW_ORIGIN, origin));
46 46
        }
47 47
48 48
        if let Some(ref allowed_methods) = inner.allowed_methods_baked {
49 -
            res.header(
49 +
            res.insert_header((
50 50
                header::ACCESS_CONTROL_ALLOW_METHODS,
51 51
                allowed_methods.clone(),
52 -
            );
52 +
            ));
53 53
        }
54 54
55 55
        if let Some(ref headers) = inner.allowed_headers_baked {
56 -
            res.header(header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone());
56 +
            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
57 57
        } else if let Some(headers) =
58 58
            req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS)
59 59
        {
60 60
            // all headers allowed, return
61 -
            res.header(header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone());
61 +
            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
62 62
        }
63 63
64 64
        if inner.supports_credentials {
65 -
            res.header(
65 +
            res.insert_header((
66 66
                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
67 67
                HeaderValue::from_static("true"),
68 -
            );
68 +
            ));
69 69
        }
70 70
71 71
        if let Some(max_age) = inner.max_age {
72 -
            res.header(header::ACCESS_CONTROL_MAX_AGE, max_age.to_string());
72 +
            res.insert_header((header::ACCESS_CONTROL_MAX_AGE, max_age.to_string()));
73 73
        }
74 74
75 75
        let res = res.finish();
@@ -121,22 +121,21 @@
Loading
121 121
    LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>>,
122 122
>;
123 123
124 -
impl<S, B> Service for CorsMiddleware<S>
124 +
impl<S, B> Service<ServiceRequest> for CorsMiddleware<S>
125 125
where
126 -
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
126 +
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
127 127
    S::Future: 'static,
128 128
    B: 'static,
129 129
{
130 -
    type Request = ServiceRequest;
131 130
    type Response = ServiceResponse<B>;
132 131
    type Error = Error;
133 132
    type Future = CorsMiddlewareServiceFuture<B>;
134 133
135 -
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
134 +
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
136 135
        self.service.poll_ready(cx)
137 136
    }
138 137
139 -
    fn call(&mut self, req: ServiceRequest) -> Self::Future {
138 +
    fn call(&self, req: ServiceRequest) -> Self::Future {
140 139
        if self.inner.preflight && req.method() == Method::OPTIONS {
141 140
            let inner = Rc::clone(&self.inner);
142 141
            let res = Self::handle_preflight(&inner, req);
@@ -187,7 +186,7 @@
Loading
187 186
        // Tests case where allowed_origins is All but there are validate functions to run incase.
188 187
        // In this case, origins are only allowed when the DNT header is sent.
189 188
190 -
        let mut cors = Cors::default()
189 +
        let cors = Cors::default()
191 190
            .allow_any_origin()
192 191
            .allowed_origin_fn(|origin, req_head| {
193 192
                assert_eq!(&origin, req_head.headers.get(header::ORIGIN).unwrap());
@@ -199,7 +198,7 @@
Loading
199 198
            .unwrap();
200 199
201 200
        let req = TestRequest::get()
202 -
            .header(header::ORIGIN, "http://example.com")
201 +
            .insert_header((header::ORIGIN, "http://example.com"))
203 202
            .to_srv_request();
204 203
        let res = cors.call(req).await.unwrap();
205 204
        assert_eq!(
@@ -210,8 +209,8 @@
Loading
210 209
        );
211 210
212 211
        let req = TestRequest::get()
213 -
            .header(header::ORIGIN, "http://example.com")
214 -
            .header(header::DNT, "1")
212 +
            .insert_header((header::ORIGIN, "http://example.com"))
213 +
            .insert_header((header::DNT, "1"))
215 214
            .to_srv_request();
216 215
        let res = cors.call(req).await.unwrap();
217 216
        assert_eq!(
Files Coverage
actix-cors 91.25%
actix-redis 83.73%
actix-session/src 89.07%
actix-web-httpauth/src 61.25%
actix-identity/src/lib.rs 95.96%
actix-protobuf/src/lib.rs 50.00%
Project Totals (29 files) 82.42%
1
comment: false
2

3
ignore: # ignore codecoverage on following paths
4
  - "**/examples"
5
  - ".github"
6
  - "**/*.md"
7
  - "**/*.toml"
Sunburst
The inner-most circle is the entire project, moving away from the center are folders then, finally, a single file. The size and color of each slice is representing the number of statements and the coverage, respectively.
Icicle
The top section represents the entire project. Proceeding with folders and finally individual files. The size and color of each slice is representing the number of statements and the coverage, respectively.
Grid
Each block represents a single file in the project. The size and color of each block is represented by the number of statements and the coverage, respectively.
Loading