mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-14 00:00:15 +02:00
examples: add examples with custom ConnectionBuilder
This commit is contained in:
Generated
+971
-114
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "example-serve-with-hyper-rustls"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
axum = { path = "../../axum", features = ["http1", "http2"] }
|
||||
http-body = "1.0"
|
||||
hyper = "1.0"
|
||||
rustls = "0.23"
|
||||
rustls-pemfile = "2"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false }
|
||||
tokio-util = "0.7"
|
||||
tower = { version = "0.5.2", features = ["util"] }
|
||||
tracing = "0.1.41"
|
||||
@@ -0,0 +1,22 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDkzCCAnugAwIBAgIUXVYkRCrM/ge03DVymDtXCuybp7gwDQYJKoZIhvcNAQEL
|
||||
BQAwWTELMAkGA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
|
||||
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDESMBAGA1UEAwwJbG9jYWxob3N0MB4X
|
||||
DTIxMDczMTE0MjIxMloXDTIyMDczMTE0MjIxMlowWTELMAkGA1UEBhMCVVMxEzAR
|
||||
BgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5
|
||||
IEx0ZDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
|
||||
MIIBCgKCAQEA02V5ZjmqLB/VQwTarrz/35qsa83L+DbAoa0001+jVmmC+G9Nufi0
|
||||
daroFWj/Uicv2fZWETU8JoZKUrX4BK9og5cg5rln/CtBRWCUYIwRgY9R/CdBGPn4
|
||||
kp+XkSJaCw74ZIyLy/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rd5Ec7eGTPqbBA0d0nMC5eeFTh7
|
||||
wV0miH20LX6Gjt9G6yJiHYSbeV5G1+vOcTYBEft5X/qJjU7aePXbWh0BAoGBAJlV
|
||||
5tgCCuhvFloK6fHYzqZtdT6O+PfpW20SMXrgkvMF22h2YvgDFrDwqKRUB47NfHzg
|
||||
3yBpxNH1ccA5/w97QO8w3gX3h6qicpJVOAPusu6cIBACFZfjRv1hyszOZwvw+Soa
|
||||
Fj5kHkqTY1YpkREPYS9V2dIW1Wjic1SXgZDw7VM/AoGAP/cZ3ZHTSCDTFlItqy5C
|
||||
rIy2AiY0WJsx+K0qcvtosPOOwtnGjWHb1gdaVdfX/IRkSsX4PAOdnsyidNC5/l/m
|
||||
y8oa+5WEeGFclWFhr4dnTA766o8HrM2UjIgWWYBF2VKdptGnHxFeJWFUmeQC/xeW
|
||||
w37pCS7ykL+7gp7V0WShYsw=
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Run with
|
||||
//!
|
||||
//! ```not_rust
|
||||
//! cargo run -p example-serve-with-hyper-rustls
|
||||
//! ```
|
||||
//!
|
||||
//! Test that the server runs with
|
||||
//! ```bash
|
||||
//! curl -kv https://localhost:3000
|
||||
//! ```
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::error::Error as StdError;
|
||||
use std::future::poll_fn;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::pin::pin;
|
||||
use std::sync::Arc;
|
||||
use std::{fs, io};
|
||||
|
||||
use axum::response::Response;
|
||||
use axum::serve::{Connection, ConnectionBuilder, Hyper};
|
||||
use axum::{extract::Request, routing::get, Router};
|
||||
use http_body::Body as HttpBody;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
use rustls::ServerConfig;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tower::Service;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HyperRustls {
|
||||
tls_acceptor: TlsAcceptor,
|
||||
inner: Hyper,
|
||||
}
|
||||
|
||||
impl HyperRustls {
|
||||
pub fn try_new() -> anyhow::Result<Self> {
|
||||
// Load public certificate.
|
||||
let certs = load_certs(&format!(
|
||||
"{}/self_signed_certs/cert.pem",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
))?;
|
||||
// Load private key.
|
||||
let key = load_private_key(&format!(
|
||||
"{}/self_signed_certs/key.pem",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
))?;
|
||||
|
||||
// Build TLS configuration.
|
||||
let mut server_config = ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(certs, key)
|
||||
.inspect_err(|e| tracing::error!(error = display(e), "Cannot load certificate."))
|
||||
.unwrap();
|
||||
server_config.alpn_protocols =
|
||||
vec![b"h2".to_vec(), b"http/1.1".to_vec(), b"http/1.0".to_vec()];
|
||||
|
||||
Ok(Self {
|
||||
tls_acceptor: TlsAcceptor::from(Arc::new(server_config)),
|
||||
inner: Hyper::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io, S, B> ConnectionBuilder<Io, S> for HyperRustls
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static,
|
||||
<S as Service<Request>>::Future: Send,
|
||||
B: HttpBody + Send + 'static,
|
||||
B::Data: Send,
|
||||
B::Error: Into<Box<dyn StdError + Send + Sync>>,
|
||||
{
|
||||
fn build_connection(&mut self, io: Io, service: S) -> impl Connection {
|
||||
let tls_acceptor = self.tls_acceptor.clone();
|
||||
let mut hyper = self.inner.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
let tls_stream = match tls_acceptor.accept(io).await {
|
||||
Ok(tls_stream) => tls_stream,
|
||||
Err(err) => {
|
||||
eprintln!("failed to perform tls handshake: {err:#}");
|
||||
return Err(Box::new(err) as _);
|
||||
}
|
||||
};
|
||||
|
||||
let mut connection = pin!(hyper.build_connection(tls_stream, service));
|
||||
|
||||
poll_fn(|cx| connection.as_mut().poll_connection(cx)).await
|
||||
})
|
||||
}
|
||||
|
||||
fn graceful_shutdown(&mut self) {
|
||||
ConnectionBuilder::<Io, S>::graceful_shutdown(&mut self.inner);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 3000);
|
||||
|
||||
println!("Starting to serve on https://{addr}");
|
||||
|
||||
// Create a regular axum app.
|
||||
let app = Router::new().route("/", get(|| async { "Hello!" }));
|
||||
|
||||
// Create a `TcpListener` using tokio.
|
||||
let listener = TcpListener::bind(addr).await.unwrap();
|
||||
|
||||
// Create a connection builder which first drives the TLS handshake and then uses `hyper` to
|
||||
// serve the connection.
|
||||
let connection_builder = HyperRustls::try_new()?;
|
||||
|
||||
axum::serve::serve(listener, app)
|
||||
.with_connection_builder(connection_builder)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Load public certificate from file.
|
||||
fn load_certs(filename: &str) -> io::Result<Vec<CertificateDer<'static>>> {
|
||||
// Open certificate file.
|
||||
let certfile = fs::File::open(filename)
|
||||
.map_err(|e| io::Error::other(format!("failed to open {filename}: {e}")))?;
|
||||
let mut reader = io::BufReader::new(certfile);
|
||||
|
||||
// Load and return certificate.
|
||||
rustls_pemfile::certs(&mut reader).collect()
|
||||
}
|
||||
|
||||
// Load private key from file.
|
||||
fn load_private_key(filename: &str) -> io::Result<PrivateKeyDer<'static>> {
|
||||
// Open keyfile.
|
||||
let keyfile = fs::File::open(filename)
|
||||
.map_err(|e| io::Error::other(format!("failed to open {filename}: {e}")))?;
|
||||
let mut reader = io::BufReader::new(keyfile);
|
||||
|
||||
// Load and return a single private key.
|
||||
rustls_pemfile::private_key(&mut reader).map(|key| key.unwrap())
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "example-serve-with-rama"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
axum = { path = "../../axum" }
|
||||
pin-project-lite = "0.2.7"
|
||||
rama = { version = "0.3.0-alpha.3", features = ["http-full", "tower"], default-features = false }
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
tower = { version = "0.5.2", features = ["util"] }
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Run with
|
||||
//!
|
||||
//! ```not_rust
|
||||
//! cargo run -p example-serve-with-rama
|
||||
//! ```
|
||||
//!
|
||||
//! This example shows how to run axum using rama as the HTTP driving server instead of the default
|
||||
//! hyper.
|
||||
use std::convert::Infallible;
|
||||
use std::future::{ready, Future};
|
||||
|
||||
use axum::body::{Body as AxumBody, HttpBody};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use axum::serve::{Connection, ConnectionBuilder};
|
||||
use axum::{extract::Request, routing::get, Router};
|
||||
use pin_project_lite::pin_project;
|
||||
use rama::graceful::ShutdownBuilder;
|
||||
use rama::http::core::body::Frame;
|
||||
use rama::http::core::server::conn::auto;
|
||||
use rama::http::Body as RamaBody;
|
||||
use rama::rt::Executor;
|
||||
use rama::utils::tower::ServiceAdapter;
|
||||
use rama::Context;
|
||||
use tokio::sync::watch;
|
||||
use tower::{Service, ServiceExt};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = Router::new().route("/", get(|| ready(StatusCode::IM_A_TEAPOT)));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
||||
.await
|
||||
.unwrap();
|
||||
let connection_builder = RamaConnectionBuilder::new();
|
||||
println!("listening on {}", listener.local_addr().unwrap());
|
||||
axum::serve::serve(listener, app)
|
||||
.with_connection_builder(connection_builder)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RamaConnectionBuilder {
|
||||
server: rama::http::server::HttpServer<auto::Builder>,
|
||||
shutdown: Option<watch::Receiver<()>>,
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
pub struct RamaConnection<F> {
|
||||
#[pin]
|
||||
inner: F
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
pub struct SyncBody<B> {
|
||||
#[pin]
|
||||
inner: B,
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY
|
||||
// This is fine because we never provide references to the inner body and the only publicly
|
||||
// accessible method using it requires `Pin<&mut Self>` which means exclusive access.
|
||||
unsafe impl<B: Send> Sync for SyncBody<B> {}
|
||||
|
||||
impl<B> SyncBody<B> {
|
||||
pub fn new(body: B) -> Self {
|
||||
Self { inner: body }
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: HttpBody> HttpBody for SyncBody<B> {
|
||||
type Data = B::Data;
|
||||
|
||||
type Error = B::Error;
|
||||
|
||||
fn poll_frame(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
||||
self.project().inner.poll_frame(cx)
|
||||
}
|
||||
|
||||
// We must NOT delegate the provided methods to the inner body. We must NOT use references to
|
||||
// the inner body as it may not be `Sync` and who knows what thread holds references to it.
|
||||
}
|
||||
|
||||
impl RamaConnectionBuilder {
|
||||
fn new() -> Self {
|
||||
let (shutdown_tx, shutdown_rx) = watch::channel(());
|
||||
let shutdown = ShutdownBuilder::new()
|
||||
.with_signal(async move { shutdown_tx.closed().await })
|
||||
.build();
|
||||
Self {
|
||||
server: rama::http::server::HttpServer::auto(Executor::graceful(shutdown.guard())),
|
||||
shutdown: Some(shutdown_rx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io, S> ConnectionBuilder<Io, S> for RamaConnectionBuilder
|
||||
where
|
||||
Io: rama::net::stream::Stream,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
S: Service<Request, Response = Response, Error = Infallible, Future: Send>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
fn build_connection(&mut self, io: Io, service: S) -> impl Connection {
|
||||
let rama_service = ServiceAdapter::new(
|
||||
service
|
||||
.map_request(|request: Request<RamaBody>| request.map(AxumBody::new))
|
||||
.map_response(|response: Response<AxumBody>| {
|
||||
response.map(SyncBody::new).map(RamaBody::new)
|
||||
}),
|
||||
);
|
||||
RamaConnection {
|
||||
inner: self.server.serve(Context::default(), io, rama_service),
|
||||
}
|
||||
}
|
||||
|
||||
fn graceful_shutdown(&mut self) {
|
||||
self.shutdown.take();
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> Connection for RamaConnection<F>
|
||||
where
|
||||
F: Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>> + Send,
|
||||
{
|
||||
fn poll_connection(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Result<(), Box<dyn std::error::Error + Send + Sync>>> {
|
||||
self.project().inner.poll(cx)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user