Building High Performance Web Services with
Rust and Rocket
@sebasmagri - May, 2017
Agenda
- ¿APIs?
- How much Rust do you need in your Rocket?
- What is Rocket anyway?
- Hands on
- Further references
What's a Web API?
Fundamentals
API
Application Programmer Interface
+
Web
Protocols and Technologies you can use when building apps for the Web
Some styles/patterns
- SOA
- RPC
- Whatever.
- REST
REST
-
Resources
- URIs o Identificadores
- Representations of its states
- HTTP Verbs
Some Rusty tools for Web Development
- Frameworks
- Iron, Nickel, Pencil, Rocket
- Database / Persistance support
- Content types and formats
How much Rust should I know to build Web APIs with Rocket?
The Rust Tenets
Safety
Concurrence
Performance
Structs
Enums
Data
struct LoadAvg {
last1: f64,
last5: f64,
last15: f64
}
...
let load_avg = LoadAvg {
last1: 0.36,
last5: 0.71,
last15: 1.1
}
...
println!("{}", load_avg.last1)
enum Gender {
Male,
Female,
Other
}
...
struct Person {
name: String,
age: i32,
gender: Gender
}
...
let p = Person {
name: "Sebastián".to_string(),
age: 15,
gender: Gender::Male
}
Type descriptions
Multiple options types
Safety
Ownership | Borrowing | Lifetimes |
---|
Rust provides mechanisms to handle memory safely in an automatic fashion.
Ownership and Lifetimes
Principles of the ownership system
- Any value can be used a single time. After its first use it gets moved to a new location and becomes unusable from its previous one.
- Every value is destroyed automatically at the end of its lifetime.
- A code block can return a value, giving away its ownership to the upper block.
- Every value gets a lifetime which defines its scope and automatic drop.
Borrowing
Principles of the borrow checker(TM)
AKA: The ownership cop
- There can only exist a single one mutable reference to a value at any single time.
- There can only be as much immutable references as you need.
- You can't mix mutable and immutable references at a single time.
Rocket
A Web Framework for Rust, focused on simplicity, performance, flexibility and safe data handling.
https://rocket.rs/
Routes
Rocket uses data attributes to indicate which functions handle specific requests.
These attributes allow the definition of the request method, the route and response content type.
#[get("/")]
fn home() -> String { ... }
#[post("/news", data = "<entry>")]
fn new(entry: Entry) -> String { ... }
#[head("/news")]
fn head() -> String { ... }
#[get("/news")]
fn entries() -> String { ... }
#[get("/news/<id>")]
fn entrie(id: i32) -> String { ... }
#[put("/news/<id>", data = "<entry>")]
fn update(entry: Entry) -> String { ... }
#[patch("/news/<id>", data = "<entry>")]
fn update_partial(id: i32, entry: Entry) -> ...
#[route(OPTIONS, "/news")]
fn options() -> String { ... }
Handlers
Handles will get requests that match all the given preconditions and will generate a response for clients based on the given parameters.
#[get("/")]
fn hello() -> String {
"Hello World".to_string()
}
// URL path parameters
#[get("/<name>")]
fn home(name: &str) -> String {
format!("Hello {}!", name)
}
// Body parameters
#[post("/login", data = "<user_form>")]
fn login(user_form: Form<UserLogin>) -> String {
// Use `user_form`, return a String.
}
// ## Request Guards
// Request requirements
#[get("/sensitive")]
fn sensitive(key: APIKey) -> &'static str { ... }
Responders
Responder is a trait provided by Rocket that will convert the handler's return data type into a HTTP response.
struct SystemLoad {
last1: f32,
last5: f32,
last15: f32
}
impl<'r, R: Responder<'r>> Responder<'r> for SystemLoad { ... }
#[get("/")]
fn hello() -> T {
"Hello World".to_string()
}
Application boot up
In the boot up process, Rocket is going to mount the routes it should handle and it's going to start a Web Server ready to get requests.
rocket::ignite()
.mount("/base", routes![index, another])
.launch()
...
🚀 Rocket has launched from http://localhost:8000...
Hands on...
Final references
- Workshop repo: https://github.com/sebasmagri/rocket-loadavg-api
- The Rust Book: https://doc.rust-lang.org/stable/book/
- Crates docs: https://docs.rs/
- Rocket's Guide: https://rocket.rs/guide
- Rocket's Examples: https://github.com/SergioBenitez/Rocket
- Rocket's IRC channel: #rocket@irc.mozilla.org
¡Thanks so much!
Be nice to each other.
Building High Performance Web Services with Rust and Rocket
By sebasmagri
Building High Performance Web Services with Rust and Rocket
- 790