Browse Source

optimize response building process (#7008)

Nikolay Kim 3 years ago
parent
commit
31a1e25b04

+ 7 - 3
frameworks/Rust/ntex/Cargo.toml

@@ -37,11 +37,11 @@ tokio = ["ntex/tokio"]
 async-std = ["ntex/async-std"]
 
 [dependencies]
-ntex = { version = "0.5.0", default-features = false }
+ntex = "0.5.6"
 mimalloc = { version = "0.1.25", default-features = false }
 snmalloc-rs = { version = "0.2.26", features = ["1mib", "native-cpu"] }
 yarte = { version = "0.15", features = ["bytes-buf", "json"] }
-env_logger = "0.8"
+env_logger = "0.9"
 nanorand = { version = "0.5", default-features = false, features = ["std", "wyrand"] }
 atoi = "0.4"
 num_cpus = "1.13"
@@ -56,6 +56,10 @@ log = { version = "0.4", features = ["release_max_level_off"] }
 tokio-postgres = { git="https://github.com/fafhrd91/postgres.git" }
 
 [profile.release]
-lto = true
 opt-level = 3
 codegen-units = 1
+panic = 'abort'
+lto = "thin"
+debug = false
+incremental = false
+overflow-checks = false

+ 18 - 14
frameworks/Rust/ntex/src/main.rs

@@ -1,8 +1,8 @@
 #[global_allocator]
 static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
 
-use ntex::http::header::{HeaderValue, CONTENT_TYPE, SERVER};
-use ntex::{http, time::Seconds, util::Bytes, util::PoolId, web};
+use ntex::http::header::{CONTENT_TYPE, SERVER};
+use ntex::{http, time::Seconds, util::PoolId, web};
 use yarte::Serialize;
 
 mod utils;
@@ -20,18 +20,25 @@ async fn json() -> web::HttpResponse {
     }
     .to_bytes_mut(&mut body);
 
-    web::HttpResponse::Ok()
-        .header(SERVER, HeaderValue::from_static("N"))
-        .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
-        .body(body)
+    let mut response = web::HttpResponse::with_body(http::StatusCode::OK, body.into());
+    response.headers_mut().append(SERVER, utils::HDR_SERVER);
+    response
+        .headers_mut()
+        .append(CONTENT_TYPE, utils::HDR_JSON_CONTENT_TYPE);
+    response
 }
 
 #[web::get("/plaintext")]
 async fn plaintext() -> web::HttpResponse {
-    web::HttpResponse::Ok()
-        .header(SERVER, HeaderValue::from_static("N"))
-        .header(CONTENT_TYPE, HeaderValue::from_static("text/plain"))
-        .body(Bytes::from_static(b"Hello, World!"))
+    let mut response = web::HttpResponse::with_body(
+        http::StatusCode::OK,
+        http::body::Body::Bytes(utils::BODY_PLAIN_TEXT),
+    );
+    response.headers_mut().append(SERVER, utils::HDR_SERVER);
+    response
+        .headers_mut()
+        .append(CONTENT_TYPE, utils::HDR_TEXT_CONTENT_TYPE);
+    response
 }
 
 #[ntex::main]
@@ -49,10 +56,7 @@ async fn main() -> std::io::Result<()> {
             http::HttpService::build()
                 .keep_alive(http::KeepAlive::Os)
                 .client_timeout(Seconds(0))
-                .h1(web::App::new()
-                    .service(json)
-                    .service(plaintext)
-                    .with_config(web::dev::AppConfig::default()))
+                .h1(web::App::new().service(json).service(plaintext).finish())
         })?
         .run()
         .await

+ 21 - 20
frameworks/Rust/ntex/src/main_db.rs

@@ -4,7 +4,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
 use std::{pin::Pin, task::Context, task::Poll};
 
 use futures::future::{ok, Future, FutureExt};
-use ntex::http::header::{HeaderValue, CONTENT_TYPE, SERVER};
+use ntex::http::header::{CONTENT_TYPE, SERVER};
 use ntex::http::{HttpService, KeepAlive, Request, Response};
 use ntex::service::{Service, ServiceFactory};
 use ntex::web::{Error, HttpResponse};
@@ -31,19 +31,18 @@ impl Service<Request> for App {
     fn call(&self, req: Request) -> Self::Future {
         match req.path() {
             "/db" => Box::pin(self.0.get_world().map(|body| {
-                Ok(HttpResponse::Ok()
-                    .header(SERVER, HeaderValue::from_static("N"))
-                    .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
-                    .body(body))
+                let mut res = HttpResponse::with_body(http::StatusCode::OK, body.into());
+                res.headers_mut().append(SERVER, utils::HDR_SERVER);
+                res.headers_mut()
+                    .append(CONTENT_TYPE, utils::HDR_JSON_CONTENT_TYPE);
+                Ok(res)
             })),
             "/fortunes" => Box::pin(self.0.tell_fortune().map(|body| {
-                Ok(HttpResponse::Ok()
-                    .header(SERVER, HeaderValue::from_static("N"))
-                    .header(
-                        CONTENT_TYPE,
-                        HeaderValue::from_static("text/html; charset=utf-8"),
-                    )
-                    .body(body))
+                let mut res = HttpResponse::with_body(http::StatusCode::OK, body.into());
+                res.headers_mut().append(SERVER, utils::HDR_SERVER);
+                res.headers_mut()
+                    .append(CONTENT_TYPE, utils::HDR_HTML_CONTENT_TYPE);
+                Ok(res)
             })),
             "/query" => Box::pin(
                 self.0
@@ -51,10 +50,11 @@ impl Service<Request> for App {
                     .map(|worlds| {
                         let mut body = BytesMut::with_capacity(35 * worlds.len());
                         let _ = simd_json::to_writer(crate::utils::Writer(&mut body), &worlds);
-                        Ok(HttpResponse::Ok()
-                            .header(SERVER, HeaderValue::from_static("N"))
-                            .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
-                            .body(body.freeze()))
+                        let mut res = HttpResponse::with_body(http::StatusCode::OK, body.into());
+                        res.headers_mut().append(SERVER, utils::HDR_SERVER);
+                        res.headers_mut()
+                            .append(CONTENT_TYPE, utils::HDR_JSON_CONTENT_TYPE);
+                        Ok(res)
                     }),
             ),
             "/update" => Box::pin(
@@ -63,10 +63,11 @@ impl Service<Request> for App {
                     .map(|worlds| {
                         let mut body = BytesMut::with_capacity(35 * worlds.len());
                         let _ = simd_json::to_writer(crate::utils::Writer(&mut body), &worlds);
-                        Ok(HttpResponse::Ok()
-                            .header(SERVER, HeaderValue::from_static("N"))
-                            .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
-                            .body(body.freeze()))
+                        let mut res = HttpResponse::with_body(http::StatusCode::OK, body.into());
+                        res.headers_mut().append(SERVER, utils::HDR_SERVER);
+                        res.headers_mut()
+                            .append(CONTENT_TYPE, utils::HDR_JSON_CONTENT_TYPE);
+                        Ok(res)
                     }),
             ),
             _ => Box::pin(ok(Response::new(http::StatusCode::NOT_FOUND))),

+ 9 - 1
frameworks/Rust/ntex/src/utils.rs

@@ -2,7 +2,15 @@
 use std::{cmp, io};
 
 use atoi::FromRadix10;
-use ntex::util::{BufMut, BytesMut};
+use ntex::http::header::HeaderValue;
+use ntex::util::{BufMut, Bytes, BytesMut};
+
+pub const HDR_SERVER: HeaderValue = HeaderValue::from_static("N");
+pub const HDR_JSON_CONTENT_TYPE: HeaderValue = HeaderValue::from_static("application/json");
+pub const HDR_TEXT_CONTENT_TYPE: HeaderValue = HeaderValue::from_static("text/plain");
+pub const HDR_HTML_CONTENT_TYPE: HeaderValue =
+    HeaderValue::from_static("text/html; charset=utf-8");
+pub const BODY_PLAIN_TEXT: Bytes = Bytes::from_static(b"Hello, World!");
 
 pub const SIZE: usize = 27;