add pub sub client implementation with examples (#22)

* add pub sub client implementation with examples

* replace subscribed_channels list Vec with HashSet to avoid duplicates

* update Subscriber to use async-stream instead of manual Stream impl

* revert update to error handling server.rs, as #21 handles it

* remove uneeded recursion limit extension
This commit is contained in:
João Oliveira
2020-04-05 18:33:21 +01:00
committed by GitHub
parent f187085156
commit 3fbd9ddc42
7 changed files with 363 additions and 22 deletions

View File

@@ -4,8 +4,8 @@ use bytes::Bytes;
#[derive(Debug)]
pub struct Publish {
channel: String,
message: Bytes,
pub(crate) channel: String,
pub(crate) message: Bytes,
}
impl Publish {
@@ -24,4 +24,13 @@ impl Publish {
dst.write_frame(&response).await?;
Ok(())
}
pub(crate) fn into_frame(self) -> Frame {
let mut frame = Frame::array();
frame.push_bulk(Bytes::from("publish".as_bytes()));
frame.push_bulk(Bytes::from(self.channel.into_bytes()));
frame.push_bulk(self.message);
frame
}
}

View File

@@ -1,5 +1,5 @@
use crate::{Command, Connection, Db, Frame, Shutdown};
use crate::cmd::{Parse, ParseError};
use crate::{Command, Connection, Db, Frame, Shutdown};
use bytes::Bytes;
use tokio::select;
@@ -7,12 +7,12 @@ use tokio::stream::{StreamExt, StreamMap};
#[derive(Debug)]
pub struct Subscribe {
channels: Vec<String>,
pub(crate) channels: Vec<String>,
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct Unsubscribe {
channels: Vec<String>,
pub(crate) channels: Vec<String>,
}
impl Subscribe {
@@ -98,8 +98,8 @@ impl Subscribe {
res = dst.read_frame() => {
let frame = match res? {
Some(frame) => frame,
// How to handle remote client closing write half
None => unimplemented!(),
// How to handle remote client closing write half?
None => return Ok(())
};
// A command has been received from the client.
@@ -147,6 +147,15 @@ impl Subscribe {
};
}
}
pub(crate) fn into_frame(self) -> Frame {
let mut frame = Frame::array();
frame.push_bulk(Bytes::from("subscribe".as_bytes()));
for channel in self.channels {
frame.push_bulk(Bytes::from(channel.into_bytes()));
}
frame
}
}
impl Unsubscribe {
@@ -166,4 +175,13 @@ impl Unsubscribe {
Ok(Unsubscribe { channels })
}
pub(crate) fn into_frame(self) -> Frame {
let mut frame = Frame::array();
frame.push_bulk(Bytes::from("unsubscribe".as_bytes()));
for channel in self.channels {
frame.push_bulk(Bytes::from(channel.into_bytes()));
}
frame
}
}