Book Image

Rust Web Programming - Second Edition

By : Maxwell Flitton
Book Image

Rust Web Programming - Second Edition

By: Maxwell Flitton

Overview of this book

Are safety and high performance a big concern for you while developing web applications? With this practical Rust book, you’ll discover how you can implement Rust on the web to achieve the desired performance and security as you learn techniques and tooling to build fully operational web apps. In this second edition, you’ll get hands-on with implementing emerging Rust web frameworks, including Actix, Rocket, and Hyper. It also features HTTPS configuration on AWS when deploying a web application and introduces you to Terraform for automating the building of web infrastructure on AWS. What’s more, this edition also covers advanced async topics. Built on the Tokio async runtime, this explores TCP and framing, implementing async systems with the actor framework, and queuing tasks on Redis to be consumed by a number of worker nodes. Finally, you’ll go over best practices for packaging Rust servers in distroless Rust Docker images with database drivers, so your servers are a total size of 50Mb each. By the end of this book, you’ll have confidence in your skills to build robust, functional, and scalable web applications from scratch.
Table of Contents (27 chapters)
Free Chapter
1
Part 1:Getting Started with Rust Web Development
4
Part 2:Processing Data and Managing Displays
8
Part 3:Data Persistence
12
Part 4:Testing and Deployment
16
Part 5:Making Our Projects Flexible
19
Part 6:Exploring Protocol Programming and Async Concepts with Low-Level Network Applications

Passing TCP to an actor

When it comes to routing TCP data to actors, we need to import our actors and channels into the main.rs file in our server project with the following code:

. . .
use tokio::sync::mpsc;
mod actors;
use actors::{OrderBookActor, BuyOrder, Message};
. . .

Now, we have to construct our order book actor and run it. However, as you may recall, we merely ran the order book actor at the end of the Tokio runtime. However, if we apply this strategy here, we will block the loop from executing, so we can listen to incoming traffic. If we run the order book actor after the loop, the order book actor will never run as the loop runs indefinitely in a while loop and thus blocks the execution of any code following it. In our case, there is a further complication. This complication is that the actor run function enters a while loop, which further explains the need to put this entire code in a separate spawned Tokio task. Because of this, we must spawn a thread before the...