use crate::deserializer::{ParseError, Parser, RawResponse};
use crate::error::SkyhashError;
use crate::types::FromSkyhashBytes;
use crate::Element;
use crate::Pipeline;
use crate::Query;
use crate::SkyQueryResult;
use crate::SkyResult;
use crate::WriteQueryAsync;
use bytes::{Buf, BytesMut};
use std::io::{Error as IoError, ErrorKind};
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufWriter};
use tokio::net::TcpStream;
const BUF_CAP: usize = 4096;
macro_rules! impl_async_methods {
($ty:ty, $inner:ty) => {
impl $ty {
pub async fn run_query<T: FromSkyhashBytes, Q: AsRef<Query>>(&mut self, query: Q) -> SkyResult<T> {
self.run_query_raw(query).await?.try_element_into()
}
pub async fn run_query_raw<Q: AsRef<Query>>(&mut self, query: Q) -> SkyResult<Element> {
match self._run_query(query.as_ref()).await? {
RawResponse::SimpleQuery(sq) => Ok(sq),
RawResponse::PipelinedQuery(_) => Err(SkyhashError::InvalidResponse.into()),
}
}
#[deprecated(
since = "0.7.0",
note = "this will be removed in a future release. consider using `run_query_raw` instead")
]
pub async fn run_simple_query(&mut self, query: &Query) -> SkyQueryResult {
self.run_query_raw(query).await
}
pub async fn run_pipeline(&mut self, pipeline: Pipeline) -> SkyResult<Vec<Element>> {
match self._run_query(&pipeline).await? {
RawResponse::PipelinedQuery(pq) => Ok(pq),
RawResponse::SimpleQuery(_) => Err(SkyhashError::InvalidResponse.into()),
}
}
async fn _run_query<Q: WriteQueryAsync<$inner>>(
&mut self,
query: &Q,
) -> SkyResult<RawResponse> {
query.write_async(&mut self.stream).await?;
self.stream.flush().await?;
loop {
if 0usize == self.stream.read_buf(&mut self.buffer).await? {
return Err(IoError::from(ErrorKind::ConnectionReset).into());
}
match self.try_response() {
Ok((query, forward_by)) => {
self.buffer.advance(forward_by);
return Ok(query);
}
Err(e) => match e {
ParseError::NotEnough => (),
ParseError::BadPacket | ParseError::UnexpectedByte => {
self.buffer.clear();
return Err(SkyhashError::InvalidResponse.into());
}
ParseError::DataTypeError => {
return Err(SkyhashError::ParseError.into())
}
ParseError::Empty => {
return Err(IoError::from(ErrorKind::ConnectionReset).into())
}
ParseError::UnknownDatatype => {
return Err(SkyhashError::UnknownDataType.into())
}
},
}
}
}
fn try_response(&mut self) -> Result<(RawResponse, usize), ParseError> {
if self.buffer.is_empty() {
return Err(ParseError::Empty);
}
Parser::new(&self.buffer).parse()
}
}
impl crate::actions::AsyncSocket for $ty {
fn run(&mut self, q: Query) -> crate::AsyncResult<SkyQueryResult> {
Box::pin(async move { self.run_query_raw(&q).await })
}
}
};
}
cfg_async!(
pub struct Connection {
stream: BufWriter<TcpStream>,
buffer: BytesMut,
}
impl Connection {
pub async fn new(host: &str, port: u16) -> SkyResult<Self> {
let stream = TcpStream::connect((host, port)).await?;
Ok(Connection {
stream: BufWriter::new(stream),
buffer: BytesMut::with_capacity(BUF_CAP),
})
}
}
impl_async_methods!(Connection, BufWriter<TcpStream>);
);
cfg_async_ssl_any!(
use tokio_openssl::SslStream;
use openssl::ssl::{SslContext, SslMethod, Ssl};
use core::pin::Pin;
use crate::error::Error;
pub struct TlsConnection {
stream: SslStream<TcpStream>,
buffer: BytesMut
}
impl TlsConnection {
pub async fn new(host: &str, port: u16, sslcert: &str) -> Result<Self, Error> {
let mut ctx = SslContext::builder(SslMethod::tls_client())?;
ctx.set_ca_file(sslcert)?;
let ssl = Ssl::new(&ctx.build())?;
let stream = TcpStream::connect((host, port)).await?;
let mut stream = SslStream::new(ssl, stream)?;
Pin::new(&mut stream).connect().await?;
Ok(Self {
stream,
buffer: BytesMut::with_capacity(BUF_CAP),
})
}
}
impl_async_methods!(TlsConnection, SslStream<TcpStream>);
);