1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 09:42:40 +01:00
actix-extras/src/redis.rs

142 lines
4.3 KiB
Rust
Raw Normal View History

2017-12-29 06:14:04 +01:00
use std::io;
use std::collections::VecDeque;
2018-01-22 09:40:50 +01:00
use actix::prelude::*;
2018-02-16 01:53:05 +01:00
use actix::actors::{Connect, Connector};
2018-01-22 09:40:50 +01:00
use backoff::ExponentialBackoff;
use backoff::backoff::Backoff;
2017-12-29 06:14:04 +01:00
use futures::Future;
use futures::unsync::oneshot;
2018-01-22 09:40:50 +01:00
use tokio_io::AsyncRead;
2018-02-16 01:53:05 +01:00
use tokio_io::io::WriteHalf;
use tokio_io::codec::FramedRead;
2017-12-29 06:14:04 +01:00
use tokio_core::net::TcpStream;
2018-01-22 19:42:13 +01:00
use redis_async::error::Error as RespError;
use redis_async::resp::{RespCodec, RespValue};
2017-12-29 06:14:04 +01:00
2018-01-22 19:42:13 +01:00
use Error;
2017-12-29 06:14:04 +01:00
2018-02-16 01:53:05 +01:00
#[derive(Debug)]
2018-01-22 19:42:13 +01:00
pub struct Command(pub RespValue);
2017-12-29 06:14:04 +01:00
2018-02-16 01:53:05 +01:00
impl Message for Command {
type Result = Result<RespValue, Error>;
}
2017-12-29 06:14:04 +01:00
/// Redis comminucation actor
pub struct RedisActor {
2018-01-22 09:40:50 +01:00
addr: String,
backoff: ExponentialBackoff,
2018-02-16 01:53:05 +01:00
cell: Option<actix::io::FramedWrite<WriteHalf<TcpStream>, RespCodec>>,
2018-01-22 19:42:13 +01:00
queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
2017-12-29 06:14:04 +01:00
}
impl RedisActor {
2018-02-16 01:53:05 +01:00
pub fn start<S: Into<String>>(addr: S) -> Addr<Unsync, RedisActor> {
2018-01-22 09:40:50 +01:00
let addr = addr.into();
Supervisor::start(|_| {
RedisActor { addr: addr,
cell: None,
backoff: ExponentialBackoff::default(),
queue: VecDeque::new() }
2018-01-22 19:27:59 +01:00
})
2017-12-29 06:14:04 +01:00
}
}
impl Actor for RedisActor {
2018-01-22 09:40:50 +01:00
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
2018-02-16 01:53:05 +01:00
Connector::from_registry().send(Connect::host(self.addr.as_str()))
2018-01-22 09:40:50 +01:00
.into_actor(self)
2018-02-16 01:53:05 +01:00
.map(|res, act, ctx| match res {
Ok(stream) => {
info!("Connected to redis server: {}", act.addr);
let (r, w) = stream.split();
// configure write side of the connection
let mut framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
act.cell = Some(framed);
// read side of the connection
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.
// we stop currect context, supervisor will restart it.
if let Some(timeout) = act.backoff.next_backoff() {
ctx.run_later(timeout, |_, ctx| ctx.stop());
} else {
ctx.stop();
}
}
2018-01-22 09:40:50 +01:00
})
.map_err(|err, act, ctx| {
error!("Can not connect to redis server: {}", err);
2018-01-22 19:43:36 +01:00
// re-connect with backoff time.
// we stop currect context, supervisor will restart it.
2018-01-22 09:40:50 +01:00
if let Some(timeout) = act.backoff.next_backoff() {
2018-01-22 19:42:13 +01:00
ctx.run_later(timeout, |_, ctx| ctx.stop());
2018-01-22 09:40:50 +01:00
} else {
ctx.stop();
}
})
.wait(ctx);
}
}
impl Supervised for RedisActor {
fn restarting(&mut self, _: &mut Self::Context) {
self.cell.take();
for tx in self.queue.drain(..) {
let _ = tx.send(Err(Error::Disconnected));
}
}
2017-12-29 06:14:04 +01:00
}
2018-02-16 01:53:05 +01:00
impl actix::io::WriteHandler<io::Error> for RedisActor {
2017-12-29 06:14:04 +01:00
2018-02-16 01:53:05 +01:00
fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
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()));
2018-01-22 09:40:50 +01:00
}
2018-02-16 01:53:05 +01:00
Running::Stop
2018-01-22 09:40:50 +01:00
}
2018-02-16 01:53:05 +01:00
fn handle(&mut self, msg: RespValue, _: &mut Self::Context) {
2017-12-29 06:14:04 +01:00
if let Some(tx) = self.queue.pop_front() {
2018-02-16 01:53:05 +01:00
let _ = tx.send(Ok(msg));
2017-12-29 06:14:04 +01:00
}
}
}
impl Handler<Command> for RedisActor {
2018-02-16 01:53:05 +01:00
type Result = ResponseFuture<RespValue, Error>;
2018-01-05 23:52:07 +01:00
2018-01-22 09:40:50 +01:00
fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
2017-12-29 06:14:04 +01:00
let (tx, rx) = oneshot::channel();
2018-01-22 09:40:50 +01:00
if let Some(ref mut cell) = self.cell {
self.queue.push_back(tx);
2018-02-16 01:53:05 +01:00
cell.write(msg.0);
2018-01-22 09:40:50 +01:00
} else {
let _ = tx.send(Err(Error::NotConnected));
}
2017-12-29 06:14:04 +01:00
2018-02-16 01:53:05 +01:00
Box::new(rx.map_err(|_| Error::Disconnected).and_then(|res| res))
2017-12-29 06:14:04 +01:00
}
}