use anyhow::{anyhow, Result};
use zmq;
pub struct EventPublisher {
#[allow(dead_code)]
context: zmq::Context,
pub_socket: zmq::Socket,
rep_socket: zmq::Socket,
}
impl EventPublisher {
pub fn new(pub_endpoint: &str, rep_endpoint: &str) -> Result<Self> {
let context = zmq::Context::new();
let pub_socket = context
.socket(zmq::PUB)
.map_err(|e| anyhow!("Failed to create PUB socket: {}", e))?;
let rep_socket = context
.socket(zmq::REP)
.map_err(|e| anyhow!("Failed to create REP socket: {}", e))?;
pub_socket
.bind(pub_endpoint)
.map_err(|e| anyhow!("Failed to bind PUB socket to {}: {}", pub_endpoint, e))?;
rep_socket
.bind(rep_endpoint)
.map_err(|e| anyhow!("Failed to bind REP socket to {}: {}", rep_endpoint, e))?;
Ok(EventPublisher {
context,
pub_socket,
rep_socket,
})
}
pub fn publish(&self, topic: &str, message: &str) -> Result<()> {
let full_message = format!("{} {}", topic, message);
self.pub_socket
.send(&full_message, 0)
.map_err(|e| anyhow!("Failed to send message: {}", e))?;
Ok(())
}
pub fn receive_request(&self) -> Result<String> {
let mut msg = zmq::Message::new();
self.rep_socket
.recv(&mut msg, 0)
.map_err(|e| anyhow!("Failed to receive request: {}", e))?;
Ok(msg.as_str().unwrap_or("").to_string())
}
pub fn send_reply(&self, reply: &str) -> Result<()> {
self.rep_socket
.send(reply, 0)
.map_err(|e| anyhow!("Failed to send reply: {}", e))?;
Ok(())
}
}
impl Drop for EventPublisher {
fn drop(&mut self) {
}
}