DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Using TLS in Rust: Handling Messages Out of Band

Using TLS in Rust: Handling Messages Out of Band

Learn more about using TLS with Rust to handle messages out of band.

Oren Eini user avatar by
Oren Eini
·
Feb. 20, 19 · Tutorial
Like (1)
Save
Tweet
Share
3.73K Views

Join the DZone community and get the full member experience.

Join For Free

I'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.

TLS Rust (programming language) BAND (application)

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Event Driven 2.0
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future
  • Easy Smart Contract Debugging With Truffle’s Console.log
  • Java Development Trends 2023

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: