use zhur_common::bincode::{deserialize, serialize};
use zhur_common::log::*;
use zhur_common::zmq::{Context, Socket, SocketType};
use zhur_invk::{HttpRes, Invocation, InvocationError};
/// The ZMQ server that takes invocations incoming from the gateway and sends back HttpReses or InvocationErrors.
pub struct CoreServer {
rep_socket: Socket
}
impl CoreServer {
pub fn new(zmq_ctx: &Context) -> Self {
Self {
rep_socket: {
let socket = zmq_ctx.socket(SocketType::REP)
.expect("Expected to be able to construct a ZMQ socket.");
let endpoint = match std::env::var("ZHUR_CORE_REP_URI") {
Ok(s) => s,
Err(_) => {
warn!("ZHUR_CORE_REP_URI not set - assuming default value of tcp://127.0.0.1:8081!");
"tcp://127.0.0.1:8081".to_owned()
}
};
socket.bind(&endpoint)
.expect("Expected to be able to bind the core server socket.");
socket
}
}
}
pub fn handle(&self) {
let bytes = match self.rep_socket.recv_bytes(0) {
Ok(b) => {
trace!("CoreServer received some bytes.");
b
},
Err(_) => {
panic!("CoreServer could not receive any bytes.")
}
};
let response = handle_invoke_bytes(&bytes);
let res_bytes = match serialize(&response) {
Ok(b) => b,
Err(_) => panic!("Could not serialize a response.")
};
match self.rep_socket.send(res_bytes, 0) {
Ok(_) => {
trace!("Sent a response!");
()
},
Err(_) => panic!("Could not send a reply.")
}
}
}
fn handle_invoke_bytes(bytes: &[u8]) -> Result<HttpRes, InvocationError> {
match deserialize::<Invocation>(bytes) {
Ok(i) => handle_invocation(&i),
Err(_) => Err(InvocationError::MalformedRequest)
}
}
fn handle_invocation(_i: &Invocation) -> Result<HttpRes, InvocationError> {
let mut res = HttpRes::default();
res.body = b"Hello world from Zhur!".to_vec();
Ok(res)
}