use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use redis_tower_core::{Command, RedisConnection, RedisError};
use tokio::sync::Mutex;
use crate::caching::CachedClient;
use crate::client::RedisClient;
use crate::multiplexed::{CachedMultiplexedClient, MultiplexedClient};
use crate::resilient::ResilientRedisClient;
pub trait RedisExecutor {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send;
}
impl RedisExecutor for RedisConnection {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
RedisConnection::execute(self, cmd)
}
}
impl RedisExecutor for RedisClient {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
RedisClient::execute(self, cmd)
}
}
impl RedisExecutor for ResilientRedisClient {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
ResilientRedisClient::execute(self, cmd)
}
}
impl RedisExecutor for CachedClient {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
CachedClient::execute(self, cmd)
}
}
impl<C: RedisExecutor + Send> RedisExecutor for Arc<Mutex<C>> {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
let arc = Arc::clone(self);
async move { arc.lock().await.execute(cmd).await }
}
}
impl<C: RedisExecutor + Send + ?Sized> RedisExecutor for &mut C {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
(**self).execute(cmd)
}
}
impl RedisExecutor for MultiplexedClient {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
MultiplexedClient::execute(self, cmd)
}
}
impl RedisExecutor for CachedMultiplexedClient {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
CachedMultiplexedClient::execute(self, cmd)
}
}
#[derive(Clone, Debug)]
pub struct ExecutorService<P> {
inner: P,
}
impl<P> ExecutorService<P> {
pub fn new(inner: P) -> Self {
Self { inner }
}
pub fn into_inner(self) -> P {
self.inner
}
pub fn get_ref(&self) -> &P {
&self.inner
}
}
impl<P, Cmd> tower_service::Service<Cmd> for ExecutorService<P>
where
P: RedisExecutor + Clone + Send + 'static,
Cmd: Command + Send + 'static,
{
type Response = Cmd::Response;
type Error = RedisError;
type Future = Pin<Box<dyn Future<Output = Result<Cmd::Response, RedisError>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, cmd: Cmd) -> Self::Future {
let mut inner = self.inner.clone();
Box::pin(async move { inner.execute(cmd).await })
}
}
#[cfg(test)]
mod tests {
use super::*;
use redis_tower_core::Frame;
use std::collections::VecDeque;
struct MockRedis {
responses: VecDeque<Frame>,
}
impl MockRedis {
fn new(responses: Vec<Frame>) -> Self {
Self {
responses: VecDeque::from(responses),
}
}
}
impl RedisExecutor for MockRedis {
fn execute<Cmd: Command>(
&mut self,
cmd: Cmd,
) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
let frame = self.responses.pop_front().unwrap_or(Frame::Null);
async move { cmd.parse_response(frame) }
}
}
#[tokio::test]
async fn mock_executor_returns_response() {
use bytes::Bytes;
use redis_tower_commands::Get;
let mut mock = MockRedis::new(vec![Frame::BulkString(Some(Bytes::from("hello")))]);
let result: Option<Bytes> = mock.execute(Get::new("key")).await.unwrap();
assert_eq!(result, Some(Bytes::from("hello")));
}
#[tokio::test]
async fn arc_mutex_implements_executor() {
use bytes::Bytes;
use redis_tower_commands::Get;
let mock = Arc::new(Mutex::new(MockRedis::new(vec![Frame::BulkString(Some(
Bytes::from("world"),
))])));
let mut executor = Arc::clone(&mock);
let result: Option<Bytes> = executor.execute(Get::new("key")).await.unwrap();
assert_eq!(result, Some(Bytes::from("world")));
}
#[tokio::test]
async fn mut_ref_implements_executor() {
use bytes::Bytes;
use redis_tower_commands::Get;
let mut mock = MockRedis::new(vec![Frame::BulkString(Some(Bytes::from("ref")))]);
let result: Option<Bytes> = mock.execute(Get::new("key")).await.unwrap();
assert_eq!(result, Some(Bytes::from("ref")));
}
#[tokio::test]
async fn executor_service_bridges_to_tower() {
use bytes::Bytes;
use redis_tower_commands::Get;
use std::future::poll_fn;
use tower_service::Service;
let mock = Arc::new(Mutex::new(MockRedis::new(vec![Frame::BulkString(Some(
Bytes::from("via-service"),
))])));
let mut svc = ExecutorService::new(mock);
let _clone = svc.clone();
poll_fn(|cx| Service::<Get>::poll_ready(&mut svc, cx))
.await
.unwrap();
let result: Option<Bytes> = svc.call(Get::new("key")).await.unwrap();
assert_eq!(result, Some(Bytes::from("via-service")));
}
}