Using TLS in Rust: Handling Messages Out of Band
Learn more about using TLS with Rust to handle messages out of band.
Join the DZone community and get the full member experience.
Join For FreeI'm pretty much done with my Rust protocol impl. The last thing that I wanted to try was to see how it would look like when I allow messages to be handled out of band.
Right now, my code consuming the protocol library looks like this:
// handler def
type Handler = fn(self::cmd::Cmd) -> Result<String, ConnectionError>;
// handler impl
fn echo(cmd: server::cmd::Cmd) -> std::result::Result<String, ConnectionError> {
Ok(cmd.args[1].clone())
}
// registeration
{
Arc::get_mut(&mut server).unwrap()
.handle("echo".to_string(), echo);
}
This is pretty simple, but note that the function definition forces us to return a value immediately and that we don't have a way to handle a command asynchronously.
What I wanted to do was change things around so that I could do that. I decided to implement the command:
remind 15 Nap
This should help me remember to nap. In order to handle this scenario, I need to provide a way to do async work and to keep sending messages to the client. Here was the first change I made:

Instead of returning a value from the function, we are going to give it the sender (which will render the value to the client) and can return an error if the command is invalid in some form.
That said, it means that the echo implementation is a bit more complex.
fn echo(cmd: server::cmd::Cmd, sender : Sender<String>) -> std::result::Result<(), ConnectionError> {
tokio::spawn(sender.send(cmd.args[1].clone()).map_err(|_|()).map(|_|()));
Ok(())
}
There is... a lot of ceremony here, even for something so small. Let's see what happens when we do something bigger, shall we? Here is the implementation of the reminder handler:
fn remind(cmd: server::cmd::Cmd, sender : Sender<String>) -> std::result::Result<(), ConnectionError> {
static COUNTER : std::sync::atomic::AtomicUsize = std::sync::atomic::ATOMIC_USIZE_INIT;
// remdind <sec> msg
#[async]
fn delayed_send(delay: u64, msg: String, sender : Sender<String>) -> std::result::Result<(), ConnectionError> {
await!(Delay::new(Instant::now() +Duration::from_secs(delay)))?;
await!(sender.send(msg))?;
Ok(())
}
let secs : u64 = match cmd.args.get(1){
None => return Err(ConnectionError::BadDataArgs{
msg: "'remind' requires a <secs> argument".to_string()
}),
Some(str) => match str.parse::<u64>(){
Err(e) => return Err(ConnectionError::BadDataArgs{
msg: "'remind' requires a <secs> argument to be a u64: ".to_string() + &e.to_string()
}),
Ok(v) => v
}
};
let msg = match cmd.args.get(2){
None => "Reminder",
Some(v) => v
};
let id = (COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1).to_string();
tokio::spawn(delayed_send(secs, msg.to_string() + "\r\nSequence: " + &id, sender.clone()).map_err(|_|()));
tokio::spawn(sender.send("OK\r\nSequence: ".to_string() + &id).map_err(|_|()).map(|_|()));
Ok(())
}
Admittedly, a lot of that is error handling, but there is a lot of code here to do something that simple. Compare that to something like C#, where the same thing could be written as:
public async Task Remind(Cmd cmd, TextWriter writer)
{
if(cmd.Arguments.Count < 3)
return await writer.WriteAsync("ERR command requires 3 parameters\r\n\r\n");
if(int.TryParse(cmd.Arguments[1], out var wait) == false))
return await writer.WriteAsync("ERR cannot parse <wait> argument for command: " + cmd.Arguments[1] + "\r\n\r\n");
await writer.WriteAsync("OK\r\n\r\n");
async Task.Delay(wait);
await writer.WriteAsync(string.Join(cmd.Arguments.Skip(2)) + "\r\n\r\n");
}
I'm not sure that the amount of complexity that is brought about by the tokio model, even with the async/await macros is worth it at this point. I believe that it needs at least a few more iterations before it is going to be usable for the general public.
There is way too much ceremony and work to be done, and a single miss and you are faced with a very pissed off compiler.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments