Ver código fonte

[rust/axum] performance improvements (#10001)

* build: upgraded dependencies

* feat: dependency updates and performance tweaks
Andrew James 1 mês atrás
pai
commit
9660e2c602

Diferenças do arquivo suprimidas por serem muito extensas
+ 177 - 229
frameworks/Rust/axum/Cargo.lock


+ 11 - 10
frameworks/Rust/axum/Cargo.toml

@@ -50,42 +50,43 @@ deadpool-postgres = { version = "0.14.1", features = ["rt_tokio_1", "serde"] }
 dotenv = "0.15.0"
 futures = "0.3.31"
 futures-util = "0.3.31"
-mongodb = { version = "3.2.3", features = [
+mongodb = { version = "3.2.4", features = [
     "zstd-compression",
     "snappy-compression",
     "zlib-compression",
 ] }
-num_cpus = "1.16.0"
-rand = { version = "0.9.1", features = ["small_rng"] }
+
+num_cpus = "1.17.0"
+rand = { version = "0.9.2", features = ["small_rng"] }
 serde = { version = "1.0.219", features = ["derive"] }
-serde_json = "1.0.140"
-sqlx = { version = "0.8.5", features = [
+serde_json = "1.0.141"
+sqlx = { version = "0.8.6", features = [
     "postgres",
     "macros",
     "runtime-tokio",
     "tls-rustls",
 ] }
-tokio = { version = "1.45.0", features = ["full"] }
+tokio = { version = "1.46.1", features = ["full"] }
 tokio-pg-mapper = { version = "0.2.0" }
 tokio-pg-mapper-derive = { version = "0.2.0" }
 tokio-postgres = { version = "0.7.13" }
 tower = { version = "0.5.2", features = ["util"] }
-tower-http = { version = "0.6.4", features = ["set-header"] }
+tower-http = { version = "0.6.6", features = ["set-header"] }
 yarte = "0.15.7"
 simd-json = { version = "0.15.1", optional = true }
 axum-core = { version = "0.5.2", optional = true }
 mime = { version = "0.3.17", optional = true }
 bytes = { version = "1.10.1", optional = true }
 serde_path_to_error = { version = "0.1.17", optional = true }
-socket2 = "0.5.9"
+socket2 = "0.5.10"
 hyper = { version = "1.6", features = ["server", "http1"] }
 hyper-util = { version = "0.1", features = ["tokio", "server-auto", "http1"] }
 quick_cache = "0.6.14"
-mimalloc = "0.1.46"
+mimalloc = "0.1.47"
 
 
 [profile.release]
 lto = "fat"
 codegen-units = 1
-strip = true
+# strip = true
 opt-level = 3

+ 1 - 1
frameworks/Rust/axum/axum.dockerfile

@@ -1,4 +1,4 @@
-FROM docker.io/rust:1.86-slim-bookworm AS builder
+FROM docker.io/rust:1.88-slim-bookworm AS builder
 
 RUN apt-get update && apt-get install -y --no-install-recommends \
     pkg-config libssl-dev \

+ 6 - 4
frameworks/Rust/axum/src/main.rs

@@ -1,7 +1,7 @@
 mod common;
 mod server;
 
-use axum::{http::StatusCode, response::IntoResponse, routing::get, Router};
+use axum::{response::IntoResponse, routing::get, Router};
 use common::models::Message;
 use dotenv::dotenv;
 use mimalloc::MiMalloc;
@@ -14,20 +14,22 @@ use axum::Json;
 #[cfg(feature = "simd-json")]
 use common::simd_json::Json;
 
+const HELLO_WORLD: &str = "Hello, World!";
+
 /// Return a plaintext static string.
 #[inline(always)]
 pub async fn plaintext() -> &'static str {
-    "Hello, World!"
+    &HELLO_WORLD
 }
 
 /// Return a JSON message.
 #[inline(always)]
 pub async fn json() -> impl IntoResponse {
     let message = Message {
-        message: "Hello, World!",
+        message: HELLO_WORLD,
     };
 
-    (StatusCode::OK, Json(message))
+    Json(message)
 }
 
 fn main() {

+ 2 - 2
frameworks/Rust/axum/src/main_sqlx.rs

@@ -1,7 +1,7 @@
 mod common;
 mod sqlx;
 
-use std::sync::Arc;
+use std::{borrow::Cow, sync::Arc};
 
 use ::sqlx::PgPool;
 use axum::{
@@ -80,7 +80,7 @@ async fn fortunes(State(AppState { db, .. }): State<AppState>) -> impl IntoRespo
 
     fortunes.push(Fortune {
         id: 0,
-        message: "Additional fortune added at request time.".to_string(),
+        message: Cow::Borrowed("Additional fortune added at request time."),
     });
 
     fortunes.sort_by(|a, b| a.message.cmp(&b.message));

+ 6 - 7
frameworks/Rust/axum/src/pg/database.rs

@@ -1,4 +1,4 @@
-use std::{convert::Infallible, io, sync::Arc};
+use std::{borrow::Cow, convert::Infallible, io, sync::Arc};
 
 use axum::{extract::FromRequestParts, http::request::Parts};
 use futures::{stream::futures_unordered::FuturesUnordered, StreamExt, TryStreamExt};
@@ -99,15 +99,14 @@ impl PgConnection {
 
         for w in &mut worlds {
             w.randomnumber = random_id(&mut rng);
-            ids.push(w.id);
-            nids.push(w.randomnumber);
+            ids.push(&w.id);
+            nids.push(&w.randomnumber);
         }
 
         // Update the random worlds in the database.
         self.client
             .execute(&self.updates, &[&ids, &nids])
-            .await
-            .unwrap();
+            .await?;
 
         Ok(worlds)
     }
@@ -115,7 +114,7 @@ impl PgConnection {
     pub async fn fetch_all_fortunes(&self) -> Result<Vec<Fortune>, PgError> {
         let mut fortunes = vec![Fortune {
             id: 0,
-            message: "Additional fortune added at request time.".parse().unwrap(),
+            message: Cow::Borrowed("Additional fortune added at request time."),
         }];
 
         let rows = self
@@ -128,7 +127,7 @@ impl PgConnection {
         while let Some(row) = rows.next().await.transpose()? {
             fortunes.push(Fortune {
                 id: row.get(0),
-                message: row.get(1),
+                message: Cow::Owned(row.get(1)),
             });
         }
 

+ 3 - 1
frameworks/Rust/axum/src/pg/models.rs

@@ -1,10 +1,12 @@
+use std::borrow::Cow;
+
 use serde::{Deserialize, Serialize};
 
 #[allow(non_snake_case)]
 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
 pub struct Fortune {
     pub id: i32,
-    pub message: String,
+    pub message: Cow<'static, str>,
 }
 
 #[allow(non_snake_case)]

+ 15 - 3
frameworks/Rust/axum/src/sqlx/models.rs

@@ -1,10 +1,22 @@
+use std::borrow::Cow;
+
 use serde::{Deserialize, Serialize};
-use sqlx::FromRow;
+use sqlx::{FromRow, Row};
+use sqlx::postgres::PgRow;
 
-#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromRow)]
+#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
 pub struct Fortune {
     pub id: i32,
-    pub message: String,
+    pub message: Cow<'static, str>,
+}
+
+impl FromRow<'_, PgRow> for Fortune {
+  fn from_row(row: &PgRow) -> Result<Self, sqlx::Error> {
+    Ok(Fortune {
+        id: row.try_get(0usize)?,
+        message: Cow::Owned(row.try_get(1usize)?)
+      })
+  }
 }
 
 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromRow)]

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff