Skip to content

Commit 1ceb785

Browse files
jplattefranz1981
authored andcommitted
Improve the axum entry (TechEmpower#8014)
* axum: Upgrade dependencies * axum: Remove identity cast * axum: Use state instead of extensions … and order / group / merge imports consistently. * axum: Use str::parse instead of invoking FromStr directly * axum: Use implicit format-args captures
1 parent 8e349d4 commit 1ceb785

15 files changed

+217
-226
lines changed

frameworks/Rust/axum/Cargo.lock

Lines changed: 20 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

frameworks/Rust/axum/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,9 @@ tokio-pg-mapper = "0.2.0"
4747
tokio-pg-mapper-derive = "0.2.0"
4848
tokio-postgres = "0.7.7"
4949
tower = { version = "0.4.13", features = ["util"] }
50-
tower-http = { version = "0.3.5", features = ["set-header"] }
50+
tower-http = { version = "0.4.0", features = ["set-header"] }
5151
yarte = "0.15.7"
5252

53-
5453
[profile.release]
5554
lto = true
56-
codegen-units = 1
55+
codegen-units = 1

frameworks/Rust/axum/src/database_mongo.rs

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,22 @@
1-
use axum::async_trait;
2-
use axum::extract::{Extension, FromRequestParts};
3-
use axum::http::request::Parts;
4-
use axum::http::StatusCode;
5-
use futures_util::stream::FuturesUnordered;
6-
use futures_util::TryStreamExt;
7-
use std::io;
8-
9-
use crate::utils::internal_error;
1+
use std::{convert::Infallible, io};
2+
3+
use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
4+
use futures_util::{stream::FuturesUnordered, StreamExt, TryStreamExt};
5+
use mongodb::{bson::doc, Database};
6+
107
use crate::{Fortune, World};
11-
use futures_util::StreamExt;
12-
use mongodb::bson::doc;
13-
use mongodb::Database;
148

159
pub struct DatabaseConnection(pub Database);
1610

1711
#[async_trait]
18-
impl<S> FromRequestParts<S> for DatabaseConnection
19-
where
20-
S: Send + Sync,
21-
{
22-
type Rejection = (StatusCode, String);
12+
impl FromRequestParts<Database> for DatabaseConnection {
13+
type Rejection = Infallible;
14+
2315
async fn from_request_parts(
24-
parts: &mut Parts,
25-
state: &S,
16+
_parts: &mut Parts,
17+
db: &Database,
2618
) -> Result<Self, Self::Rejection> {
27-
let Extension(db) = Extension::<Database>::from_request_parts(parts, state)
28-
.await
29-
.map_err(internal_error)?;
30-
31-
Ok(Self(db))
19+
Ok(Self(db.clone()))
3220
}
3321
}
3422

frameworks/Rust/axum/src/database_mongo_raw.rs

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,25 @@
1-
use axum::async_trait;
2-
use axum::extract::{Extension, FromRequestParts};
3-
use axum::http::request::Parts;
4-
use axum::http::StatusCode;
5-
use futures_util::stream::FuturesUnordered;
6-
use futures_util::TryStreamExt;
7-
use std::io;
8-
9-
use crate::utils::internal_error;
1+
use std::{convert::Infallible, io};
2+
3+
use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
4+
use futures_util::{stream::FuturesUnordered, TryStreamExt};
5+
use mongodb::{
6+
bson::{doc, RawDocumentBuf},
7+
Database,
8+
};
9+
1010
use crate::World;
11-
use mongodb::bson::{doc, RawDocumentBuf};
12-
use mongodb::Database;
1311

1412
pub struct DatabaseConnection(pub Database);
1513

1614
#[async_trait]
17-
impl<S> FromRequestParts<S> for DatabaseConnection
18-
where
19-
S: Send + Sync,
20-
{
21-
type Rejection = (StatusCode, String);
15+
impl FromRequestParts<Database> for DatabaseConnection {
16+
type Rejection = Infallible;
2217

2318
async fn from_request_parts(
24-
parts: &mut Parts,
25-
state: &S,
19+
_parts: &mut Parts,
20+
db: &Database,
2621
) -> Result<Self, Self::Rejection> {
27-
let Extension(db) = Extension::<Database>::from_request_parts(parts, state)
28-
.await
29-
.map_err(internal_error)?;
30-
31-
Ok(Self(db))
22+
Ok(Self(db.clone()))
3223
}
3324
}
3425

frameworks/Rust/axum/src/database_pg.rs

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
1-
use axum::async_trait;
2-
use axum::extract::{Extension, FromRequestParts};
3-
use axum::http::request::Parts;
4-
use axum::http::StatusCode;
1+
use std::{collections::HashMap, convert::Infallible, fmt::Write, io, sync::Arc};
2+
3+
use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
54
use futures::{
65
stream::futures_unordered::FuturesUnordered, FutureExt, StreamExt, TryStreamExt,
76
};
87
use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng};
9-
use std::sync::Arc;
10-
use std::{collections::HashMap, fmt::Write, io};
118
use tokio::pin;
129
use tokio_postgres::{connect, types::ToSql, Client, NoTls, Statement};
1310

1411
use crate::models_pg::{Fortune, World};
15-
use crate::utils::internal_error;
1612

1713
#[derive(Debug)]
1814
pub enum PgError {
@@ -49,7 +45,7 @@ impl PgConnection {
4945
// Spawn connection
5046
tokio::spawn(async move {
5147
if let Err(error) = conn.await {
52-
eprintln!("Connection error: {}", error);
48+
eprintln!("Connection error: {error}");
5349
}
5450
});
5551

@@ -63,14 +59,14 @@ impl PgConnection {
6359
q.push_str("UPDATE world SET randomnumber = CASE id ");
6460

6561
for _ in 1..=num {
66-
let _ = write!(q, "when ${} then ${} ", pl, pl + 1);
62+
let _ = write!(q, "when ${pl} then ${} ", pl + 1);
6763
pl += 2;
6864
}
6965

7066
q.push_str("ELSE randomnumber END WHERE id IN (");
7167

7268
for _ in 1..=num {
73-
let _ = write!(q, "${},", pl);
69+
let _ = write!(q, "${pl},");
7470
pl += 1;
7571
}
7672

@@ -191,21 +187,13 @@ impl PgConnection {
191187
pub struct DatabaseConnection(pub Arc<PgConnection>);
192188

193189
#[async_trait]
194-
impl<S> FromRequestParts<S> for DatabaseConnection
195-
where
196-
S: Send + Sync,
197-
{
198-
type Rejection = (StatusCode, String);
190+
impl FromRequestParts<Arc<PgConnection>> for DatabaseConnection {
191+
type Rejection = Infallible;
199192

200193
async fn from_request_parts(
201-
parts: &mut Parts,
202-
state: &S,
194+
_parts: &mut Parts,
195+
pg_connection: &Arc<PgConnection>,
203196
) -> Result<Self, Self::Rejection> {
204-
let Extension(pg_connection) =
205-
Extension::<Arc<PgConnection>>::from_request_parts(parts, state)
206-
.await
207-
.map_err(internal_error)?;
208-
209-
Ok(Self(pg_connection))
197+
Ok(Self(pg_connection.clone()))
210198
}
211199
}

frameworks/Rust/axum/src/database_pg_pool.rs

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
use axum::async_trait;
2-
use axum::extract::{Extension, FromRequestParts};
3-
use axum::http::request::Parts;
4-
use axum::http::StatusCode;
5-
use deadpool_postgres::{Client, Manager, ManagerConfig, RecyclingMethod};
61
use std::io;
7-
use std::str::FromStr;
2+
3+
use axum::{
4+
async_trait,
5+
extract::FromRequestParts,
6+
http::{request::Parts, StatusCode},
7+
};
8+
use deadpool_postgres::{Client, Manager, ManagerConfig, RecyclingMethod};
89
use tokio_pg_mapper::FromTokioPostgresRow;
910
use tokio_postgres::{NoTls, Row, Statement};
1011

11-
use crate::utils::internal_error;
12-
use crate::{Fortune, World};
12+
use crate::{utils::internal_error, Fortune, World};
1313

1414
#[derive(Debug)]
1515
pub enum PgError {
@@ -33,8 +33,8 @@ pub async fn create_pool(
3333
database_url: String,
3434
max_pool_size: u32,
3535
) -> deadpool_postgres::Pool {
36-
let pg_config =
37-
tokio_postgres::Config::from_str(&database_url).expect("invalid database url");
36+
let pg_config: tokio_postgres::Config =
37+
database_url.parse().expect("invalid database url");
3838

3939
let mgr_config = ManagerConfig {
4040
recycling_method: RecyclingMethod::Fast,
@@ -51,21 +51,13 @@ pub async fn create_pool(
5151
pub struct DatabaseClient(pub Client);
5252

5353
#[async_trait]
54-
impl<S> FromRequestParts<S> for DatabaseClient
55-
where
56-
S: Send + Sync,
57-
{
54+
impl FromRequestParts<deadpool_postgres::Pool> for DatabaseClient {
5855
type Rejection = (StatusCode, String);
5956

6057
async fn from_request_parts(
61-
parts: &mut Parts,
62-
state: &S,
58+
_parts: &mut Parts,
59+
pool: &deadpool_postgres::Pool,
6360
) -> Result<Self, Self::Rejection> {
64-
let Extension(pool) =
65-
Extension::<deadpool_postgres::Pool>::from_request_parts(parts, state)
66-
.await
67-
.map_err(internal_error)?;
68-
6961
let conn = pool.get().await.map_err(internal_error)?;
7062

7163
Ok(Self(conn))

frameworks/Rust/axum/src/database_sqlx.rs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
1-
use axum::async_trait;
2-
use axum::extract::{Extension, FromRequestParts};
3-
use axum::http::request::Parts;
4-
use axum::http::StatusCode;
51
use std::io;
62

7-
use crate::utils::internal_error;
8-
use crate::{Fortune, World};
9-
use sqlx::pool::PoolConnection;
10-
use sqlx::postgres::{PgArguments, PgPoolOptions};
11-
use sqlx::{Arguments, PgPool, Postgres};
3+
use axum::{
4+
async_trait,
5+
extract::FromRequestParts,
6+
http::{request::Parts, StatusCode},
7+
};
8+
use sqlx::{
9+
pool::PoolConnection,
10+
postgres::{PgArguments, PgPoolOptions},
11+
Arguments, PgPool, Postgres,
12+
};
13+
14+
use crate::{utils::internal_error, Fortune, World};
1215

1316
#[derive(Debug)]
1417
pub enum PgError {
@@ -44,19 +47,13 @@ pub async fn create_pool(
4447
pub struct DatabaseConnection(pub PoolConnection<Postgres>);
4548

4649
#[async_trait]
47-
impl<S> FromRequestParts<S> for DatabaseConnection
48-
where
49-
S: Send + Sync,
50-
{
50+
impl FromRequestParts<PgPool> for DatabaseConnection {
5151
type Rejection = (StatusCode, String);
52+
5253
async fn from_request_parts(
53-
parts: &mut Parts,
54-
state: &S,
54+
_parts: &mut Parts,
55+
pool: &PgPool,
5556
) -> Result<Self, Self::Rejection> {
56-
let Extension(pool) = Extension::<PgPool>::from_request_parts(parts, state)
57-
.await
58-
.map_err(internal_error)?;
59-
6057
let conn = pool.acquire().await.map_err(internal_error)?;
6158

6259
Ok(Self(conn))

frameworks/Rust/axum/src/main.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1+
use axum::{
2+
http::{header, HeaderValue, StatusCode},
3+
response::IntoResponse,
4+
routing::get,
5+
Json, Router,
6+
};
7+
use dotenv::dotenv;
8+
use tower_http::set_header::SetResponseHeaderLayer;
9+
110
mod models_common;
211
mod server;
312

4-
use models_common::Message;
5-
6-
use axum::http::StatusCode;
7-
use axum::http::{header, HeaderValue};
8-
use axum::response::IntoResponse;
9-
use axum::Json;
10-
use axum::{routing::get, Router};
11-
use dotenv::dotenv;
12-
use tower_http::set_header::SetResponseHeaderLayer;
13+
use self::models_common::Message;
1314

1415
pub async fn plaintext() -> &'static str {
1516
"Hello, World!"

0 commit comments

Comments
 (0)