mirror of https://github.com/chipsenkbeil/distant
Refactor code to have request/response format w/ client wrapper for easier processing
parent
f6fa3e606e
commit
f2cce4aa34
@ -1,75 +1,102 @@
|
|||||||
use crate::utils::Session;
|
mod transport;
|
||||||
use codec::{DistantCodec, DistantCodecError};
|
pub use transport::{Transport, TransportError};
|
||||||
use derive_more::{Display, Error, From};
|
|
||||||
use futures::SinkExt;
|
use crate::{
|
||||||
use orion::{
|
data::{Request, Response, ResponsePayload},
|
||||||
aead::{self, SecretKey},
|
utils::Session,
|
||||||
errors::UnknownCryptoError,
|
};
|
||||||
|
use log::*;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
};
|
};
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
use tokio::{
|
||||||
use std::sync::Arc;
|
io,
|
||||||
use tokio::{io, net::TcpStream};
|
sync::{oneshot, watch},
|
||||||
use tokio_stream::StreamExt;
|
};
|
||||||
use tokio_util::codec::Framed;
|
use tokio_stream::wrappers::WatchStream;
|
||||||
|
|
||||||
mod codec;
|
type Callbacks = Arc<Mutex<HashMap<usize, oneshot::Sender<Response>>>>;
|
||||||
|
|
||||||
#[derive(Debug, Display, Error, From)]
|
/// Represents a client that can make requests against a server
|
||||||
pub enum TransportError {
|
pub struct Client {
|
||||||
CodecError(DistantCodecError),
|
/// Underlying transport used by client
|
||||||
EncryptError(UnknownCryptoError),
|
transport: Arc<tokio::sync::Mutex<Transport>>,
|
||||||
IoError(io::Error),
|
|
||||||
SerializeError(serde_cbor::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represents a transport of data across the network
|
/// Collection of callbacks to be invoked upon receiving a response to a request
|
||||||
pub struct Transport {
|
callbacks: Callbacks,
|
||||||
inner: Framed<TcpStream, DistantCodec>,
|
|
||||||
key: Arc<SecretKey>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Transport {
|
/// Callback to trigger when a response is received without an origin or with an origin
|
||||||
/// Wraps a `TcpStream` and associated credentials in a transport layer
|
/// not found in the list of callbacks
|
||||||
pub fn new(stream: TcpStream, key: Arc<SecretKey>) -> Self {
|
rx: watch::Receiver<Response>,
|
||||||
Self {
|
}
|
||||||
inner: Framed::new(stream, DistantCodec),
|
|
||||||
key,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
impl Client {
|
||||||
/// Establishes a connection using the provided session
|
/// Establishes a connection using the provided session
|
||||||
pub async fn connect(session: Session) -> io::Result<Self> {
|
pub async fn connect(session: Session) -> io::Result<Self> {
|
||||||
let stream = TcpStream::connect(session.to_socket_addr().await?).await?;
|
let transport = Arc::new(tokio::sync::Mutex::new(Transport::connect(session).await?));
|
||||||
Ok(Self::new(stream, Arc::new(session.key)))
|
let callbacks: Callbacks = Arc::new(Mutex::new(HashMap::new()));
|
||||||
}
|
let (tx, rx) = watch::channel(Response::from(ResponsePayload::Error {
|
||||||
|
description: String::from("Fake server response"),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Start a task that continually checks for responses and triggers callbacks
|
||||||
|
let transport_2 = Arc::clone(&transport);
|
||||||
|
let callbacks_2 = Arc::clone(&callbacks);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
match transport_2.lock().await.receive::<Response>().await {
|
||||||
|
Ok(Some(res)) => {
|
||||||
|
let maybe_callback = res
|
||||||
|
.origin_id
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|id| callbacks_2.lock().unwrap().remove(id));
|
||||||
|
|
||||||
|
// If there is an origin to this response, trigger the callback
|
||||||
|
if let Some(tx) = maybe_callback {
|
||||||
|
if let Err(res) = tx.send(res) {
|
||||||
|
error!("Failed to trigger callback for response {}", res.id);
|
||||||
|
}
|
||||||
|
|
||||||
/// Sends some data across the wire
|
// Otherwise, this goes into the junk draw of response handlers
|
||||||
pub async fn send<T: Serialize>(&mut self, data: T) -> Result<(), TransportError> {
|
} else {
|
||||||
// Serialize, encrypt, and then (TODO) sign
|
if let Err(x) = tx.send(res) {
|
||||||
// NOTE: Cannot used packed implementation for now due to issues with deserialization
|
error!("Failed to trigger watch: {}", x);
|
||||||
let data = serde_cbor::to_vec(&data)?;
|
}
|
||||||
let data = aead::seal(&self.key, &data)?;
|
}
|
||||||
|
}
|
||||||
|
Ok(None) => break,
|
||||||
|
Err(x) => {
|
||||||
|
error!("{}", x);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
self.inner
|
Ok(Self {
|
||||||
.send(&data)
|
transport,
|
||||||
.await
|
callbacks,
|
||||||
.map_err(TransportError::CodecError)
|
rx,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receives some data from out on the wire, waiting until it's available,
|
/// Sends a request and waits for a response
|
||||||
/// returning none if the transport is now closed
|
pub async fn send(&self, req: Request) -> Result<Response, TransportError> {
|
||||||
pub async fn receive<T: DeserializeOwned>(&mut self) -> Result<Option<T>, TransportError> {
|
// First, add a callback that will trigger when we get the response for this request
|
||||||
// If data is received, we process like usual
|
let (tx, rx) = oneshot::channel();
|
||||||
if let Some(data) = self.inner.next().await {
|
self.callbacks.lock().unwrap().insert(req.id, tx);
|
||||||
// Validate (TODO) signature, decrypt, and then deserialize
|
|
||||||
let data = data?;
|
// Second, send the request
|
||||||
let data = aead::open(&self.key, &data)?;
|
self.transport.lock().await.send(req).await?;
|
||||||
let data = serde_cbor::from_slice(&data)?;
|
|
||||||
Ok(Some(data))
|
// Third, wait for the response
|
||||||
|
rx.await
|
||||||
|
.map_err(|x| TransportError::from(io::Error::new(io::ErrorKind::ConnectionAborted, x)))
|
||||||
|
}
|
||||||
|
|
||||||
// Otherwise, if no data is received, this means that our socket has closed
|
/// Creates and returns a new stream of responses that are received with no originating request
|
||||||
} else {
|
pub fn to_response_stream(&self) -> WatchStream<Response> {
|
||||||
Ok(None)
|
WatchStream::new(self.rx.clone())
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,75 @@
|
|||||||
|
use crate::utils::Session;
|
||||||
|
use codec::{DistantCodec, DistantCodecError};
|
||||||
|
use derive_more::{Display, Error, From};
|
||||||
|
use futures::SinkExt;
|
||||||
|
use orion::{
|
||||||
|
aead::{self, SecretKey},
|
||||||
|
errors::UnknownCryptoError,
|
||||||
|
};
|
||||||
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::{io, net::TcpStream};
|
||||||
|
use tokio_stream::StreamExt;
|
||||||
|
use tokio_util::codec::Framed;
|
||||||
|
|
||||||
|
mod codec;
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
pub enum TransportError {
|
||||||
|
CodecError(DistantCodecError),
|
||||||
|
EncryptError(UnknownCryptoError),
|
||||||
|
IoError(io::Error),
|
||||||
|
SerializeError(serde_cbor::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents a transport of data across the network
|
||||||
|
pub struct Transport {
|
||||||
|
inner: Framed<TcpStream, DistantCodec>,
|
||||||
|
key: Arc<SecretKey>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport {
|
||||||
|
/// Wraps a `TcpStream` and associated credentials in a transport layer
|
||||||
|
pub fn new(stream: TcpStream, key: Arc<SecretKey>) -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Framed::new(stream, DistantCodec),
|
||||||
|
key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establishes a connection using the provided session
|
||||||
|
pub async fn connect(session: Session) -> io::Result<Self> {
|
||||||
|
let stream = TcpStream::connect(session.to_socket_addr().await?).await?;
|
||||||
|
Ok(Self::new(stream, Arc::new(session.key)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends some data across the wire
|
||||||
|
pub async fn send<T: Serialize>(&mut self, data: T) -> Result<(), TransportError> {
|
||||||
|
// Serialize, encrypt, and then (TODO) sign
|
||||||
|
// NOTE: Cannot used packed implementation for now due to issues with deserialization
|
||||||
|
let data = serde_cbor::to_vec(&data)?;
|
||||||
|
let data = aead::seal(&self.key, &data)?;
|
||||||
|
|
||||||
|
self.inner
|
||||||
|
.send(&data)
|
||||||
|
.await
|
||||||
|
.map_err(TransportError::CodecError)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Receives some data from out on the wire, waiting until it's available,
|
||||||
|
/// returning none if the transport is now closed
|
||||||
|
pub async fn receive<T: DeserializeOwned>(&mut self) -> Result<Option<T>, TransportError> {
|
||||||
|
// If data is received, we process like usual
|
||||||
|
if let Some(data) = self.inner.next().await {
|
||||||
|
// Validate (TODO) signature, decrypt, and then deserialize
|
||||||
|
let data = data?;
|
||||||
|
let data = aead::open(&self.key, &data)?;
|
||||||
|
let data = serde_cbor::from_slice(&data)?;
|
||||||
|
Ok(Some(data))
|
||||||
|
|
||||||
|
// Otherwise, if no data is received, this means that our socket has closed
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue