ACTE I
La Promesse
TYPES · SERVEUR HTTP · AXUM
CE SOIR · EN UN NUMĂRO
Type-Driven Magic
dans les coulisses d'Axum
Igor Laboriegithub.com/ilaborie/axum-magic-types
ACTE I
TYPES · SERVEUR HTTP · AXUM
CE SOIR · EN UN NUMĂRO
dans les coulisses d'Axum
Igor Laboriegithub.com/ilaborie/axum-magic-types
@RestController
@RequestMapping("/shows")
public class ShowController {
@Autowired
private Stage stage;
@PostMapping("/{magician}/tricks")
public Rabbit performTrick(
@PathVariable String magician,
@RequestBody Trick trick) {
// ...
}
}
Router::new()
.route("/shows/{magician}/tricks",
post(perform_trick))
.with_state(Stage::new());
async fn perform_trick(
stage: State<Stage>,
magician: Path<String>,
trick: Json<Trick>,
) -> Result<Json<Rabbit>, EpicFailure> {
todo!("đȘđ©đ°")
}
EN COULISSES
Igor Laborie
Founding backend engineer
// Unit type ~ Void
()
// Tuple 1 T
(T,)
// Pair T1 Ă T2
(T1, T2)
// Tuple T1 Ă T2 Ă T3 Ă ...
(T1, T2, T3, ...)
struct Aether; // Singleton
struct Magician(i32); // ~ tuple nommé
// Record
struct Rabbit {
name: String,
color: RabbitColor,
}
Warning
â POO, pas d'hĂ©ritage en Rust !
enum RabbitColor {
White,
Black,
}
// Pas de `null`, on utilise `Option`
enum Option<T> {
Some(T),
None,
}
// Pas d'exception, on utilise `Result`
enum Result<T, E> {
Ok(T),
Err(E),
}
Note
Ressemble aux tagged union, sealed class
impl RabbitColor {
// `self` correspond au `this`
// `Self` correspond au type, i.e. `RabbitColor`
fn is_late(&self) -> bool {
match self {
Self::White => true,
_ => false
}
}
}
Note
T on passe l'ownership de la valeur (move)&T on passe une référence partagé&mut T on passe une référence exclusive (ou mutable)trait FromHat {
fn pull(hat: &mut Hat) -> Result<Self, EpicFailure>;
}
impl FromHat for Rabbit {
fn pull(hat: &mut Hat) -> Result<Self, EpicFailure> {
hat.rabbits.pop().ok_or(EpicFailure)
}
}
fn perform<T>(hat: &mut Hat) -> Result<T, EpicFailure>
where
T: FromHat,
{
T::pull(hat)
}
Note
Orphan rule: on peut implémenter si c'est notre type, ou si c'est notre trait
// Server: une fonction asynchrone
type Server = fn(Request) -> Response;
// Route: prédicat & handler (verbe HTTP + chemin)
type Route = (fn(&Request) -> bool, Handler);
// Router: ensemble de routes
type Router = Trie<Route>;
// Handler: mĂȘme forme qu'un serveur
type Handler = fn(Request) -> Response;
// Middleware: un décorateur
type Middleware = fn(Handler) -> Handler;
axumhttps://github.com/tokio-rs/axum
| Crate | RĂŽle |
|---|---|
http |
types Request, Response, StatusCode, ... |
hyper |
implémentation HTTP/1.1 + HTTP/2 |
matchit |
router radix-tree |
tower |
Middlewares |
tokio |
moteur asynchrone (I/O non bloquantes) |
đ€ Mais alors qu'est-ce qu'il y a dans axum ?
ACTE II
HANDLERS · EXTRACTORS · EN DIRECT
Warning
tower)tokioasync fn serve(addr: SocketAddr, router: Router) -> Result {
let listener = TcpListener::bind(addr)?;
loop {
let tcp_stream = listener.accept().await?;
tokio::spawn(accept(tcp_stream, router));
}
}
Caution
Vue simplifiée, ne compile pas !
hyper + tokioasync fn accept(tcp_stream: TcpStream, router: Router) {
let service = service_fn(|req| dispatch(req, router));
Builder::new(TokioExecutor::new())
.serve_connection(tcp_stream, service)
.await;
}
async fn dispatch(req: Req, router: Router) -> Resp {
let Some(route) = router.at(req.path()) else {
return Resp::NOT_FOUND;
};
route.handler(req).await
}
Caution
Vue simplifiée, ne compile pas !
// T: les arguments de la fonction
// S: le state (context d'injection)
pub trait Handler<T, S>: Clone + Send + Sync + 'static {
fn call(self, req: Req, state: S) -> impl Future<Output = Resp> + Send;
}
// Implémentation pour une fonction sans paramÚtre
impl<F, S, Fut> Handler<(), S> for F
where
F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Resp> + Send,
S: Send + Clone,
{
async fn call(self, _req: Req, _state: S) -> Resp {
self().await
}
}
// examples/demo.rs
async fn hello() -> Resp { Resp::new("Hello World!") }
Router::new().route("/", hello)
pub trait FromRequest: Sized {
type Rejection: Debug;
fn from_request(req: Req)
-> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}
impl FromRequest for Method {
type Rejection = Infallible;
async fn from_request(req: Req) -> Result<Self, Self::Rejection> {
let (parts, _body) = req.into_parts();
Ok(parts.method)
}
}
impl<T: DeserializeOwned> FromRequest for Json<T> {
type Rejection = BoxedError;
async fn from_request(req: Req) -> Result<Self, Self::Rejection> {
let body = req.into_raw_body().await?;
Ok(Json(serde_json::from_slice(&body)?))
}
}
Note
Rejection est un type associé : l'erreur est choisie une fois par
le type qui implémente, et pas par le code qui appel.
Le type Method est définit dans la crate http, on peut implémenter des traits
pour les types externes - si on respect la orphan rule.
// Implémentation avec paramÚtre
impl<F, T, S, Fut> Handler<(T,), S> for F
where
F: FnOnce(T) -> Fut + Clone + Send + Sync + 'static,
T: FromRequest,
Fut: Future<Output = Resp> + Send,
S: Send + Clone,
{
async fn call(self, req: Req, _state: S) -> Resp {
let t = match T::from_request(req).await {
Ok(value) => value,
Err(err) => return Resp::from_rejection(err),
};
self(t).await
}
}
// examples/demo.rs
async fn get_mood(verb: Method) -> Resp { /* ... */ }
async fn fill_the_hat(Json(payload): Json<Value>) -> Resp { /* ... */ }
pub trait FromParts: Sized {
type Rejection: Debug;
fn from_parts(parts: &mut Parts) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}
impl FromParts for Method {
type Rejection = Infallible;
async fn from_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
Ok(parts.method.clone())
}
}
// Implémenter `FromParts` implémente automiatiquement `FromRequest`
impl<E> FromRequest for E
where
E: FromParts,
{
type Rejection = E::Rejection;
async fn from_request(req: Req) -> Result<Self, Self::Rejection> {
let (mut parts, _body) = req.into_parts();
Self::from_parts(&mut parts).await
}
}
Warning
Deux extracteurs ne peuvent pas consommer la requĂȘte (move).
Il faut 2 types d'extracteur: FromParts pour l'entĂȘte et FromRequest pour l'ensemble.
macro_rules! impl_handler {
($($t:ident),* ) => {
#[allow(non_snake_case, unused_mut )] // supprime les warnings
impl<F, $($t,)* Last, S, Fut> Handler<($($t,)* Last,), S> for F
where
F: FnOnce($($t,)* Last) -> Fut + Clone + Send + Sync + 'static,
$(
$t: FromParts + Send,
)*
Last: FromRequest + Send,
Fut: Future<Output = Resp> + Send,
S: Send + Clone,
{
async fn call(self, req: Req, _state: S) -> Resp {
let (mut parts, body) = req.into_parts();
$(
let $t = match $t::from_parts(&mut parts).await {
Ok(value) => value,
Err(err) => return Resp::from_rejection(err),
};
)*
let req = Req::from_parts(parts, body);
let last = match Last::from_request(req).await {
Ok(value) => value,
Err(err) => return Resp::from_rejection(err),
};
self($($t,)* last).await
}
}
};
}
impl_handler!();
impl_handler!(T);
impl_handler!(T1, T2);
impl_handler!(T1, T2, T3);
// ...
Note
Rust n'a pas (encore) de générique variadique : il faut une impl par nombre
d'arguments.
Les déclarative macro avec macro_rules! permet d'écrire facilement ces implémentations.
pub trait IntoResponse {
fn into_response(self) -> Resp;
}
impl IntoResponse for String {
fn into_response(self) -> Resp {
Resp::new(self)
}
}
impl<T, E> IntoResponse for Result<T, E>
where
T: IntoResponse,
E: IntoResponse,
{
fn into_response(self) -> Resp {
self.map_or_else(E::into_response, T::into_response)
}
}
-async fn hello() -> Resp {
- Resp::new("Hello World!")
+async fn hello() -> &'static str {
+ "Hello World!"
}
-async fn get_mood(verb: Method) -> Resp {
+async fn get_mood(verb: Method) -> impl IntoResponse {
let mood = AudienceMood::from(verb);
- Resp::new(format!("Mood: {mood}"))
+ format!("Mood: {mood}")
}
-async fn fill_one_hat(Path(id): Path<usize>, Json(payload): Json<Value>) -> Resp {
+async fn fill_one_hat(
+ Path(id): Path<usize>,
+ Json(payload): Json<Value>,
+) -> impl IntoResponse {
let hat = HatRack::fill(id, payload);
- Resp::new(format!("{hat:#?}"))
+ format!("{hat:#?}")
}
pub trait FromRequest: Sized {
- type Rejection: Debug;
+ type Rejection: IntoResponse;
macro_rules! impl_handler {
($($t:ident),* ) => {
- impl<F, $($t,)* Last, S, Fut> Handler<($($t,)* Last,), S> for F
+ impl<F, $($t,)* Last, S, Fut, R> Handler<($($t,)* Last,), S> for F
where
Last: FromRequest + Send,
- Fut: Future<Output = Resp> + Send,
+ Fut: Future<Output = R> + Send,
+ R: IntoResponse,
{
async fn call(self, req: Req, _state: S) -> Resp {
let $t = match $t::from_parts(&mut parts).await {
Ok(value) => value,
- Err(err) => return Resp::from_rejection(err),
+ Err(err) => return err.into_response(),
};
- self($($t,)* last).await
+ let result = self($($t,)* last).await;
+ result.into_response()
-pub trait FromRequest: Sized {
+pub trait FromRequest<S>: Sized {
type Rejection: IntoResponse;
- fn from_request(req: Req) -> impl Future<Output = ...> + Send;
+ fn from_request(state: &S, req: Req) -> impl Future<Output = ...> + Send;
}
-pub trait FromParts: Sized {
+pub trait FromParts<S>: Sized {
type Rejection: IntoResponse;
- fn from_parts(parts: &mut Parts) -> impl Future<Output = ...> + Send;
+ fn from_parts(state: &S, parts: &mut Parts) -> impl Future<Output = ...> + Send;
}
-impl<E> FromRequest for E
+impl<E, S> FromRequest<S> for E
where
- E: FromParts,
+ E: FromParts<S>,
+ S: Send + Sync,
{
/// L'état de l'application (Context d'injection)
pub struct State<T>(pub T);
impl<S> FromParts<S> for State<S>
where
S: Send + Sync + Clone,
{
type Rejection = Infallible;
// Ajout de l'argument state dans nos extracteurs
async fn from_parts(state: &S, _parts: &mut Parts) -> Result<Self, Self::Rejection> {
// Notez que le clone est généralement peu cher (utilisation de Arc, clone de pointeur)
Ok(Self(state.clone()))
}
}
error[E0119]: conflicting implementations of trait `FromRequest<_>`
for type `Json<_>`
Pour un couple (type, trait) il faut la garantie d'avoir une seule implémentation.
E0119
La blanket implémentation automatique de FromParts vers FromRequest
ouvre la porte à un conflit d'implémentation.
Warning
Attention on a tendance à retenir une version simplifié de l'orphan rule.
Le vérificateur de cohérence ne sait plus
prouver que Json<T>: FromParts<S> est impossible pour tout S - et
dans le doute, il refuse.
-pub trait FromRequest<S>: Sized {
+pub trait FromRequest<S, M = specialization::ViaRequest>: Sized {
type Rejection: IntoResponse;
-impl<E, S> FromRequest<S> for E
+impl<E, S> FromRequest<S, specialization::ViaParts> for E
where
E: FromParts<S>,
S: Send + Sync,
{
+// Deux étiquettes, habitées par personne, lues à la compilation
+pub(crate) mod specialization {
+ pub enum ViaRequest {}
+ pub enum ViaParts {}
+}
mini-axum en faitJavaTypeScriptGo
Self-> Result<Self, Self::Rejection>ââ ïžâ
type associĂ©type Rejection: IntoResponseâââ
impl type externeimpl IntoResponse for Stringâââ
blanket implimpl<F, âŠ> Handler<(), S> for Fâââ ïž
type par dĂ©fautFromRequest<S, M = ViaRequest>ââ
â
ACTE III
RECETTE · ALTERNATIVES · BACKEND
This is a reader monad,
and a monad is just a monoid in the category of endofunctors,
what's the problem?
async fn my_handler(ex: FromParts, last: FromRequest) -> impl IntoResponse {
// ...
}
async0..n arguments qui impl FromRequestParts0..1 argument qui impl FromRequestimpl IntoResponseNote
MĂȘme mĂ©canisme dans Bevy : les arguments d'un systĂšme ECS impl SystemParam
Option, Result : ni null, ni exceptionenum et match : le compilateur vérifie la couvertureSend et Sync, thread-safety à la compilation&mut : un seul écrivain à la foiscargo : build, test, doc, clippy, fmttokio, serde, tower, sqlx, axumFROM scratch, rien à installer sur le serveurloc. Répondre à un problÚme par un geste inattendu, et pourtant ingénieusement efficace.