From 09f9e722f43fdf3e2661db154906286e11cad190 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 11 Mar 2023 18:02:32 +0100 Subject: [PATCH 1/5] axum: Upgrade dependencies --- frameworks/Rust/axum/Cargo.lock | 22 ++++++++++++++++++++-- frameworks/Rust/axum/Cargo.toml | 5 ++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/frameworks/Rust/axum/Cargo.lock b/frameworks/Rust/axum/Cargo.lock index c550419da21..579391e4ba8 100644 --- a/frameworks/Rust/axum/Cargo.lock +++ b/frameworks/Rust/axum/Cargo.lock @@ -95,7 +95,7 @@ dependencies = [ "tokio-pg-mapper-derive", "tokio-postgres", "tower", - "tower-http", + "tower-http 0.4.0", "yarte", ] @@ -128,7 +128,7 @@ dependencies = [ "sync_wrapper", "tokio", "tower", - "tower-http", + "tower-http 0.3.5", "tower-layer", "tower-service", ] @@ -2308,6 +2308,24 @@ dependencies = [ "tower-service", ] +[[package]] +name = "tower-http" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d1d42a9b3f3ec46ba828e8d376aec14592ea199f70a06a548587ecd1c4ab658" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-range-header", + "pin-project-lite", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-layer" version = "0.3.2" diff --git a/frameworks/Rust/axum/Cargo.toml b/frameworks/Rust/axum/Cargo.toml index a384bff84fc..413c99bd2a4 100644 --- a/frameworks/Rust/axum/Cargo.toml +++ b/frameworks/Rust/axum/Cargo.toml @@ -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 \ No newline at end of file +codegen-units = 1 From fcd6512a06edd62f324afde2def44a235c6c40aa Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 11 Mar 2023 18:03:49 +0100 Subject: [PATCH 2/5] axum: Remove identity cast --- frameworks/Rust/axum/src/main_mongo.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/Rust/axum/src/main_mongo.rs b/frameworks/Rust/axum/src/main_mongo.rs index e18cf5a2a40..767a2389f60 100644 --- a/frameworks/Rust/axum/src/main_mongo.rs +++ b/frameworks/Rust/axum/src/main_mongo.rs @@ -105,7 +105,7 @@ async fn fortunes(DatabaseConnection(db): DatabaseConnection) -> impl IntoRespon let fortune_infos: Vec = fortunes .iter() .map(|f| FortuneInfo { - id: f.id as i32, + id: f.id, message: f.message.clone(), }) .collect(); From 17f60ab29079e1a493175c7930e4764b5cc0a87a Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 11 Mar 2023 18:20:53 +0100 Subject: [PATCH 3/5] axum: Use state instead of extensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit … and order / group / merge imports consistently. --- frameworks/Rust/axum/src/database_mongo.rs | 36 ++++++---------- .../Rust/axum/src/database_mongo_raw.rs | 37 ++++++---------- frameworks/Rust/axum/src/database_pg.rs | 28 ++++-------- frameworks/Rust/axum/src/database_pg_pool.rs | 30 +++++-------- frameworks/Rust/axum/src/database_sqlx.rs | 35 +++++++-------- frameworks/Rust/axum/src/main.rs | 19 ++++---- frameworks/Rust/axum/src/main_mongo.rs | 40 +++++++++-------- frameworks/Rust/axum/src/main_mongo_raw.rs | 39 ++++++++++------- frameworks/Rust/axum/src/main_pg.rs | 28 ++++++------ frameworks/Rust/axum/src/main_pg_pool.rs | 43 ++++++++++--------- frameworks/Rust/axum/src/main_sqlx.rs | 35 +++++++-------- frameworks/Rust/axum/src/server.rs | 6 ++- frameworks/Rust/axum/src/utils.rs | 21 ++++----- 13 files changed, 186 insertions(+), 211 deletions(-) diff --git a/frameworks/Rust/axum/src/database_mongo.rs b/frameworks/Rust/axum/src/database_mongo.rs index 3d063747e9e..dcb9b1bebb9 100644 --- a/frameworks/Rust/axum/src/database_mongo.rs +++ b/frameworks/Rust/axum/src/database_mongo.rs @@ -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 FromRequestParts for DatabaseConnection -where - S: Send + Sync, -{ - type Rejection = (StatusCode, String); +impl FromRequestParts for DatabaseConnection { + type Rejection = Infallible; + async fn from_request_parts( - parts: &mut Parts, - state: &S, + _parts: &mut Parts, + db: &Database, ) -> Result { - let Extension(db) = Extension::::from_request_parts(parts, state) - .await - .map_err(internal_error)?; - - Ok(Self(db)) + Ok(Self(db.clone())) } } diff --git a/frameworks/Rust/axum/src/database_mongo_raw.rs b/frameworks/Rust/axum/src/database_mongo_raw.rs index af713d1e377..2fa02c07ec4 100644 --- a/frameworks/Rust/axum/src/database_mongo_raw.rs +++ b/frameworks/Rust/axum/src/database_mongo_raw.rs @@ -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 FromRequestParts for DatabaseConnection -where - S: Send + Sync, -{ - type Rejection = (StatusCode, String); +impl FromRequestParts for DatabaseConnection { + type Rejection = Infallible; async fn from_request_parts( - parts: &mut Parts, - state: &S, + _parts: &mut Parts, + db: &Database, ) -> Result { - let Extension(db) = Extension::::from_request_parts(parts, state) - .await - .map_err(internal_error)?; - - Ok(Self(db)) + Ok(Self(db.clone())) } } diff --git a/frameworks/Rust/axum/src/database_pg.rs b/frameworks/Rust/axum/src/database_pg.rs index 59fb6dde4d8..3526a75de3a 100644 --- a/frameworks/Rust/axum/src/database_pg.rs +++ b/frameworks/Rust/axum/src/database_pg.rs @@ -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 { @@ -191,21 +187,13 @@ impl PgConnection { pub struct DatabaseConnection(pub Arc); #[async_trait] -impl FromRequestParts for DatabaseConnection -where - S: Send + Sync, -{ - type Rejection = (StatusCode, String); +impl FromRequestParts> for DatabaseConnection { + type Rejection = Infallible; async fn from_request_parts( - parts: &mut Parts, - state: &S, + _parts: &mut Parts, + pg_connection: &Arc, ) -> Result { - let Extension(pg_connection) = - Extension::>::from_request_parts(parts, state) - .await - .map_err(internal_error)?; - - Ok(Self(pg_connection)) + Ok(Self(pg_connection.clone())) } } diff --git a/frameworks/Rust/axum/src/database_pg_pool.rs b/frameworks/Rust/axum/src/database_pg_pool.rs index 49d63ef779d..28dc31b9282 100644 --- a/frameworks/Rust/axum/src/database_pg_pool.rs +++ b/frameworks/Rust/axum/src/database_pg_pool.rs @@ -1,15 +1,15 @@ -use axum::async_trait; -use axum::extract::{Extension, FromRequestParts}; -use axum::http::request::Parts; -use axum::http::StatusCode; +use std::{io, str::FromStr}; + +use axum::{ + async_trait, + extract::FromRequestParts, + http::{request::Parts, StatusCode}, +}; use deadpool_postgres::{Client, Manager, ManagerConfig, RecyclingMethod}; -use std::io; -use std::str::FromStr; 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 { @@ -51,21 +51,13 @@ pub async fn create_pool( pub struct DatabaseClient(pub Client); #[async_trait] -impl FromRequestParts for DatabaseClient -where - S: Send + Sync, -{ +impl FromRequestParts for DatabaseClient { type Rejection = (StatusCode, String); async fn from_request_parts( - parts: &mut Parts, - state: &S, + _parts: &mut Parts, + pool: &deadpool_postgres::Pool, ) -> Result { - let Extension(pool) = - Extension::::from_request_parts(parts, state) - .await - .map_err(internal_error)?; - let conn = pool.get().await.map_err(internal_error)?; Ok(Self(conn)) diff --git a/frameworks/Rust/axum/src/database_sqlx.rs b/frameworks/Rust/axum/src/database_sqlx.rs index 5aa30028d46..e26baebde03 100644 --- a/frameworks/Rust/axum/src/database_sqlx.rs +++ b/frameworks/Rust/axum/src/database_sqlx.rs @@ -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 { @@ -44,19 +47,13 @@ pub async fn create_pool( pub struct DatabaseConnection(pub PoolConnection); #[async_trait] -impl FromRequestParts for DatabaseConnection -where - S: Send + Sync, -{ +impl FromRequestParts for DatabaseConnection { type Rejection = (StatusCode, String); + async fn from_request_parts( - parts: &mut Parts, - state: &S, + _parts: &mut Parts, + pool: &PgPool, ) -> Result { - let Extension(pool) = Extension::::from_request_parts(parts, state) - .await - .map_err(internal_error)?; - let conn = pool.acquire().await.map_err(internal_error)?; Ok(Self(conn)) diff --git a/frameworks/Rust/axum/src/main.rs b/frameworks/Rust/axum/src/main.rs index 05c870cd139..075ee1c01e6 100644 --- a/frameworks/Rust/axum/src/main.rs +++ b/frameworks/Rust/axum/src/main.rs @@ -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!" diff --git a/frameworks/Rust/axum/src/main_mongo.rs b/frameworks/Rust/axum/src/main_mongo.rs index 767a2389f60..8219113f583 100644 --- a/frameworks/Rust/axum/src/main_mongo.rs +++ b/frameworks/Rust/axum/src/main_mongo.rs @@ -1,30 +1,34 @@ -mod database_mongo; -mod models_common; -mod models_mongo; -mod server; -mod utils; +use std::time::Duration; -use axum::http::{header, HeaderValue}; use axum::{ - extract::Query, http::StatusCode, response::IntoResponse, routing::get, Extension, + extract::Query, + http::{header, HeaderValue, StatusCode}, + response::IntoResponse, + routing::get, Json, Router, }; use dotenv::dotenv; -use mongodb::options::{ClientOptions, Compressor}; -use mongodb::Client; +use mongodb::{ + options::{ClientOptions, Compressor}, + Client, +}; use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng}; -use std::time::Duration; use tower_http::set_header::SetResponseHeaderLayer; use yarte::Template; -use crate::database_mongo::{ - fetch_fortunes, find_world_by_id, find_worlds, update_worlds, +mod database_mongo; +mod models_common; +mod models_mongo; +mod server; +mod utils; + +use self::{ + database_mongo::{ + fetch_fortunes, find_world_by_id, find_worlds, update_worlds, DatabaseConnection, + }, + models_mongo::{Fortune, FortuneInfo, World}, + utils::{get_environment_variable, parse_params, Params, Utf8Html}, }; -use crate::utils::get_environment_variable; -use database_mongo::DatabaseConnection; -use models_mongo::FortuneInfo; -use models_mongo::{Fortune, World}; -use utils::{parse_params, Params, Utf8Html}; #[derive(Template)] #[template(path = "fortunes.html.hbs")] @@ -171,7 +175,7 @@ async fn serve() { .route("/db", get(db)) .route("/queries", get(queries)) .route("/updates", get(updates)) - .layer(Extension(database)) + .with_state(database) .layer(SetResponseHeaderLayer::if_not_present( header::SERVER, server_header_value, diff --git a/frameworks/Rust/axum/src/main_mongo_raw.rs b/frameworks/Rust/axum/src/main_mongo_raw.rs index 4a42f54efcd..72db28af280 100644 --- a/frameworks/Rust/axum/src/main_mongo_raw.rs +++ b/frameworks/Rust/axum/src/main_mongo_raw.rs @@ -1,26 +1,33 @@ -mod database_mongo_raw; -mod models_common; -mod models_mongo; -mod server; -mod utils; +use std::time::Duration; -use axum::http::{header, HeaderValue}; use axum::{ - extract::Query, http::StatusCode, response::IntoResponse, routing::get, Extension, + extract::Query, + http::{header, HeaderValue, StatusCode}, + response::IntoResponse, + routing::get, Json, Router, }; use dotenv::dotenv; -use mongodb::options::{ClientOptions, Compressor}; -use mongodb::Client; +use mongodb::{ + options::{ClientOptions, Compressor}, + Client, +}; use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng}; -use std::time::Duration; use tower_http::set_header::SetResponseHeaderLayer; -use database_mongo_raw::DatabaseConnection; -use database_mongo_raw::{find_world_by_id, find_worlds, update_worlds}; -use models_mongo::World; -use utils::get_environment_variable; -use utils::{parse_params, Params}; +mod database_mongo_raw; +mod models_common; +mod models_mongo; +mod server; +mod utils; + +use self::{ + database_mongo_raw::{ + find_world_by_id, find_worlds, update_worlds, DatabaseConnection, + }, + models_mongo::World, + utils::{get_environment_variable, parse_params, Params}, +}; async fn db(DatabaseConnection(db): DatabaseConnection) -> impl IntoResponse { let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); @@ -140,7 +147,7 @@ async fn serve() { .route("/db", get(db)) .route("/queries", get(queries)) .route("/updates", get(updates)) - .layer(Extension(database)) + .with_state(database) .layer(SetResponseHeaderLayer::if_not_present( header::SERVER, server_header_value, diff --git a/frameworks/Rust/axum/src/main_pg.rs b/frameworks/Rust/axum/src/main_pg.rs index 8b123463eb0..3b4748dfc39 100644 --- a/frameworks/Rust/axum/src/main_pg.rs +++ b/frameworks/Rust/axum/src/main_pg.rs @@ -1,23 +1,25 @@ -mod database_pg; -mod models_common; -mod models_pg; -mod server; -mod utils; - -use axum::http::{header, HeaderValue}; use axum::{ - extract::Query, http::StatusCode, response::IntoResponse, routing::get, Extension, + extract::Query, + http::{header, HeaderValue, StatusCode}, + response::IntoResponse, + routing::get, Json, Router, }; use dotenv::dotenv; use tower_http::set_header::SetResponseHeaderLayer; use yarte::Template; -use crate::database_pg::{DatabaseConnection, PgConnection}; -use models_pg::Fortune; -use utils::{parse_params, Params}; +mod database_pg; +mod models_common; +mod models_pg; +mod server; +mod utils; -use crate::utils::{get_environment_variable, Utf8Html}; +use self::{ + database_pg::{DatabaseConnection, PgConnection}, + models_pg::Fortune, + utils::{get_environment_variable, parse_params, Params, Utf8Html}, +}; #[derive(Template)] #[template(path = "fortunes.html.hbs")] @@ -101,7 +103,7 @@ async fn serve() { .route("/db", get(db)) .route("/queries", get(queries)) .route("/updates", get(updates)) - .layer(Extension(pg_connection.clone())) + .with_state(pg_connection) .layer(SetResponseHeaderLayer::if_not_present( header::SERVER, server_header_value, diff --git a/frameworks/Rust/axum/src/main_pg_pool.rs b/frameworks/Rust/axum/src/main_pg_pool.rs index 3ca67b03b9f..4c767b4a06c 100644 --- a/frameworks/Rust/axum/src/main_pg_pool.rs +++ b/frameworks/Rust/axum/src/main_pg_pool.rs @@ -1,30 +1,31 @@ -mod database_pg_pool; -mod models_common; -mod models_pg_pool; -mod server; -mod utils; - -use crate::database_pg_pool::{ - create_pool, fetch_all_fortunes, fetch_world_by_id, - prepare_fetch_all_fortunes_statement, prepare_fetch_world_by_id_statement, - prepare_update_world_by_id_statement, update_world, DatabaseClient, PgError, -}; -use axum::http::{header, HeaderValue}; use axum::{ - extract::Query, http::StatusCode, response::IntoResponse, routing::get, Extension, + extract::Query, + http::{header, HeaderValue, StatusCode}, + response::IntoResponse, + routing::get, Json, Router, }; use dotenv::dotenv; -use futures_util::stream::FuturesUnordered; -use futures_util::TryStreamExt; -use rand::rngs::SmallRng; -use rand::{thread_rng, Rng, SeedableRng}; +use futures_util::{stream::FuturesUnordered, TryStreamExt}; +use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng}; use tower_http::set_header::SetResponseHeaderLayer; use yarte::Template; -use crate::utils::{get_environment_variable, Utf8Html}; -use models_pg_pool::{Fortune, World}; -use utils::{parse_params, random_number, Params}; +mod database_pg_pool; +mod models_common; +mod models_pg_pool; +mod server; +mod utils; + +use self::{ + database_pg_pool::{ + create_pool, fetch_all_fortunes, fetch_world_by_id, + prepare_fetch_all_fortunes_statement, prepare_fetch_world_by_id_statement, + prepare_update_world_by_id_statement, update_world, DatabaseClient, PgError, + }, + models_pg_pool::{Fortune, World}, + utils::{get_environment_variable, parse_params, random_number, Params, Utf8Html}, +}; #[derive(Template)] #[template(path = "fortunes.html.hbs")] @@ -151,7 +152,7 @@ async fn serve() { .route("/db", get(db)) .route("/queries", get(queries)) .route("/updates", get(updates)) - .layer(Extension(pool)) + .with_state(pool) .layer(SetResponseHeaderLayer::if_not_present( header::SERVER, server_header_value, diff --git a/frameworks/Rust/axum/src/main_sqlx.rs b/frameworks/Rust/axum/src/main_sqlx.rs index 3f7debbd68d..c773233fcfa 100644 --- a/frameworks/Rust/axum/src/main_sqlx.rs +++ b/frameworks/Rust/axum/src/main_sqlx.rs @@ -1,26 +1,27 @@ -mod database_sqlx; -mod models_common; -mod models_sqlx; -mod server; -mod utils; - -use crate::database_sqlx::{fetch_fortunes, fetch_world, DatabaseConnection}; -use axum::http::{header, HeaderValue}; use axum::{ - extract::Extension, http::StatusCode, response::IntoResponse, routing::get, Json, - Router, + http::{header, HeaderValue, StatusCode}, + response::IntoResponse, + routing::get, + Json, Router, }; use dotenv::dotenv; -use rand::rngs::SmallRng; -use rand::{thread_rng, Rng, SeedableRng}; +use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng}; use sqlx::PgPool; use tower_http::set_header::SetResponseHeaderLayer; use yarte::Template; -use crate::utils::get_environment_variable; -use database_sqlx::create_pool; -use models_sqlx::{Fortune, World}; -use utils::Utf8Html; +mod database_sqlx; +mod models_common; +mod models_sqlx; +mod server; +mod utils; + +use self::{ + database_sqlx::{create_pool, fetch_fortunes, fetch_world, DatabaseConnection}, + models_sqlx::{Fortune, World}, + utils::get_environment_variable, + utils::Utf8Html, +}; #[derive(Template)] #[template(path = "fortunes.html.hbs")] @@ -86,7 +87,7 @@ async fn router(pool: PgPool) -> Router { Router::new() .route("/fortunes", get(fortunes)) .route("/db", get(db)) - .layer(Extension(pool)) + .with_state(pool) .layer(SetResponseHeaderLayer::if_not_present( header::SERVER, server_header_value, diff --git a/frameworks/Rust/axum/src/server.rs b/frameworks/Rust/axum/src/server.rs index 9232ef47017..118f35c8d83 100644 --- a/frameworks/Rust/axum/src/server.rs +++ b/frameworks/Rust/axum/src/server.rs @@ -1,5 +1,7 @@ -use std::io; -use std::net::{Ipv4Addr, SocketAddr}; +use std::{ + io, + net::{Ipv4Addr, SocketAddr}, +}; use hyper::server::conn::AddrIncoming; use tokio::net::{TcpListener, TcpSocket}; diff --git a/frameworks/Rust/axum/src/utils.rs b/frameworks/Rust/axum/src/utils.rs index e0355e1a216..ebb0a25b4ea 100644 --- a/frameworks/Rust/axum/src/utils.rs +++ b/frameworks/Rust/axum/src/utils.rs @@ -1,20 +1,20 @@ -use axum::body::{Bytes, Full}; -use axum::http::{header, HeaderValue, StatusCode}; -use axum::response::{IntoResponse, Response}; -use rand::rngs::SmallRng; -use rand::Rng; -use serde::Deserialize; +use std::{env, fmt::Debug, str::FromStr}; -use std::env; -use std::fmt::Debug; -use std::str::FromStr; +use axum::{ + body::{Bytes, Full}, + http::{header, HeaderValue, StatusCode}, + response::{IntoResponse, Response}, +}; +use rand::{rngs::SmallRng, Rng}; +use serde::Deserialize; pub fn get_environment_variable(key: &str) -> T where ::Err: Debug, { T::from_str( - &env::var(key).unwrap_or_else(|_| panic!("{} environment variable was not set", key)), + &env::var(key) + .unwrap_or_else(|_| panic!("{} environment variable was not set", key)), ) .unwrap_or_else(|_| panic!("could not parse {}", key)) } @@ -40,6 +40,7 @@ pub fn parse_params(params: Params) -> i32 { /// Utility function for mapping any error into a `500 Internal Server Error` /// response. +#[allow(dead_code)] pub fn internal_error(err: E) -> (StatusCode, String) where E: std::error::Error, From 59d67ecb6b62004e13c21198c826efa59d7c1b64 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 11 Mar 2023 18:22:12 +0100 Subject: [PATCH 4/5] axum: Use str::parse instead of invoking FromStr directly --- frameworks/Rust/axum/src/database_pg_pool.rs | 6 +++--- frameworks/Rust/axum/src/utils.rs | 9 ++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/frameworks/Rust/axum/src/database_pg_pool.rs b/frameworks/Rust/axum/src/database_pg_pool.rs index 28dc31b9282..f86c002845a 100644 --- a/frameworks/Rust/axum/src/database_pg_pool.rs +++ b/frameworks/Rust/axum/src/database_pg_pool.rs @@ -1,4 +1,4 @@ -use std::{io, str::FromStr}; +use std::io; use axum::{ async_trait, @@ -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, diff --git a/frameworks/Rust/axum/src/utils.rs b/frameworks/Rust/axum/src/utils.rs index ebb0a25b4ea..a8f0b005d0e 100644 --- a/frameworks/Rust/axum/src/utils.rs +++ b/frameworks/Rust/axum/src/utils.rs @@ -12,11 +12,10 @@ pub fn get_environment_variable(key: &str) -> T where ::Err: Debug, { - T::from_str( - &env::var(key) - .unwrap_or_else(|_| panic!("{} environment variable was not set", key)), - ) - .unwrap_or_else(|_| panic!("could not parse {}", key)) + env::var(key) + .unwrap_or_else(|_| panic!("{} environment variable was not set", key)) + .parse::() + .unwrap_or_else(|_| panic!("could not parse {}", key)) } #[derive(Debug, Deserialize)] From a860e227a5e9029a1e63441e0742dde7bb0ba0c8 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 11 Mar 2023 18:23:53 +0100 Subject: [PATCH 5/5] axum: Use implicit format-args captures --- frameworks/Rust/axum/src/database_pg.rs | 6 +++--- frameworks/Rust/axum/src/server.rs | 2 +- frameworks/Rust/axum/src/utils.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frameworks/Rust/axum/src/database_pg.rs b/frameworks/Rust/axum/src/database_pg.rs index 3526a75de3a..56e07553af3 100644 --- a/frameworks/Rust/axum/src/database_pg.rs +++ b/frameworks/Rust/axum/src/database_pg.rs @@ -45,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}"); } }); @@ -59,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; } diff --git a/frameworks/Rust/axum/src/server.rs b/frameworks/Rust/axum/src/server.rs index 118f35c8d83..29e165f6f5c 100644 --- a/frameworks/Rust/axum/src/server.rs +++ b/frameworks/Rust/axum/src/server.rs @@ -27,7 +27,7 @@ fn reuse_listener(addr: SocketAddr) -> io::Result { #[cfg(unix)] { if let Err(e) = socket.set_reuseport(true) { - eprintln!("error setting SO_REUSEPORT: {}", e); + eprintln!("error setting SO_REUSEPORT: {e}"); } } diff --git a/frameworks/Rust/axum/src/utils.rs b/frameworks/Rust/axum/src/utils.rs index a8f0b005d0e..89ecaeae6ab 100644 --- a/frameworks/Rust/axum/src/utils.rs +++ b/frameworks/Rust/axum/src/utils.rs @@ -13,9 +13,9 @@ where ::Err: Debug, { env::var(key) - .unwrap_or_else(|_| panic!("{} environment variable was not set", key)) + .unwrap_or_else(|_| panic!("{key} environment variable was not set")) .parse::() - .unwrap_or_else(|_| panic!("could not parse {}", key)) + .unwrap_or_else(|_| panic!("could not parse {key}")) } #[derive(Debug, Deserialize)]