Skip to content

Commit

Permalink
Update docs
Browse files Browse the repository at this point in the history
* Update version to "0.1.1"
  • Loading branch information
nathiss committed Aug 6, 2023
1 parent bfe615c commit 78c24bf
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "reception"
version = "0.1.0"
version = "0.1.1"
authors = ["Kamil Rusin <kamil.jakub.rusin@gmail.com>"]
edition = "2021"
description = "A Rust library for creating TCP listeners that spawns clients providing model abstraction layer."
Expand Down Expand Up @@ -29,6 +29,7 @@ humantime-serde = "1.1.1"
cancellable = "0.3.0"
async-trait = "0.1.72"
fastrand = "2.0.0"
tokio-util = "0.7.8"

[dev-dependencies]
anyhow = "1.0.71"
Expand Down
63 changes: 63 additions & 0 deletions examples/echo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use cancellable::Cancellable;
use reception::{client::Client, connection::Connection, SenderHandle};
use tokio::{net::TcpStream, sync::mpsc::unbounded_channel};
use tokio_tungstenite::WebSocketStream;
use tokio_util::sync::CancellationToken;

#[derive(Debug)]
struct Model {
payload: Vec<u8>,
}

impl Into<Vec<u8>> for Model {
fn into(self) -> Vec<u8> {
self.payload
}
}

impl TryFrom<Vec<u8>> for Model {
type Error = anyhow::Error;

fn try_from(payload: Vec<u8>) -> Result<Self, Self::Error> {
Ok(Self { payload })
}
}

fn handle_client(
client: Client<Connection<WebSocketStream<TcpStream>>, Model, Model>,
cancellation_token: CancellationToken,
) -> Result<(), Client<Connection<WebSocketStream<TcpStream>>, Model, Model>> {
tokio::spawn(async move {
let (tx, mut rx) = unbounded_channel();
let mut handle = client
.spawn_with_callback(cancellation_token, move |msg| {
tx.send(msg).unwrap();
Ok(())
})
.await;

while let Some(msg) = rx.recv().await {
handle.send(msg).await.unwrap();
}
});
Ok(())
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
let cancellation_token = CancellationToken::new();

let listener =
reception::Listener::<Model, Model>::bind(Default::default(), cancellation_token.clone())
.await?;

let handle = listener
.spawn_with_callback(cancellation_token.clone(), move |client| {
handle_client(client, cancellation_token.clone())
})
.await;

handle.await??;

Ok(())
}
3 changes: 2 additions & 1 deletion src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ mod shared_state;

use std::{fmt::Display, marker::PhantomData};

use cancellable::{Cancellable, CancellableHandle, CancellationResult, CancellationToken};
use cancellable::{Cancellable, CancellableHandle, CancellationResult};
use tokio::sync::mpsc::{error::SendError, unbounded_channel, UnboundedReceiver};
use tokio_util::sync::CancellationToken;

use crate::SenderHandle;

Expand Down
1 change: 0 additions & 1 deletion src/connection/connection_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::{
atomic::{AtomicBool, Ordering},
Arc, Weak,
},
vec,
};

use async_trait::async_trait;
Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
#![warn(missing_docs)]

//! This crate provides a way of binding a TCP listener that will accept incoming
//! [WebSocket](https://en.wikipedia.org/wiki/WebSocket) connections. Additionally it provides an abstraction layer (see
//! [`Client`](crate::client::Client)) for serializing and deserializing well-defined models.

/// Module containing types associated with client-level abstraction (sending and receiving models).
pub mod client;

/// Module containing types associated with connection-level abstraction (sending raw bytes and handling protocol
/// details).
pub mod connection;
mod listener;
mod sender_handle;
Expand All @@ -9,3 +17,4 @@ pub use listener::config::ListenerConfig;
pub use listener::error::ListenerError;
pub use listener::Listener;
pub use sender_handle::SenderHandle;
pub use tokio_util::sync::CancellationToken;
7 changes: 5 additions & 2 deletions src/listener/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ pub(crate) mod error;

use std::{marker::PhantomData, net::SocketAddr};

use cancellable::{Cancellable, CancellationResult, CancellationToken};

use cancellable::{Cancellable, CancellationResult};
use tokio::{
net::{TcpListener, TcpStream},
sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
};
use tokio_tungstenite::{accept_async_with_config, WebSocketStream};
use tokio_util::sync::CancellationToken;

use crate::{client::Client, connection::Connection, ListenerConfig, ListenerError};

Expand Down Expand Up @@ -46,6 +46,9 @@ where
/// all clients spawned from this listener.
///
/// # Returns
///
/// `Ok(Self)` if it successfully bound to the socket. See
/// [`ListenerError`](`crate::listener::error::ListenerError`) for errors descriptions.
pub async fn bind(
config: ListenerConfig,
cancellation_token: CancellationToken,
Expand Down
16 changes: 16 additions & 0 deletions src/sender_handle.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
use async_trait::async_trait;

/// Sender trait implemented for some service handles.
///
/// Useful for sending data into the service.
#[async_trait]
pub trait SenderHandle {
/// Type of value send into the service.
type Item;

/// Type of error returned when the send has failed.
type Error;

/// Sends the given `item` into the service.
///
/// # Arguments
///
/// * `item` - value to the send into the service.
///
/// # Returns
///
/// Returns `Ok(())` when it successfully send data into the service,
/// `Err(Self::Error)` otherwise.
async fn send(&mut self, item: Self::Item) -> Result<(), Self::Error>;
}

0 comments on commit 78c24bf

Please sign in to comment.