use std::io;
use bytes::{BufMut, BytesMut};
use tokio_io::codec::Encoder;
const BUFFER_GROW: usize = 1024;
const SPACE_NEEDED: usize = 32;
#[derive(Builder, Debug)]
pub struct Message {
id: BytesMut,
body: BytesMut,
timestamp: i64,
attempts: u16,
}
impl Message {
pub fn id(&self) -> BytesMut {
self.id.clone()
}
pub fn body(&self) -> BytesMut {
self.body.clone()
}
pub fn timestamp(&self) -> i64 {
self.timestamp
}
pub fn attempts(&self) -> u16 {
self.attempts
}
}
pub enum MessageReply {
Fin(BytesMut),
Req(BytesMut),
Touch(BytesMut),
Nop,
}
pub trait Handler {
fn handle_message(&self, message: &Message) -> MessageReply;
}
fn put_nop(dst: &mut BytesMut) {
dst.put("NOP\n");
}
fn put_fin(dst: &mut BytesMut, id: &BytesMut) {
dst.put("FIN ");
dst.put(id);
dst.put("\n");
}
fn put_req(dst: &mut BytesMut, id: &BytesMut) {
dst.put("REQ ");
dst.put(id);
dst.put("\n");
}
fn put_touch(dst: &mut BytesMut, id: &BytesMut) {
dst.put("TOUCH ");
dst.put(id);
dst.put("\n");
}
#[derive(Default)]
pub struct NsqResponder;
impl Encoder for NsqResponder {
type Item = MessageReply;
type Error = io::Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
if dst.remaining_mut() < SPACE_NEEDED {
dst.reserve(BUFFER_GROW);
}
match item {
MessageReply::Nop => put_nop(dst),
MessageReply::Fin(ref id) => put_fin(dst, id),
MessageReply::Req(ref id) => put_req(dst, id),
MessageReply::Touch(ref id) => put_touch(dst, id),
}
Ok(())
}
}