1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-27 10:39:03 +02:00

actix-web 0.6 compatibility

This commit is contained in:
Nikolay Kim
2018-05-08 10:12:57 -07:00
parent 2a7ffe6e0a
commit 7af09390ee
9 changed files with 161 additions and 126 deletions

View File

@ -6,12 +6,12 @@
//! * [Chat on gitter](https://gitter.im/actix/actix)
//! * Cargo package: [actix-redis](https://crates.io/crates/actix-redis)
//! * Minimum supported Rust version: 1.21 or later
//!
//!
extern crate actix;
extern crate backoff;
extern crate futures;
extern crate tokio_io;
extern crate tokio_core;
extern crate tokio_io;
#[macro_use]
extern crate log;
#[macro_use]
@ -22,34 +22,34 @@ extern crate failure;
mod redis;
pub use redis::{Command, RedisActor};
#[cfg(feature="web")]
#[cfg(feature = "web")]
extern crate actix_web;
#[cfg(feature="web")]
#[cfg(feature = "web")]
extern crate cookie;
#[cfg(feature="web")]
extern crate rand;
#[cfg(feature="web")]
#[cfg(feature = "web")]
extern crate http;
#[cfg(feature="web")]
#[cfg(feature = "web")]
extern crate rand;
#[cfg(feature = "web")]
extern crate serde;
#[cfg(feature="web")]
#[cfg(feature = "web")]
extern crate serde_json;
#[cfg(feature="web")]
#[cfg(feature = "web")]
mod session;
#[cfg(feature="web")]
#[cfg(feature = "web")]
pub use session::RedisSessionBackend;
/// General purpose actix redis error
#[derive(Fail, Debug)]
pub enum Error {
#[fail(display="Redis error {}", _0)]
#[fail(display = "Redis error {}", _0)]
Redis(redis_async::error::Error),
/// Receiving message during reconnecting
#[fail(display="Redis: Not connected")]
#[fail(display = "Redis: Not connected")]
NotConnected,
/// Cancel all waters when connection get dropped
#[fail(display="Redis: Disconnected")]
#[fail(display = "Redis: Disconnected")]
Disconnected,
}
@ -63,5 +63,5 @@ impl From<redis_async::error::Error> for Error {
}
// re-export
pub use redis_async::resp::RespValue;
pub use redis_async::error::Error as RespError;
pub use redis_async::resp::RespValue;

View File

@ -1,22 +1,21 @@
use std::io;
use std::collections::VecDeque;
use std::io;
use actix::prelude::*;
use actix::actors::{Connect, Connector};
use backoff::ExponentialBackoff;
use actix::prelude::*;
use backoff::backoff::Backoff;
use futures::Future;
use backoff::ExponentialBackoff;
use futures::unsync::oneshot;
use tokio_io::AsyncRead;
use tokio_io::io::WriteHalf;
use tokio_io::codec::FramedRead;
use tokio_core::net::TcpStream;
use futures::Future;
use redis_async::error::Error as RespError;
use redis_async::resp::{RespCodec, RespValue};
use tokio_core::net::TcpStream;
use tokio_io::codec::FramedRead;
use tokio_io::io::WriteHalf;
use tokio_io::AsyncRead;
use Error;
/// Command for send data to Redis
#[derive(Debug)]
pub struct Command(pub RespValue);
@ -38,11 +37,11 @@ impl RedisActor {
pub fn start<S: Into<String>>(addr: S) -> Addr<Unsync, RedisActor> {
let addr = addr.into();
Supervisor::start(|_| {
RedisActor { addr: addr,
cell: None,
backoff: ExponentialBackoff::default(),
queue: VecDeque::new() }
Supervisor::start(|_| RedisActor {
addr: addr,
cell: None,
backoff: ExponentialBackoff::default(),
queue: VecDeque::new(),
})
}
}
@ -51,7 +50,8 @@ impl Actor for RedisActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
Connector::from_registry().send(Connect::host(self.addr.as_str()))
Connector::from_registry()
.send(Connect::host(self.addr.as_str()))
.into_actor(self)
.map(|res, act, ctx| match res {
Ok(stream) => {
@ -67,7 +67,7 @@ impl Actor for RedisActor {
ctx.add_stream(FramedRead::new(r, RespCodec));
act.backoff.reset();
},
}
Err(err) => {
error!("Can not connect to redis server: {}", err);
// re-connect with backoff time.
@ -103,15 +103,16 @@ impl Supervised for RedisActor {
}
impl actix::io::WriteHandler<io::Error> for RedisActor {
fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
warn!("Redis connection dropped: {} error: {}", self.addr, err);
warn!(
"Redis connection dropped: {} error: {}",
self.addr, err
);
Running::Stop
}
}
impl StreamHandler<RespValue, RespError> for RedisActor {
fn error(&mut self, err: RespError, _: &mut Self::Context) -> Running {
if let Some(tx) = self.queue.pop_front() {
let _ = tx.send(Err(err.into()));
@ -138,6 +139,9 @@ impl Handler<Command> for RedisActor {
let _ = tx.send(Err(Error::NotConnected));
}
Box::new(rx.map_err(|_| Error::Disconnected).and_then(|res| res))
Box::new(
rx.map_err(|_| Error::Disconnected)
.and_then(|res| res),
)
}
}

View File

@ -1,21 +1,21 @@
use std::rc::Rc;
use std::iter::FromIterator;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::rc::Rc;
use serde_json;
use rand::{self, Rng};
use futures::Future;
use futures::future::{Either, ok as FutOk, err as FutErr};
use redis_async::resp::RespValue;
use cookie::{CookieJar, Cookie, Key};
use http::header::{self, HeaderValue};
use actix::prelude::*;
use actix_web::{error, Error, Result, HttpRequest, HttpResponse};
use actix_web::middleware::{SessionImpl, SessionBackend, Response as MiddlewareResponse};
use actix_web::middleware::session::{SessionBackend, SessionImpl};
use actix_web::middleware::Response as MiddlewareResponse;
use actix_web::{error, Error, HttpRequest, HttpResponse, Result};
use cookie::{Cookie, CookieJar, Key};
use futures::future::{err as FutErr, ok as FutOk, Either};
use futures::Future;
use http::header::{self, HeaderValue};
use rand::{self, Rng};
use redis_async::resp::RespValue;
use serde_json;
use redis::{Command, RedisActor};
/// Session that stores data in redis
pub struct RedisSession {
changed: bool,
@ -25,7 +25,6 @@ pub struct RedisSession {
}
impl SessionImpl for RedisSession {
fn get(&self, key: &str) -> Option<&str> {
self.state.get(key).map(|s| s.as_str())
}
@ -47,8 +46,11 @@ impl SessionImpl for RedisSession {
fn write(&self, resp: HttpResponse) -> Result<MiddlewareResponse> {
if self.changed {
Ok(MiddlewareResponse::Future(
self.inner.update(&self.state, resp, self.value.as_ref())))
Ok(MiddlewareResponse::Future(self.inner.update(
&self.state,
resp,
self.value.as_ref(),
)))
} else {
Ok(MiddlewareResponse::Done(resp))
}
@ -58,10 +60,11 @@ impl SessionImpl for RedisSession {
/// Use redis as session storage.
///
/// You need to pass an address of the redis server and random value to the
/// constructor of `RedisSessionBackend`. This is private key for cookie session,
/// When this value is changed, all session data is lost.
/// constructor of `RedisSessionBackend`. This is private key for cookie
/// session, When this value is changed, all session data is lost.
///
/// Note that whatever you write into your session is visible by the user (but not modifiable).
/// Note that whatever you write into your session is visible by the user (but
/// not modifiable).
///
/// Constructor panics if key length is less than 32 bytes.
pub struct RedisSessionBackend(Rc<Inner>);
@ -71,11 +74,12 @@ impl RedisSessionBackend {
///
/// * `addr` - address of the redis server
pub fn new<S: Into<String>>(addr: S, key: &[u8]) -> RedisSessionBackend {
RedisSessionBackend(
Rc::new(Inner{key: Key::from_master(key),
ttl: "7200".to_owned(),
addr: RedisActor::start(addr),
name: "actix-session".to_owned()}))
RedisSessionBackend(Rc::new(Inner {
key: Key::from_master(key),
ttl: "7200".to_owned(),
addr: RedisActor::start(addr),
name: "actix-session".to_owned(),
}))
}
/// Set time to live in seconds for session value
@ -92,9 +96,8 @@ impl RedisSessionBackend {
}
impl<S> SessionBackend<S> for RedisSessionBackend {
type Session = RedisSession;
type ReadFuture = Box<Future<Item=RedisSession, Error=Error>>;
type ReadFuture = Box<Future<Item = RedisSession, Error = Error>>;
fn from_request(&self, req: &mut HttpRequest<S>) -> Self::ReadFuture {
let inner = Rc::clone(&self.0);
@ -105,13 +108,15 @@ impl<S> SessionBackend<S> for RedisSessionBackend {
changed: false,
inner: inner,
state: state,
value: Some(value) }
value: Some(value),
}
} else {
RedisSession {
changed: false,
inner: inner,
state: HashMap::new(),
value: None }
value: None,
}
}
}))
}
@ -126,8 +131,9 @@ struct Inner {
impl Inner {
#[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
fn load<S>(&self, req: &mut HttpRequest<S>)
-> Box<Future<Item=Option<(HashMap<String, String>, String)>, Error=Error>>
fn load<S>(
&self, req: &mut HttpRequest<S>,
) -> Box<Future<Item = Option<(HashMap<String, String>, String)>, Error = Error>>
{
if let Ok(cookies) = req.cookies() {
for cookie in cookies {
@ -137,31 +143,42 @@ impl Inner {
if let Some(cookie) = jar.signed(&self.key).get(&self.name) {
let value = cookie.value().to_owned();
return Box::new(
self.addr.send(Command(resp_array!["GET", cookie.value()]))
self.addr
.send(Command(resp_array!["GET", cookie.value()]))
.map_err(Error::from)
.and_then(move |res| match res {
Ok(val) => {
match val {
RespValue::Error(err) =>
RespValue::Error(err) => {
return Err(
error::ErrorInternalServerError(err).into()),
RespValue::SimpleString(s) =>
if let Ok(val) = serde_json::from_str(&s) {
return Ok(Some((val, value)))
},
RespValue::BulkString(s) => {
if let Ok(val) = serde_json::from_slice(&s) {
return Ok(Some((val, value)))
error::ErrorInternalServerError(err)
.into(),
)
}
RespValue::SimpleString(s) => {
if let Ok(val) = serde_json::from_str(&s)
{
return Ok(Some((val, value)));
}
},
}
RespValue::BulkString(s) => {
if let Ok(val) =
serde_json::from_slice(&s)
{
return Ok(Some((val, value)));
}
}
_ => (),
}
Ok(None)
},
Err(err) => Err(error::ErrorInternalServerError(err).into())
}))
}
Err(err) => {
Err(error::ErrorInternalServerError(err).into())
}
}),
);
} else {
return Box::new(FutOk(None))
return Box::new(FutOk(None));
}
}
}
@ -169,10 +186,10 @@ impl Inner {
Box::new(FutOk(None))
}
fn update(&self, state: &HashMap<String, String>,
mut resp: HttpResponse,
value: Option<&String>) -> Box<Future<Item=HttpResponse, Error=Error>>
{
fn update(
&self, state: &HashMap<String, String>, mut resp: HttpResponse,
value: Option<&String>,
) -> Box<Future<Item = HttpResponse, Error = Error>> {
let (value, jar) = if let Some(value) = value {
(value.clone(), None)
} else {
@ -190,25 +207,28 @@ impl Inner {
(value, Some(jar))
};
Box::new(
match serde_json::to_string(state) {
Err(e) => Either::A(FutErr(e.into())),
Ok(body) => Either::B(
self.addr.send(Command(resp_array!["SET", value, body,"EX", &self.ttl]))
.map_err(Error::from)
.and_then(move |res| match res {
Ok(_) => {
if let Some(jar) = jar {
for cookie in jar.delta() {
let val = HeaderValue::from_str(
&cookie.to_string())?;
resp.headers_mut().append(header::SET_COOKIE, val);
}
Box::new(match serde_json::to_string(state) {
Err(e) => Either::A(FutErr(e.into())),
Ok(body) => Either::B(
self.addr
.send(Command(resp_array![
"SET", value, body, "EX", &self.ttl
]))
.map_err(Error::from)
.and_then(move |res| match res {
Ok(_) => {
if let Some(jar) = jar {
for cookie in jar.delta() {
let val =
HeaderValue::from_str(&cookie.to_string())?;
resp.headers_mut().append(header::SET_COOKIE, val);
}
Ok(resp)
},
Err(err) => Err(error::ErrorInternalServerError(err).into())
}))
})
}
Ok(resp)
}
Err(err) => Err(error::ErrorInternalServerError(err).into()),
}),
),
})
}
}