Skip to content

Commit

Permalink
Improve the axum entry (#8014)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
jplatte authored Mar 16, 2023
1 parent 729a16b commit e6799bd
Show file tree
Hide file tree
Showing 15 changed files with 217 additions and 226 deletions.
22 changes: 20 additions & 2 deletions frameworks/Rust/axum/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions frameworks/Rust/axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,9 @@ tokio-pg-mapper = "0.2.0"
tokio-pg-mapper-derive = "0.2.0"
tokio-postgres = "0.7.7"
tower = { version = "0.4.13", features = ["util"] }
tower-http = { version = "0.3.5", features = ["set-header"] }
tower-http = { version = "0.4.0", features = ["set-header"] }
yarte = "0.15.7"


[profile.release]
lto = true
codegen-units = 1
codegen-units = 1
36 changes: 12 additions & 24 deletions frameworks/Rust/axum/src/database_mongo.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,22 @@
use axum::async_trait;
use axum::extract::{Extension, FromRequestParts};
use axum::http::request::Parts;
use axum::http::StatusCode;
use futures_util::stream::FuturesUnordered;
use futures_util::TryStreamExt;
use std::io;

use crate::utils::internal_error;
use std::{convert::Infallible, io};

use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
use futures_util::{stream::FuturesUnordered, StreamExt, TryStreamExt};
use mongodb::{bson::doc, Database};

use crate::{Fortune, World};
use futures_util::StreamExt;
use mongodb::bson::doc;
use mongodb::Database;

pub struct DatabaseConnection(pub Database);

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
S: Send + Sync,
{
type Rejection = (StatusCode, String);
impl FromRequestParts<Database> for DatabaseConnection {
type Rejection = Infallible;

async fn from_request_parts(
parts: &mut Parts,
state: &S,
_parts: &mut Parts,
db: &Database,
) -> Result<Self, Self::Rejection> {
let Extension(db) = Extension::<Database>::from_request_parts(parts, state)
.await
.map_err(internal_error)?;

Ok(Self(db))
Ok(Self(db.clone()))
}
}

Expand Down
37 changes: 14 additions & 23 deletions frameworks/Rust/axum/src/database_mongo_raw.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
use axum::async_trait;
use axum::extract::{Extension, FromRequestParts};
use axum::http::request::Parts;
use axum::http::StatusCode;
use futures_util::stream::FuturesUnordered;
use futures_util::TryStreamExt;
use std::io;

use crate::utils::internal_error;
use std::{convert::Infallible, io};

use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
use futures_util::{stream::FuturesUnordered, TryStreamExt};
use mongodb::{
bson::{doc, RawDocumentBuf},
Database,
};

use crate::World;
use mongodb::bson::{doc, RawDocumentBuf};
use mongodb::Database;

pub struct DatabaseConnection(pub Database);

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
S: Send + Sync,
{
type Rejection = (StatusCode, String);
impl FromRequestParts<Database> for DatabaseConnection {
type Rejection = Infallible;

async fn from_request_parts(
parts: &mut Parts,
state: &S,
_parts: &mut Parts,
db: &Database,
) -> Result<Self, Self::Rejection> {
let Extension(db) = Extension::<Database>::from_request_parts(parts, state)
.await
.map_err(internal_error)?;

Ok(Self(db))
Ok(Self(db.clone()))
}
}

Expand Down
34 changes: 11 additions & 23 deletions frameworks/Rust/axum/src/database_pg.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
use axum::async_trait;
use axum::extract::{Extension, FromRequestParts};
use axum::http::request::Parts;
use axum::http::StatusCode;
use std::{collections::HashMap, convert::Infallible, fmt::Write, io, sync::Arc};

use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
use futures::{
stream::futures_unordered::FuturesUnordered, FutureExt, StreamExt, TryStreamExt,
};
use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng};
use std::sync::Arc;
use std::{collections::HashMap, fmt::Write, io};
use tokio::pin;
use tokio_postgres::{connect, types::ToSql, Client, NoTls, Statement};

use crate::models_pg::{Fortune, World};
use crate::utils::internal_error;

#[derive(Debug)]
pub enum PgError {
Expand Down Expand Up @@ -49,7 +45,7 @@ impl PgConnection {
// Spawn connection
tokio::spawn(async move {
if let Err(error) = conn.await {
eprintln!("Connection error: {}", error);
eprintln!("Connection error: {error}");
}
});

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

for _ in 1..=num {
let _ = write!(q, "when ${} then ${} ", pl, pl + 1);
let _ = write!(q, "when ${pl} then ${} ", pl + 1);
pl += 2;
}

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

for _ in 1..=num {
let _ = write!(q, "${},", pl);
let _ = write!(q, "${pl},");
pl += 1;
}

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

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
S: Send + Sync,
{
type Rejection = (StatusCode, String);
impl FromRequestParts<Arc<PgConnection>> for DatabaseConnection {
type Rejection = Infallible;

async fn from_request_parts(
parts: &mut Parts,
state: &S,
_parts: &mut Parts,
pg_connection: &Arc<PgConnection>,
) -> Result<Self, Self::Rejection> {
let Extension(pg_connection) =
Extension::<Arc<PgConnection>>::from_request_parts(parts, state)
.await
.map_err(internal_error)?;

Ok(Self(pg_connection))
Ok(Self(pg_connection.clone()))
}
}
34 changes: 13 additions & 21 deletions frameworks/Rust/axum/src/database_pg_pool.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use axum::async_trait;
use axum::extract::{Extension, FromRequestParts};
use axum::http::request::Parts;
use axum::http::StatusCode;
use deadpool_postgres::{Client, Manager, ManagerConfig, RecyclingMethod};
use std::io;
use std::str::FromStr;

use axum::{
async_trait,
extract::FromRequestParts,
http::{request::Parts, StatusCode},
};
use deadpool_postgres::{Client, Manager, ManagerConfig, RecyclingMethod};
use tokio_pg_mapper::FromTokioPostgresRow;
use tokio_postgres::{NoTls, Row, Statement};

use crate::utils::internal_error;
use crate::{Fortune, World};
use crate::{utils::internal_error, Fortune, World};

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

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

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseClient
where
S: Send + Sync,
{
impl FromRequestParts<deadpool_postgres::Pool> for DatabaseClient {
type Rejection = (StatusCode, String);

async fn from_request_parts(
parts: &mut Parts,
state: &S,
_parts: &mut Parts,
pool: &deadpool_postgres::Pool,
) -> Result<Self, Self::Rejection> {
let Extension(pool) =
Extension::<deadpool_postgres::Pool>::from_request_parts(parts, state)
.await
.map_err(internal_error)?;

let conn = pool.get().await.map_err(internal_error)?;

Ok(Self(conn))
Expand Down
35 changes: 16 additions & 19 deletions frameworks/Rust/axum/src/database_sqlx.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use axum::async_trait;
use axum::extract::{Extension, FromRequestParts};
use axum::http::request::Parts;
use axum::http::StatusCode;
use std::io;

use crate::utils::internal_error;
use crate::{Fortune, World};
use sqlx::pool::PoolConnection;
use sqlx::postgres::{PgArguments, PgPoolOptions};
use sqlx::{Arguments, PgPool, Postgres};
use axum::{
async_trait,
extract::FromRequestParts,
http::{request::Parts, StatusCode},
};
use sqlx::{
pool::PoolConnection,
postgres::{PgArguments, PgPoolOptions},
Arguments, PgPool, Postgres,
};

use crate::{utils::internal_error, Fortune, World};

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

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
S: Send + Sync,
{
impl FromRequestParts<PgPool> for DatabaseConnection {
type Rejection = (StatusCode, String);

async fn from_request_parts(
parts: &mut Parts,
state: &S,
_parts: &mut Parts,
pool: &PgPool,
) -> Result<Self, Self::Rejection> {
let Extension(pool) = Extension::<PgPool>::from_request_parts(parts, state)
.await
.map_err(internal_error)?;

let conn = pool.acquire().await.map_err(internal_error)?;

Ok(Self(conn))
Expand Down
19 changes: 10 additions & 9 deletions frameworks/Rust/axum/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use axum::{
http::{header, HeaderValue, StatusCode},
response::IntoResponse,
routing::get,
Json, Router,
};
use dotenv::dotenv;
use tower_http::set_header::SetResponseHeaderLayer;

mod models_common;
mod server;

use models_common::Message;

use axum::http::StatusCode;
use axum::http::{header, HeaderValue};
use axum::response::IntoResponse;
use axum::Json;
use axum::{routing::get, Router};
use dotenv::dotenv;
use tower_http::set_header::SetResponseHeaderLayer;
use self::models_common::Message;

pub async fn plaintext() -> &'static str {
"Hello, World!"
Expand Down
Loading

0 comments on commit e6799bd

Please sign in to comment.