Handling HTTP Requests
local graph
Chapter 5 — Handling HTTP Requests
Section titled “Chapter 5 — Handling HTTP Requests”5 Handling HTTP Requests
Section titled “5 Handling HTTP Requests”After the detour of understanding async on a deeper level, we are now going back to the project that we were working on in Chapter 3. So far, we have structured our to-do module in a flexible, scalable, and reusable manner. However, this can only get us so far in terms of web programming. We want our to-do module to reach people quickly without the user having to install Rust on their own computers. We can do this with a web framework.
In this chapter, we will build on the core logic of our to-do items and connect this core logic to a server. By the end of this chapter, you will be able to build a server that has a data access layer, core layer, and networking layer. You will also get some exposure in handling errors across all Cargo workspaces and refactoring some of our code as our requirements for our server get more defined over time.
We will cover the following topics in this chapter:
- Launching a basic web server
- Connecting the core to the server
- Refactoring our to-do items
- Serving our to-do items
- Handling errors in API endpoints
We will start this journey by building a simple server that accepts incoming HTTP requests.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files, as well as the server code we created in Chapter 3, are included in the downloadable code bundle.
Launching a basic web server
Section titled “Launching a basic web server”In this section, we are merely going to get an Actix server running using the Actix Web framework before connecting our server to our core code.
Why Actix Web?
Section titled “Why Actix Web?”This is now the third edition of the book. Several people have emailed me asking about a range of different web frameworks. The truth is, the choice of framework is close to trivial when it comes to implementing the API of that web framework. If you structure your code well, you should be able to switch these frameworks with minimal effort. Throughout this book, we will structure our code so we can use multiple different web frameworks at the same time. Actix is chosen for the book because we must choose one framework to demonstrate web programming concepts, and Actix is the most mature and stable web framework at the time of writing this book.
The GitHub repository of this book will also have the implementations of Axum, Rocket, and Hyper, but they will not be covered directly in the book to avoid bloat. However, the concepts covered will be the same, with the same file structure. This book will highlight differences in the other frameworks when they come up, but you will have to visit the GitHub repository for the full code examples.
Before we write any code, we must define our file layout.
Defining our file layout
Section titled “Defining our file layout”For our server, we are going to create a networking layer for our to-do nanoservice and put a Cargo project for our Actix server in that networking layer directory. With our server module, the file layout for our nanoservice should take the following form:
With this new layout, the Cargo.toml file at the root of our project should have the following work-spaces defined:
File: ./Cargo.toml
Section titled “File: ./Cargo.toml”[workspace]resolver = "2"members = [ "to_do/core", "to_do/dal", "to_do/networking/actix_server"]Declaring all the workspaces in the root Cargo.toml file enables us to run a cargo command in the root of our system, and have this cargo command apply to all the workspaces at the same time. The workspaces also help IDEs map the code when performing syntax highlighting and checking.
We are nearly finished with the boilerplate code. Before we write any server code, we need to define the server’s dependencies in the server Cargo.toml file with the following:
File: ./to_do/networking/actix_server/Cargo.toml
Section titled “File: ./to_do/networking/actix_server/Cargo.toml”[package]name = "to-do-actix-server"version = "0.1.0"edition = "2021"
[dependencies]tokio = { version = "1.36.0", features = ["full"] }actix-web = "4.9.0"We can now write our server main.rs file.
Writing our server code
Section titled “Writing our server code”We begin with the following structs and traits:
use actix_web::{web, App, HttpServer, Responder, HttpRequest};We will see how these structs and traits are used as and when we use them.
Recall from the previous chapter, servers typically handle incoming requests by passing these requests as async tasks into the async runtime to be handled. It should not be a surprise that our server API endpoint is an async task defined by the following code:
async fn greet(req: HttpRequest) -> impl Responder { let name = req.match_info().get("name").unwrap_or("World"); format!("Hello {}!", name)}With the preceding code, we can see that our API endpoint receives the HTTP request and returns anything that has implemented the Responder trait. We then extract the name from the endpoint of the URL or world string if the name is not in the URL endpoint. Our view then returns a string.
To see what we can automatically return as a response, we can check the Responder trait in the Actix Web docs and scroll down to the Implementations on Foreign Types section, as seen in Figure 5.1:
Implementations on Foreign Types
Section titled “Implementations on Foreign Types”[+] impl Responder for &‘static str
[+] impl Responder for &‘static [u8]
[+] impl Responder for &String
[+] impl Responder for Cow<’__, str>
[+] impl Responder for String
[+] impl Responder for Vec
[+] impl Responder for ResponseBuilder
[+] impl Responder for ByteString
[+] impl<R, E> Responder for Result<R, E>
where
R: Responder,
E: Into
[+] impl<R: Responder> Responder for (R, StatusCode)
[+] impl<R: Responder> Responder for Option
Figure 5.1 – Implementations of Foreign types [Source: Actix Web (2024), https://docs.rs/actix-web/latest/actix_web/trait.Responder.html#foreign-impls]
Figure 5.1 shows that we can essentially return strings and bytes as a response to the HTTP request. Now that we have our API endpoint, we can build our server with the following code:
#[tokio::main]async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .route("/", web::get().to(greet)) .route("/{name}", web::get().to(greet)) .route("/say/hello", web::get().to(||[figure outside: Figure 5.1]
async { “Hello Again!” }))
}).workers(4).bind("127.0.0.1:8080")?.run().await
}In the preceding code, we can see that we are running HttpServer after constructing it using the HttpServer::new function. Knowing what we know now, we can see that we have passed in a closure that returns and the App struct. We can see that we have used several different ways to define a view. We defined a view by building a function or an async closure. We assign the greet function that we have created to our application server as the route view with the .route(”/”, web::get().to(greet)) command. We also see that we can pass in the name from the URL to our greet function with the .route(”/{name}”, web::get().to(greet)) command. Finally, we pass in a closure into the final route. All of this enables us to route incoming requests to the right function to be processed, depending on the URL and HTTP method. Our server is now ready to run.
Running our server
Section titled “Running our server”With our configuration, let’s say we run the following command:
cargo run -p to-do-actix-serverThe -p parameter tells Cargo which Cargo workspace to run. Running our server workspace gives us the following printout:
Finished dev [unoptimized + debuginfo] target(s) in 0.21s
Running target/debug/to-do-actix-server
We can see in the preceding output that, right now, there is no logging, but we are running a basic web server. This is expected, and we will configure logging later.
Now that our server is running, we should expect the following URL inputs and outputs on the browser:
http://127.0.0.1:8080/ Hello World!
http://127.0.0.1:8080/Maxwell Hello Maxwell!
http://127.0.0.1:8080/say/hello Hello Again!
And there we have it! If you have cloned the Github repository, we can run the Axum version of this server with the following command: cargo run -p to-do-axum-server
You can run the Rocket server with the following command: cargo run -p to-do-rocket-server
We can see with the Rocket example that logging is already configured. Rocket is basically a “batteries included” framework where things like logging are already set up.
You can run the Hyper server with the following command: cargo run -p to-do-hyper-server
Our server is running, but it is also isolated. In the next section, we are going to connect our server to the core module.
Connecting the core to the server
Section titled “Connecting the core to the server”When it comes to connecting our networking layer to our core layer, we map our api modules on both the core and networking layers in the same way to avoid confusion.
Defining our core file layout
Section titled “Defining our core file layout”To map both layers, we must add the following new files for the core:
└─ to_do └─ core └─ src ├── api │ ├── basic_actions │ ├── create.rs │ ├── delete.rs │ ├── get.rs │ ├── mod.rs │ └── update.rs └── mod.rs ├── lib.rs └── ...We can see that we are adding a file for each basic action that we expect to perform on a to-do task. Also, note that we added a src/lib.rs file. This turns our core module into a lib so it can be mounted into the networking applications. The networking layer will interact with the core module through the src/lib.rs file.
If we wanted to, we could now delete the src/main.rs file as our core module now has a lib interface. However, we will be using this for a quick test later in the chapter, so hold onto the file until that test is done.
The module file in the basic actions module now takes the following form:
pub mod create;pub mod get;pub mod delete;pub mod update;We are keeping the files public as we want the src/lib.rs file to expose them to another workspace that uses our core module, with the following code:
pub mod api;pub mod structs;pub mod enums;Our core module is now ready to be used in other Cargo workspaces.
For our server to accommodate our core module, we need to add the following files to our networking layer that will interact with our core layer. This networking layer essentially gets an HTTP request, processes that request, and feeds the extracted data from the HTTP request into the core functions:
to_do networking actix_server … src api basic_actions create.rs delete.rs get.rs mod.rs update.rs mod.rs main.rs
Here, we are keeping our main.rs file because this Cargo workspace is not going to be used elsewhere yet. However, we are going to be using the main.rs file to run the server. With our files defined, we can now move on to coding our networking layer
Coding our networking layer
Section titled “Coding our networking layer”It should not be a surprise that the module file in the basic actions takes the following form:
pub mod create;pub mod get;pub mod delete;pub mod update;In the api module file, we expose the basic actions with the following code:
pub mod basic_actions;We declare the api module in our main.rs file with the following code:
...mod api;...All our code is now stitched up and ready to talk to each other. The only thing left to do is declare our core module in the Cargo.toml file with the following code:
#! File: to_do/networking/actix_server/Cargo.toml …
[dependencies]tokio = { version = "1.36.0", features = ["full"] }actix-web = "4.9.0"to-do-core = { path = "../../core" }We can see that our to-do-core dependency points to where the Cargo.toml file of the to-do-core module is, relative to the networking Cargo.toml file. Building with this relative path will result in an error if there is no Cargo.toml file with the package named to-do-core in that path. If the Cargo.toml file is situated in that relative path, the Rust code of the to-do-core module will be compiled into our networking layer and referenced just like any other dependency. We can now run a cargo build command. If the build passes, we know that everything is going to play nicely with each other. This is one of the many reasons why I love Rust. The compiler makes it hard for beginners to do basic things; however, when you start growing the complexity of your system, when the system compiles, you know that you are not going to get basic bugs in production. Wait, isn’t this over-engineered?
It is reasonable to have some alarm bells going off at what we have just done. Our nanoservice now consists of three Cargo workspaces, and all we have so far is a read and write to a basic JSON file, an isolated create function that talks to the JSON file, and an isolated server that just returns a couple of strings. We have produced a lot of files and directories just for this functionality.
While there is some utility to the term “over-engineered,” it is vague and is at risk of being abused. In my experience, a lot of people do not look at the bigger picture when accusing an approach of being over-engineered. As we stick with our approach, you will get to experience the flexibility that we have when running our application locally or on a server. The ease of swapping out layers so our nanoservice will be able to run as a microservice in its own Docker container, or just compile into another Cargo workspace, will prevent over-engineering in the future, as you will not have to run multiple Docker containers to develop against the entire system. And as systems get bigger with multiple developers and teams, trust me, you will thank your past self that you took this approach.
Now that everything is compiling, we can move on to serving our to-do items, but we might need to refactor them first.
Refactoring our to-do items
If we want to serve our to-do items, we need to get our server to talk to our core, which will then get all the to-do items from our JSON file. Right now, just to represent either a pending or a done item, we need to navigate between three structs. Our TaskStatus enum handles the logic and serialization of the status of these structs.
Now is a good time to look at the structs in our core module and have a quick think on how you could represent them in a single vector to be displayed in the browser.
If you did try and work out how to convert the to-do items into a single vector, you may have considered wrapping the items in an enum and then implementing a serialization trait to display these to-do items. This is like how we handle the writing of the to-do item to a file. However, this is a good time to listen to those alarm bells. We are having to do a lot of work to handle a variance in a status title. This complexity does not give us any advantages, so we need to act now to prevent this over-engineered approach from getting more embedded into our system, as it will be harder to rip out the longer we leave it. David Farley (author of the book Modern Software Engineering) says, “the outcome of a surgical procedure is not better or safer because the surgeon uses a blunt knife.” Likewise, we do not have a safe system because we do not touch or change chunks of our code. In fact, it’s the opposite. A sign of a safe, well-designed system that is handled by skilled engineers is the ability to confidently change chunks of the system as we find out more, and still manage to keep the system stable. Right now, let us retreat to a safer, simpler position so the handling of our to-do items is easier to manage. We can do this by completely ripping out the to_do/core/src/structs/ directory and replacing it with a to_do/core/src/structs.rs file. Inside this file, we can define a to-do item with the following code:
use std::fmt;use serde::{Serialize, Deserialize};use crate::enums::TaskStatus;
#[derive(Serialize, Deserialize, Debug, Clone)]pub struct ToDoItem { pub title: String, pub status: TaskStatus}We can directly implement the serialization traits because our TaskStatus enum has already implemented them. We also want our ToDoItem struct to print out in the same way our enum wrapping our two different previous structs did so; we can do this by implanting the Display trait with the following code:
impl fmt::Display for ToDoItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.status { TaskStatus::PENDING => write!( f, "Pending: {}", self.title ), TaskStatus::DONE => write!( f, "Done: {}", self.title ), } }}We now only need to refactor our create api function with the following code:
use crate::enums::TaskStatus;use crate::structs::ToDoItem;
#[cfg(feature = "json-file-storage")]use to_do_dal::json_file::save_one;
pub fn create(title: &str, status: TaskStatus) -> Result<ToDoItem, String> { let item = ToDoItem { title: title.to_string(), status }; let _ = save_one(&title.to_string(), &item)?; Ok(item)}We can see that the create function is simpler than our previous implementation.
If you kept the src/main.rs file, we can clear our tasks.json file so that we have the same file contents after running the following commands test our program:
cargo run -- --title washing --status pendingcargo run -- --title coding --status doneWe can then check our tasks.json JSON file, which should have the following content:
{ "coding": { "title": "coding", "status": "DONE" }, "washing": { "title": "washing", "status": "PENDING" }}Here, we see that we still can access the task with the title as the key, but the corresponding values contain the title and status of the task. We did not change any of the code in the data access layer. Instead, we are seeing how our to-do items are serialized. We are now ready to return all our to-do items to the browser.
Make sure that you keep the task.json file in the root of the entire project, next to the Cargo.toml file that defines the workspaces. We will use this JSON file for testing our get API endpoint.
Serving our to-do items
Section titled “Serving our to-do items”We are now at the stage of serving all our items to the browser. However, before we touch any of the server code, we need to add another struct from our core module. We can start by defining the JSON body.
Defining the JSON body
Section titled “Defining the JSON body”We need a container that houses two lists of items for the pending and done items, which takes the following form:
use std::collections::HashMap;...#[derive(Serialize, Deserialize, Debug, Clone)]pub struct AllToDoItems { pub pending: Vec<ToDoItem>, pub done: Vec<ToDoItem>}This struct enables us to structure the entire state of the to-do items and also serialize and deserialize the state, letting us save/load to JSON files, and also send data to the browser.
You might recall that we load the data from the JSON file in a HashMap form, meaning that we are going to need a from_hashmap function for our AllToDoItems struct. We can add this with the following code:
impl AllToDoItems { pub fn from_hashmap(all_items: HashMap<String, ToDoItem>) -> AllToDoItems { let mut pending = Vec::new(); let mut done = Vec::new();
for (_, item) in all_items { match item.status { TaskStatus::PENDING => pending.push(item), TaskStatus::DONE => done.push(item) } } AllToDoItems { pending, done } }}We can now utilize our new container struct by building our get_all API function.
Defining the get all API
Section titled “Defining the get all API”Our get_all function is defined with the following code:
use to_do_dal::json_file::get_all as get_all_handle;use crate::structs::{ ToDoItem, AllToDoItems};pub async fn get_all() -> Result<AllToDoItems, String> { Ok(AllToDoItems::from_hashmap( get_all_handle::<ToDoItem>()? ))}Wow, there is not much code there. However, we can see what type of data is being loaded as the value of the hashmap with the get_all_handle::
Here, our core API function is fusing the logic of the core module and the data access layer. The data from our core API function is then passed to the Actix API function, which can then return the data to the browser, as seen in Figure 5.2:
Figure 5.2 – Pathway for getting all to-do items
[figure outside: Figure 5.2]
We can now build our Actix API function with the following code:
//! File: to_do/networking/actix_server//! /src/api/basic_actions/get.rsuse to_do_core::api::basic_actions::get::get_all as get_all_core;use actix_web::HttpResponse;
pub async fn get_all() -> HttpResponse { let all_items = match get_all_core().await { Ok(items) => items, Err(e) => return HttpResponse::InternalServerError().json(e), }; HttpResponse::Ok().json(all_items)}We can see that we are renaming the core function that we import with a _core. This is just to make it easier on the eye. When another developer looks at the code, they will know exactly where the calls to the core are happening.
The match statement here does bloat the code a little bit, but we will handle this in the next section. We can see that if there is any error, we return it with an internal server error response code.
We now must connect our get_all async function to our server.
Connecting get_all to our server
Section titled “Connecting get_all to our server”We should keep our API module endpoint definitions isolated, as we want to be able to version control the different API modules. We can define the get_all URI with the following code:
//! File: to_do/networking/actix_server//! /src/api/basic_actions/mod.rs...use actix_web::web::{ServiceConfig, get, scope};
pub fn basic_actions_factory(app: &mut ServiceConfig) { app.service( scope("/api/v1") .route("get/all", get().to(get::get_all)) );}In the preceding code, our function is called a factory. A factory is a standard design pattern where objects are constructed or things are configured. In our factory pattern, we are assembling API endpoints and attaching them to our ServiceConfig struct, which is going to be mounted to the server. Factories are often used to encapsulate object creation or setup logic. For our factory function, we can see that we pass in a mutable reference of a ServiceConfig struct. This struct allows bigger applications to split up configuration into different files, and it enables us to define things like views to the server in different fields. We then apply a service to the ServiceConfig struct.
We should define all backend API endpoints with “/api/” to differentiate backend endpoints from the frontend endpoints. We also have “/v1/” to facilitate versioning.
When there are breaking changes to the API, we should keep the previous version, but put the new breaking change API in the new version. We then alert users about the update in the version and give a date as to when the lower version will no longer be supported or removed.
Now that we have defined our endpoint factory for our basic actions, we need one last factory that collects all the other factories and calls them with the following code:
pub mod basic_actions;use actix_web::web::ServiceConfig;
pub fn views_factory(app: &mut ServiceConfig) { basic_actions::basic_actions_factory(app);}With this, we only need to configure our server with our views factory. We do this with the following code:
#[tokio::main]async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new().configure(api::views_factory) }) .workers(4) .bind("127.0.0.1:8080")? .run() .await}We see that we have defined the number of workers here. Workers are processes that have their own state and a copy of the application. They run by themselves with no concurrency issues, and the incoming requests are distributed between these workers. By default, the number of workers is the number of CPUs available. If we run our server and hit our endpoint in the browser, we get the result seen in Figure 5.3:
Figure 5.3 – Return data from the get all API endpoint
And there we have it; our server is now returning the to-do items in a sorted fashion. However, remember that we were relying on a match statement in our web API function? We can reduce the need for this by defining our own error handling so we can exploit the ? operator in our API function.
You can see in the GitHub repository how we handle different API endpoints for the following web frameworks:
- Axum: Our views factory is the same as for Actix Web; however, we pass in a Router as opposed to a ServiceConfig, and we return the Router struct from the factory with the new API endpoints added.
- Rocket: The views factory returns routes![] with the routes inside the square brackets. This macro is then mounted to the server using the .mount(“/api/v1”, basic_actions_factory()); function. A macro above the API function itself defines the method and the last part of the URI.
- Hyper: Because Hyper is more low-level, we have a general handle function that accepts the incoming HTTP request. We then extract the URI and method, and match the method and URI using a match statement, passing the HTTP request to the mapped function.
We have nearly wrapped up this chapter. We just need to handle errors for the web server API function.
[figure outside: Figure 5.3]
Handling errors in API endpoints
Section titled “Handling errors in API endpoints”We are at the final hurdle of this chapter, where we want to get rid of the match statement in our API functions for our server. The match statement is a result of us handling an error. As our server grows, we would have to repeat the clunky handling of errors again and again, and there is a risk that we could mishandle the error. To prevent having to manually handle the errors for every API endpoint, we can bake the HTTP responses into our error handling. To do this, we can create an error type that can construct an HTTP response, so we can exploit the ? operator in our web API function, and the server will simply respond with an HTTP response. However, this means that all our Cargo workspaces need to share the same custom error types. This is where a glue module will come in. A glue module is a crate that all other workspaces install. With this glue module, all Cargo workspaces can seamlessly pass the same error type between each other.
Glue modules can help us pass the same data types between different crates so they can communicate more effectively. We see this in Figure 5.4, where we can see that the different layers can pass errors between each other because every layer is referencing the error struct from the glue module.
Figure 5.4 – Glue module enabling layers to pass errors between each other
It does not stop there. Throughout the book, we will build another server, which is the authentication server, to log in and manage authentication sessions for users. The authentication server will have a dal, core, and networking layer. Throughout the book, we will cover how to deploy servers separately. Because we have the layers, we will also cover how to compile the auth server into the to-do server binary. This enables the to-do server to directly call the auth core API functions because the auth server will also reference structs such as errors from the same glue module.
[figure outside: Figure 5.4]
This is why I decided to call it a glue module, because it enables any of our systems to compile into each other and pass structs such as errors or auth tokens between each other. When rewriting the Rust Kubernetes cluster with Caroline Morton for the third time, we found that having a glue module helped with upgrading tens of servers, enabling them to talk to each other and compile together. Because certain packages were used in the glue module, we only had to update the package in the glue module, and all servers got the update.
Now that we understand the power that we get from a glue module, we can code our glue module.
Defining our glue module
Section titled “Defining our glue module”Before we create our glue module, we must appreciate what is happening to our whole system. Our nanoservice is just sitting there. If we put the glue module next to our nanoservice, then it can get confusing as to what is what. To reduce the risk of confusion, we need to shift our nanoservice into its own directory called nanoservices. The nanoservices directory is where we will put other nano-services, such as the authentication service.
Considering that the glue module is to be used everywhere, we can put the glue module in the root, giving us the following Cargo.toml file in our root:
[workspace]resolver = "2"members = [ "glue", "nanoservices/to_do/core", "nanoservices/to_do/dal", "nanoservices/to_do/networking/actix_server"]Our glue module should have the file following layout:
glue ├── Cargo.toml └── src ├── errors.rs └── lib.rs
We can now define the Cargo.toml file of the glue module with the following code:
File: glue/Cargo.toml
Section titled “File: glue/Cargo.toml”[package]name = "glue"version = "0.1.0"edition = "2021"[dependencies]actix-web = { version = "4.9.0", optional = true }serde = { version = "1.0.197", features = ["derive"] }thiserror = "1.0.58"[features]actix = ["actix-web"]Here, we can see that the actix-web dependency is optional and only used if the actix feature is enabled. This is because we only want to compile Actix Web if we are directly mapping the error in the Actix server. There is no need for the core or data access layers to rely on the actix-web dependency. In the future, we can add features of other web frameworks as and when we need them.
In the lib.rs file of the glue module, we make the errors publicly available with the following code:
pub mod errors;We can now move on to our error definitions in our src/errors.rs file.
Building our custom error
Section titled “Building our custom error”First, we are going to need the following structs and traits:
use serde::{Deserialize, Serialize};use thiserror::Error;use std::fmt;
#[cfg(feature = "actix")]use actix_web::{ HttpResponse, error::ResponseError, http::StatusCode};Note that we are only using the actix-web dependency if the actix feature is enabled.
We can now define the different statuses that the error can respond with using the following code:
#[derive(Error, Debug, Serialize, Deserialize, PartialEq)]pub enum NanoServiceErrorStatus { #[error("Requested resource was not found")] NotFound, #[error("You are forbidden to access requested resource.")]}Forbidden, #[error(“Unknown Internal Error”)] Unknown, #[error(“Bad Request”)] BadRequest, #[error(“Conflict”)] Conflict, #[error(“Unauthorized”)] Unauthorized
The #[error(“something”)] derive macro essentially implements the Display trait for our enum. If a field is decorated with #[error(“something”)], then that field will display a “something” when the Display trait is utilized.
We can now define our nanoservice error with the following code:
#[derive(Serialize, Deserialize, Debug, Error)]pub struct NanoServiceError { pub message: String, pub status: NanoServiceErrorStatus}impl NanoServiceError { pub fn new(message: String, status: NanoServiceErrorStatus) -> NanoServiceError { -> NanoServiceError { NanoServiceError { message, status } } }}Next, we need to implement a response trait for our nanoservice error. We start by implementing the Display trait for our nanoservice error with the following code:
impl fmt::Display for NanoServiceError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.message) }}And with this, we can now implement the ResponseError trait for the nanoservice error. We do this with the following code:
#[cfg(feature = "actix")]impl ResponseError for NanoServiceError { fn status_code(&self) -> StatusCode { ... } fn error_response(&self) -> HttpResponse { ... }}Implementing the ResponseError trait for our NanoServiceError struct enables the NanoServiceError to be converted into an HTTP response with a message and error code. This means that in our networking layer, if our core function returns an error, we can just send that error directly back to the client!
For our status code function, we need to merely map our status number with the Actix Web status code, as follows:
fn status_code(&self) -> StatusCode { match self.status { NanoServiceErrorStatus::NotFound => StatusCode::NOT_FOUND, NanoServiceErrorStatus::Forbidden => StatusCode::FORBIDDEN, NanoServiceErrorStatus::Unknown => StatusCode::INTERNAL_SERVER_ERROR, NanoServiceErrorStatus::BadRequest => StatusCode::BAD_REQUEST, NanoServiceErrorStatus::Conflict => StatusCode::CONFLICT, NanoServiceErrorStatus::Unauthorized => StatusCode::UNAUTHORIZED }}For our error response function, we need to construct an HTTP response from our status and message with the following code:
fn error_response(&self) -> HttpResponse {let status_code = self.status_code();HttpResponse::build(status_code).json(self.message.clone())}And our error can now construct an HTTP response.
For the other web frameworks, we can implement the following traits for our custom error:
- Axum: IntoResponse trait
- Hyper: A custom trait that just converts to a response
- Rocket: Responder trait
You can see these implementations in the GitHub repository for this chapter in the errors file of the glue module. Each implementation is guarded by a feature flag, meaning that you do not have to install dependencies of other frameworks, just the framework you choose.
Our custom error is now ready to be used. We now need to build some macros to help us map the errors in our system.
Mapping our custom error
Section titled “Mapping our custom error”We know that there are functions that return different types of errors that are out of our control. For instance, reading a file would rely on functions that we did not write. The file reading functions could return errors such as an I/O error. This is where the map_err function comes in. Basically, the map_err function converts one type of error into another type of error. For example, if we were to open a file, we could map the potential error of that file open operation to a nanoservice error with the following code:
let mut file = File::open(&path).map_err(|err| NanoServiceError::new( format!( "Failed to open file: {} - {}", path.as_ref().display(), err ), NanoServiceErrorStatus::Unknown, ))?;However, we do not want to have to write the map_err function every time we want to convert an error to a nanoservice error. We can prevent repetitive code with the following macro:
#[macro_export]macro_rules! safe_eject { ($e:expr, $err_status:expr) => { $e.map_err(|x| NanoServiceError::new(
x.to_string(), $err_status) ) }; ($e:expr, $err_status:expr, $message_context:expr) => { $e.map_err(|x| NanoServiceError::new( format!("{}: {}", $message_context, x.to_string()), $err_status ) ) };}Here, we can see that there are two arms to the macro. These arms are defined by the (…) => pattern. If we just pass in the expression to be mapped and the error status, the first branch will be triggered, and we will map the error message to the nanoservice error. However, if we pass in the expression to be mapped, the status, and a message, the second arm will be triggered, and the macro will add extra context to the error message, letting us know where the error is happening. This will save us from repeating ourselves.
We can now see how our errors are implemented. There is going to be a fair bit of refactoring, but it is better to correct all this now than later, where the refactor will require more work. Also, we will get some experience with what refactoring code feels like in our Rust system. We can start with our data access module.
Integrating our glue module into our dal
Section titled “Integrating our glue module into our dal”In this section, we are going to be importing our glue module into the data access layer of the to-do service so we can implement our errors. In the data access Cargo.toml file, we add the following dependency:
File: nanoservices/to_do/dal/Cargo.toml
Section titled “File: nanoservices/to_do/dal/Cargo.toml”[dependencies] ... glue = { path = "../../../glue"}We then use our error structs and macros in our json_file.rs file with the following code:
File: nanoservices/to_do/dal/src/json_file.rs
Section titled “File: nanoservices/to_do/dal/src/json_file.rs” ... use glue::errors::{ NanoServiceError, NanoServiceErrorStatus }; use glue::safe_eject;With this, we can now replace all our String error return types with our nanoservices error. For instance, our handle function takes the following form:
fn get_handle(path: Option<&str>) -> Result<File, NanoServiceError>{ let path = match path { Some(p) => p, None => { &env::var("JSON_STORE_PATH").unwrap_or( "./tasks.json".to_string() ) } }; safe_eject!(OpenOptions::new() .read(true) .write(true) .create(true) .open(&path), NanoServiceErrorStatus::Unknown, "Error writing tasks to JSON to file" )}Here, we can see that getting our file handle is more robust. Our macro converts the error of getting the file handle into a NanoServiceError error. We can also see that we add context to the error, so if this error is returned, we know it is to do with the JSON file. Our get_all function is now defined with the following code:
pub fn get_all<T: DeserializeOwned>() -> Result<HashMap<String, T>, NanoServiceError> { let mut file = get_handle(None)?; let mut contents = String::new(); safe_eject!( file.read_to_string(&mut contents), NanoServiceErrorStatus::Unknown, "Error reading JSON file to get all tasks" )?; let tasks: HashMap<String, T> = safe_eject!( serde_json::from_str(&contents), NanoServiceErrorStatus::Unknown, "Error parsing JSON file" )?;Ok(tasks)}It must be noted before you run anything that the core layer has not been updated to return a NanoServiceError yet. If you try and compile the entire system, you will get an error. Right now, you will not be able to compile the entire system until we have updated the error signatures of the core and networking layers. We can see how our safe_eject! macro lifts out the repetitive code, and we just focus on defining the expression to be evaluated, the error status, and the optional context message of where the error is happening, which will be presented alongside the error message. Our safe_eject! macro is mainly used for third-party results, as we aim for all our functions to return the nanoservice error.
For the save_all function, we have the following code:
pub fn save_all<T: Serialize>(tasks: &HashMap<String, T>) -> Result<(), NanoServiceError> { let mut file = get_handle(None)?; let json = safe_eject!( serde_json::to_string_pretty(tasks), NanoServiceErrorStatus::Unknown, "Error serializing JSON before saving tasks" )?; safe_eject!( file.write_all(json.as_bytes()), NanoServiceErrorStatus::Unknown, "Error writing tasks to JSON to file" )?; Ok(())}Our get_one function takes the following form:
pub fn get_one<T: DeserializeOwned + Clone>(id: &str) -> Result<T, NanoServiceError> { let tasks = get_all::<T>()?; match tasks.get(id) { Some(t) => Ok(t.clone()), None => Err( NanoServiceError::new( format!( "Task with id {} not found", id ) ) ) }}),NanoServiceErrorStatus::Unknown))}}We then build our save_one function with the following code:
pub fn save_one<T>(id: &str, task: &T) -> Result<(), NanoServiceError>where T: Serialize + DeserializeOwned + Clone,{ let mut tasks = get_all::<T>().unwrap_or_else( |_| HashMap::new() ); tasks.insert(id.to_string(), task.clone()); save_all(&tasks)}And finally, the delete_one function takes the following form:
pub fn delete_one<T>(id: &str) -> Result<(), NanoServiceError>where T: Serialize + DeserializeOwned + Clone,{ let mut tasks = get_all::<T>().unwrap_or(HashMap::new()); tasks.remove(id); save_all(&tasks)}With this, our data access layer is ready to be used by our core layer.
Integrating our glue module into our core layer
Section titled “Integrating our glue module into our core layer”For our core layer, we add the following dependency:
File: nanoservices/to_do/core/Cargo.toml
Section titled “File: nanoservices/to_do/core/Cargo.toml”[dependencies] … glue = { path = ”../../../glue”}
For our create API endpoint, we just need to update the signature of the create function to return the NanoServiceError with the following code:
//! nanoservices/to_do/core/src//! /api/basic_actions/create.rs...use glue::errors::NanoServiceError;
pub fn create(title: &str, status: TaskStatus) -> Result<ToDoItem, NanoServiceError> { ...}We also do the same with our get function, with the following code:
//! nanoservices/to_do/core/src//! /api/basic_actions/get.rs...use glue::errors::NanoServiceError;
pub async fn get_all() -> Result<AllToDoItems, NanoServiceError> { ...}Our endpoints are now supported; however, we also must get main working as well. This means our TaskStatus supports NanoServiceError with the following code:
//! nanoservices/to_do/core/src/enums.rs...use glue::errors::NanoServiceError;...impl TaskStatus {
pub fn from_string(status: &String) -> Result<TaskStatus, NanoServiceError> { match status.to_uppercase().as_str() { "DONE" => Ok(TaskStatus::DONE), "PENDING" => Ok(TaskStatus::PENDING), _ => Err( NanoServiceError::new( "Invalid status".to_string(), NanoServiceErrorStatus::BadRequest ) ) } }And finally, our main function has the following signature:
//! nanoservices/to_do/core/src/main.rs//...use glue::errors::NanoServiceError;//...fn main() -> Result<(), NanoServiceError> { // ... Ok(())}Our core layer is now ready, so finally, we can configure our networking.
Integrating our glue module into our networking layer
Section titled “Integrating our glue module into our networking layer”Unlike the core and dal layers, we will have the Actix feature for our glue package with the following Cargo.toml file code:
glue = { path = "../../../../glue", features = ["actix"] }With our glue package, our create function file for our API endpoint takes the following form:
//! File: nanoservices/to_do/networking/actix_server///! src/api/basic_actions/get.rsuse core::api::basic_actions::get::get_all as get_all_core;use actix_web::HttpResponse;use glue::errors::NanoServiceError;
pub async fn get_all() -> Result<HttpResponse, NanoServiceError> { Ok(HttpResponse::Ok().json(get_all_core().await?))}And that is it! I appreciate that there has been a fair amount of reworking with the juggling of multiple workspaces. However, the hard, tedious parts are now done. Adding new API endpoints from now on is going to be simple. Slotting in new nanoservices and layers will also be effortless. With this in mind, we are ready to move on to our next chapter of processing HTTP requests.
Summary In this chapter, we built a functioning nanoservice that has a core layer, a data access layer, and a networking layer. While getting there took a bit of refactoring, our work resulted in a well-structured server where all the layers compile together to be served by the networking layer. To aid in error handling, we also built a glue module that was used by all layers, enabling us to propagate the same error type through all the layers in the nanoservice. At this stage, slotting in other web frameworks or data storage approaches is as simple as creating another Cargo workspace in the networking layer, or another feature in the data access layer.
Also in this chapter, we chained factories to enable our views to be constructed on the fly and added to the server. With this chained factory mechanism, we can slot entire view modules in and out of the configuration when the server is being built.
In the next chapter, we will work with processing requests and responses. We will learn how to pass parameters, bodies, headers, and forms to views and process them, returning JSON. We will be using these new methods with the to-do module we built in Chapter 3 to enable our interaction with to-do items to be achieved through server views.
Questions
- What parameter is passed into the HttpServer: :new function, and what does the parameter return?
- How can we work out what data types an API function can return automatically?
- How can we enable data handling across all Cargo workspaces, including the HTTP response?
- Why is it a good idea to have /api/v1 in the endpoint of the URL?
- How can we support multiple dependencies but be selective on what dependencies we compile, depending on our needs, such as networking dependencies?
- For our networking API endpoints, we have view factories that are chained into the main API factory. What is the advantage of chaining factories?
Answers
-
A closure is passed into the function. It has to return the App struct so the bind and run func-tions can be acted on after the HttpServer: :new function has fired.
-
We can look at the documentation for the Responder trait to see which data types have implemented the Responder trait.
-
We create a separate Cargo workspace where we define an error struct. All other workspaces can then compile this workspace as a dependency and return the error struct as the error type. For the HTTP response, we need to implement the ResponseError for our error.
-
The api part of the URL enables us to differentiate between frontend and backend HTTP re-quests. The v1 part enables us to version control the API endpoint and enables us to support multiple versions.
-
We can use features. For example, we can define a dependency as optional and state that this dependency is used if we use a feature that we tether to that dependency. We can then optionally compile the #[cfg(feature = “some-feature”)] code.
-
Chaining factories gives us flexibility on how individual modules are constructed and how they are orchestrated. The factory inside the module focuses on how the module is constructed, and the factory outside the module focuses on how the different modules are orchestrated. This isolation enables us to swap out modules, as all the logic is maintained in the module. Chaining factories also enables us to keep bloat to a minimum. For instance, our main.rs file only focuses on the running of the server, and is not overrun by mapping URL endpoints.
Get this book’s PDF copy, code bundle, and more
Section titled “Get this book’s PDF copy, code bundle, and more”Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
UNLOCK NOW
Note: Have your invoice handy. Purchases made directly from the Packt website don’t require an invoice.