Skip to content

hyper: simplify handlers #9728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions frameworks/Rust/hyper/hyper.dockerfile
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
FROM rust:1.85 AS hyper

WORKDIR /src
COPY . .
RUN RUSTFLAGS="-C target-cpu=native" cargo install --path . --locked
ENV RUSTFLAGS="-C target-cpu=native"

# Cache dependency builds (requires passing --force-rm False to tfb command)
COPY Cargo.toml Cargo.lock /src/
RUN mkdir src \
&& echo "fn main() {println!(\"if you see this, the build broke\")}" > src/main.rs \
&& cargo build --release \
&& rm -rfv src/ target/release/hyper-techempower* target/release/deps/hyper_techempower*

COPY . /src/
RUN cargo install --path . --locked
EXPOSE 8080
CMD ["hyper-techempower"]
HEALTHCHECK CMD curl --fail http://localhost:8080/ping || exit 1
16 changes: 7 additions & 9 deletions frameworks/Rust/hyper/src/fortunes.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use std::convert::Infallible;

use http::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use http::Response;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use http_body_util::Full;
use hyper::body::Bytes;
use tokio_postgres::Row;

use crate::db::POOL;
use crate::{Error, SERVER_HEADER, TEXT_HTML};
use crate::{Error, Result, TEXT_HTML};

const QUERY: &str = "SELECT id, message FROM fortune";

Expand All @@ -26,18 +24,18 @@ impl From<&Row> for Fortune {
}
}

pub async fn get() -> crate::Result<Response<BoxBody<Bytes, Infallible>>> {
pub async fn get() -> Result<Response<Full<Bytes>>> {
let fortunes = tell_fortune().await?;
let content = FortunesTemplate { fortunes }.to_string();

Response::builder()
.header(SERVER, SERVER_HEADER.clone())
.header(CONTENT_TYPE, TEXT_HTML.clone())
.header(CONTENT_LENGTH, content.len())
.body(Full::from(content).boxed())
.body(content.into())
.map_err(Error::from)
}

async fn tell_fortune() -> crate::Result<Vec<Fortune>> {
async fn tell_fortune() -> Result<Vec<Fortune>> {
let db = POOL.get().await?;
let statement = db.prepare_cached(QUERY).await?;
let rows = db.query(&statement, &[]).await?;
Expand Down
15 changes: 6 additions & 9 deletions frameworks/Rust/hyper/src/json.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
use std::convert::Infallible;

use http::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use http::Response;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use http_body_util::Full;
use hyper::body::Bytes;
use serde::Serialize;

use crate::{Error, Result, APPLICATION_JSON, SERVER_HEADER};
use crate::{Error, Result, APPLICATION_JSON};

#[derive(Serialize)]
struct JsonResponse<'a> {
Expand All @@ -18,12 +15,12 @@ static CONTENT: JsonResponse = JsonResponse {
message: "Hello, world!",
};

pub fn get() -> Result<Response<BoxBody<Bytes, Infallible>>> {
pub fn get() -> Result<Response<Full<Bytes>>> {
let content = serde_json::to_vec(&CONTENT)?;

Response::builder()
.header(SERVER, SERVER_HEADER.clone())
.header(CONTENT_TYPE, APPLICATION_JSON.clone())
.header(CONTENT_LENGTH, content.len())
.body(Full::from(content).boxed())
.body(content.into())
.map_err(Error::from)
}
33 changes: 16 additions & 17 deletions frameworks/Rust/hyper/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{io, thread};

use clap::{Parser, ValueEnum};
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Empty, Full};
use http_body_util::Empty;
use hyper::body::{Bytes, Incoming};
use hyper::header::{HeaderValue, SERVER};
use hyper::server::conn::http1;
Expand Down Expand Up @@ -181,32 +181,31 @@ async fn accept_loop(handle: runtime::Handle, listener: TcpListener) -> Result<(
/// Routes requests to the appropriate handler.
async fn router(request: Request<Incoming>) -> Result<Response<BoxBody<Bytes, Infallible>>> {
// The method is always GET, so we don't check it.
match request.uri().path() {
"/ping" => ping(),
"/json" => json::get(),
"/db" => single_query::get().await,
"/queries" => multiple_queries::get(request.uri().query()).await,
"/fortunes" => fortunes::get().await,
"/plaintext" => plaintext::get(),
_ => not_found_error(),
}
let mut response = match request.uri().path() {
"/ping" => ping()?.map(BoxBody::new),
"/json" => json::get()?.map(BoxBody::new),
"/db" => single_query::get().await?.map(BoxBody::new),
"/queries" => multiple_queries::get(request.uri().query()).await?.map(BoxBody::new),
"/fortunes" => fortunes::get().await?.map(BoxBody::new),
"/plaintext" => plaintext::get()?.map(BoxBody::new),
_ => not_found_error()?.map(BoxBody::new),
};
response.headers_mut().insert(SERVER, SERVER_HEADER.clone());
Ok(response)
}

/// A handler that returns a "pong" response.
///
/// This handler is used to verify that the server is running and can respond to requests. It is
/// used by the docker health check command.
fn ping() -> Result<Response<BoxBody<Bytes, Infallible>>> {
Response::builder()
.body(Full::from("pong").boxed())
.map_err(Error::from)
fn ping() -> Result<Response<String>> {
Response::builder().body("pong".to_string()).map_err(Error::from)
}

/// A handler that returns a 404 response.
fn not_found_error() -> Result<Response<BoxBody<Bytes, Infallible>>> {
fn not_found_error() -> Result<Response<Empty<Bytes>>> {
Response::builder()
.status(StatusCode::NOT_FOUND)
.header(SERVER, SERVER_HEADER.clone())
.body(Empty::new().boxed())
.body(Empty::new())
.map_err(Error::from)
}
19 changes: 7 additions & 12 deletions frameworks/Rust/hyper/src/multiple_queries.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
use std::convert::Infallible;

use http::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use http::Response;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use http_body_util::Full;
use hyper::body::Bytes;
use serde::Serialize;
use tokio_postgres::Row;

use crate::db::POOL;
use crate::{Error, Result, APPLICATION_JSON, SERVER_HEADER};
use crate::{Error, Result, APPLICATION_JSON};

const QUERY: &str = "SELECT id, randomnumber FROM world WHERE id = $1";

Expand All @@ -28,21 +25,19 @@ impl From<Row> for World {
}
}

pub async fn get(query: Option<&str>) -> Result<Response<BoxBody<Bytes, Infallible>>> {
pub async fn get(query: Option<&str>) -> Result<Response<Full<Bytes>>> {
let count = query
.and_then(|query| query.strip_prefix("count="))
.and_then(|query| query.parse().ok())
.unwrap_or(1)
.clamp(1, 500);

let worlds = query_worlds(count).await?;
let json = serde_json::to_vec(&worlds)?;
let content = serde_json::to_vec(&worlds)?;

Response::builder()
.header(SERVER, SERVER_HEADER.clone())
.header(CONTENT_TYPE, APPLICATION_JSON.clone())
.header(CONTENT_LENGTH, json.len())
.body(Full::from(json).boxed())
.header(CONTENT_LENGTH, content.len())
.body(content.into())
.map_err(Error::from)
}

Expand Down
14 changes: 5 additions & 9 deletions frameworks/Rust/hyper/src/plaintext.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
use std::convert::Infallible;

use http::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use http::Response;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use http_body_util::Full;
use hyper::body::Bytes;

use crate::{Error, Result, SERVER_HEADER, TEXT_PLAIN};
use crate::{Error, Result, TEXT_PLAIN};

static CONTENT: &[u8] = b"Hello, world!";

pub fn get() -> Result<Response<BoxBody<Bytes, Infallible>>> {
pub fn get() -> Result<Response<Full<Bytes>>> {
Response::builder()
.header(SERVER, SERVER_HEADER.clone())
.header(CONTENT_TYPE, TEXT_PLAIN.clone())
.header(CONTENT_LENGTH, CONTENT.len())
.body(Full::from(CONTENT).boxed())
.body(CONTENT.into())
.map_err(Error::from)
}
20 changes: 8 additions & 12 deletions frameworks/Rust/hyper/src/single_query.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
use std::convert::Infallible;

use http::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use http::Response;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use http_body_util::Full;
use hyper::body::Bytes;
use serde::Serialize;
use tokio_postgres::Row;

use crate::db::POOL;
use crate::{Error, Result, APPLICATION_JSON, SERVER_HEADER};
use crate::{Error, Result, APPLICATION_JSON};

static QUERY: &str = "SELECT id, randomnumber FROM world WHERE id = $1";

Expand All @@ -28,16 +25,15 @@ impl From<Row> for World {
}
}

pub async fn get() -> Result<Response<BoxBody<Bytes, Infallible>>> {
pub async fn get() -> Result<Response<Full<Bytes>>> {
let id = fastrand::i32(1..10_000);
let world = query_world(id).await?;
let json = serde_json::to_vec(&world)?;

let content = serde_json::to_vec(&world)?;
Response::builder()
.header(SERVER, SERVER_HEADER.clone())
.header(CONTENT_TYPE, APPLICATION_JSON.clone())
.header(CONTENT_LENGTH, json.len())
.body(Full::from(json).boxed())
.header(CONTENT_LENGTH, content.len())
.body(content.into())
.map_err(Error::from)
}

Expand Down
4 changes: 4 additions & 0 deletions toolset/run-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,10 @@ def main(argv=None):
nargs='*',
default=None,
help='Extra docker arguments to be passed to the test container')
parser.add_argument(
'--force-rm',
default=True,
help='Remove intermediate docker containers after running.')

# Network options
parser.add_argument(
Expand Down
1 change: 1 addition & 0 deletions toolset/utils/benchmark_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def __init__(self, args):
self.cpuset_cpus = args.cpuset_cpus
self.test_container_memory = args.test_container_memory
self.extra_docker_runtime_args = args.extra_docker_runtime_args
self.force_rm_intermediate_docker_layers = args.force_rm

if self.network_mode is None:
self.network = 'tfb'
Expand Down
2 changes: 1 addition & 1 deletion toolset/utils/docker_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __build(self, base_url, path, build_log_file, log_prefix, dockerfile,
path=path,
dockerfile=dockerfile,
tag=tag,
forcerm=True,
forcerm=self.benchmarker.config.force_rm_intermediate_docker_layers,
timeout=3600,
pull=True,
buildargs=buildargs,
Expand Down
Loading