Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for reverse binding between PUB and SUB #149

Merged
merged 5 commits into from
Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions examples/forwarder_device.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
mod async_helpers;
use std::error::Error;
use zeromq::prelude::*;

#[async_helpers::main]
async fn main() -> Result<(), Box<dyn Error>> {
println!("Start forwarder");
let mut frontend = zeromq::SubSocket::new();
frontend.bind("tcp://127.0.0.1:30001").await?;

let mut backend = zeromq::PubSocket::new();
backend.bind("tcp://127.0.0.1:30002").await?;

frontend.subscribe("").await?;

let forward = async move {
loop {
let message = frontend.recv().await.unwrap();
println!("passing message: {:?}", message);
backend.send(message).await.unwrap();
}
};

forward.await;

Ok(())
}
81 changes: 76 additions & 5 deletions src/sub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,89 @@ use crate::message::*;
use crate::transport::AcceptStopHandle;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, Socket, SocketBackend, SocketEvent, SocketOptions, SocketRecv, SocketType,
MultiPeerBackend, Socket, SocketBackend, SocketEvent, SocketOptions, SocketRecv, SocketType
};

use crate::backend::GenericSocketBackend;
use crate::backend::Peer;
use dashmap::DashMap;
use parking_lot::Mutex;
use crate::fair_queue::QueueInner;
use crate::fair_queue::FairQueue;
use crossbeam::queue::SegQueue;
use async_trait::async_trait;
use bytes::{BufMut, BytesMut};
use futures::channel::mpsc;
use futures::{SinkExt, StreamExt};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

pub(crate) struct SubSocketBackend {
pub(crate) peers: DashMap<PeerIdentity, Peer>,
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
pub(crate) round_robin: SegQueue<PeerIdentity>,
socket_type: SocketType,
socket_options: SocketOptions,
pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>,
}

impl SubSocketBackend {
pub(crate) fn with_options(
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
socket_type: SocketType,
options: SocketOptions,
) -> Self {
Self {
peers: DashMap::new(),
fair_queue_inner,
round_robin: SegQueue::new(),
socket_type,
socket_options: options,
socket_monitor: Mutex::new(None),
}
}
}

impl SocketBackend for SubSocketBackend {
fn socket_type(&self) -> SocketType {
self.socket_type
}

fn socket_options(&self) -> &SocketOptions {
&self.socket_options
}

fn shutdown(&self) {
self.peers.clear();
}

fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> {
&self.socket_monitor
}
}

impl MultiPeerBackend for SubSocketBackend {
fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) {
let (recv_queue, send_queue) = io.into_parts();
self.peers.insert(peer_id.clone(), Peer { send_queue });
self.round_robin.push(peer_id.clone());
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().insert(peer_id.clone(), recv_queue);
}
};
}

fn peer_disconnected(&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
}
}

pub struct SubSocket {
backend: Arc<GenericSocketBackend>,
backend: Arc<SubSocketBackend>,
fair_queue: FairQueue<ZmqFramedRead, PeerIdentity>,
binds: HashMap<Endpoint, AcceptStopHandle>,
subs: HashSet<String>,
}

impl Drop for SubSocket {
Expand All @@ -41,10 +108,12 @@ impl SubSocket {
.send(Message::Message(message.clone()))
.await?;
}
self.subs.insert(subscription.to_string());
Ok(())
}

pub async fn unsubscribe(&mut self, subscription: &str) -> ZmqResult<()> {
self.subs.insert(subscription.to_string());
Alexei-Kornienko marked this conversation as resolved.
Show resolved Hide resolved
let mut buf = BytesMut::with_capacity(subscription.len() + 1);
buf.put_u8(0);
buf.extend_from_slice(subscription.as_bytes());
Expand All @@ -58,18 +127,20 @@ impl SubSocket {
}
}


#[async_trait]
impl Socket for SubSocket {
fn with_options(options: SocketOptions) -> Self {
let fair_queue = FairQueue::new(true);
Self {
backend: Arc::new(GenericSocketBackend::with_options(
backend: Arc::new(SubSocketBackend::with_options(
Some(fair_queue.inner()),
SocketType::SUB,
options,
)),
fair_queue,
binds: HashMap::new(),
subs: HashSet::new(),
}
}

Expand Down