Fix example-unix-domain-socket on non-unix platforms (#919)

* remove unused `axum`'s dependency:`tokio-util`

* fix `examples/todos`'s `async fn todos_index` iter_overeager_cloned

* Add docs to `/examples/async-graphql`, just like other xamples.

* remove `examples/async-graphql` unused dependencies `tracing-subscriber` and `trace`

* `examples/chat` deps `trace` and `tracing-subscriber` never be used. Add trace `debug` to `chat`

* remove `examples/print-request-response` unused dependency `axum-extra`

* remove `examples/prometheus-metrics` unused dependency `axum-extra`

* remove `examples/reverse-proxy` unused dependencies `tracing-subscriber` and `trace`

* `examples/chat` fmt fix

* fix `example-unix-domain-socket` compile error on not-unix platforms

Co-authored-by: zys864 <zys864@qq.com>
Co-authored-by: zys864 <zys864@gmail.com>
This commit is contained in:
zys864 2022-04-08 17:29:52 +08:00 committed by GitHub
parent 3747650ae9
commit a237edb7c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,31 +4,11 @@
//! cargo run -p example-unix-domain-socket //! cargo run -p example-unix-domain-socket
//! ``` //! ```
use axum::{ #[cfg(unix)]
body::Body, #[tokio::main]
extract::connect_info::{self, ConnectInfo}, async fn main() {
http::{Method, Request, StatusCode, Uri}, unix::server().await;
routing::get, }
Router,
};
use futures::ready;
use hyper::{
client::connect::{Connected, Connection},
server::accept::Accept,
};
use std::{
io,
path::PathBuf,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{unix::UCred, UnixListener, UnixStream},
};
use tower::BoxError;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[cfg(not(unix))] #[cfg(not(unix))]
fn main() { fn main() {
@ -36,8 +16,34 @@ fn main() {
} }
#[cfg(unix)] #[cfg(unix)]
#[tokio::main] mod unix {
async fn main() { use axum::{
body::Body,
extract::connect_info::{self, ConnectInfo},
http::{Method, Request, StatusCode, Uri},
routing::get,
Router,
};
use futures::ready;
use hyper::{
client::connect::{Connected, Connection},
server::accept::Accept,
};
use std::{
io,
path::PathBuf,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{unix::UCred, UnixListener, UnixStream},
};
use tower::BoxError;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
pub async fn server() {
tracing_subscriber::registry() tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new( .with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".into()), std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".into()),
@ -84,19 +90,19 @@ async fn main() {
let body = hyper::body::to_bytes(response.into_body()).await.unwrap(); let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
let body = String::from_utf8(body.to_vec()).unwrap(); let body = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body, "Hello, World!"); assert_eq!(body, "Hello, World!");
} }
async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str { async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
println!("new connection from `{:?}`", info); println!("new connection from `{:?}`", info);
"Hello, World!" "Hello, World!"
} }
struct ServerAccept { struct ServerAccept {
uds: UnixListener, uds: UnixListener,
} }
impl Accept for ServerAccept { impl Accept for ServerAccept {
type Conn = UnixStream; type Conn = UnixStream;
type Error = BoxError; type Error = BoxError;
@ -107,13 +113,13 @@ impl Accept for ServerAccept {
let (stream, _addr) = ready!(self.uds.poll_accept(cx))?; let (stream, _addr) = ready!(self.uds.poll_accept(cx))?;
Poll::Ready(Some(Ok(stream))) Poll::Ready(Some(Ok(stream)))
} }
} }
struct ClientConnection { struct ClientConnection {
stream: UnixStream, stream: UnixStream,
} }
impl AsyncWrite for ClientConnection { impl AsyncWrite for ClientConnection {
fn poll_write( fn poll_write(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
@ -122,7 +128,10 @@ impl AsyncWrite for ClientConnection {
Pin::new(&mut self.stream).poll_write(cx, buf) Pin::new(&mut self.stream).poll_write(cx, buf)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> {
Pin::new(&mut self.stream).poll_flush(cx) Pin::new(&mut self.stream).poll_flush(cx)
} }
@ -132,9 +141,9 @@ impl AsyncWrite for ClientConnection {
) -> Poll<Result<(), io::Error>> { ) -> Poll<Result<(), io::Error>> {
Pin::new(&mut self.stream).poll_shutdown(cx) Pin::new(&mut self.stream).poll_shutdown(cx)
} }
} }
impl AsyncRead for ClientConnection { impl AsyncRead for ClientConnection {
fn poll_read( fn poll_read(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
@ -142,22 +151,22 @@ impl AsyncRead for ClientConnection {
) -> Poll<io::Result<()>> { ) -> Poll<io::Result<()>> {
Pin::new(&mut self.stream).poll_read(cx, buf) Pin::new(&mut self.stream).poll_read(cx, buf)
} }
} }
impl Connection for ClientConnection { impl Connection for ClientConnection {
fn connected(&self) -> Connected { fn connected(&self) -> Connected {
Connected::new() Connected::new()
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
#[allow(dead_code)] #[allow(dead_code)]
struct UdsConnectInfo { struct UdsConnectInfo {
peer_addr: Arc<tokio::net::unix::SocketAddr>, peer_addr: Arc<tokio::net::unix::SocketAddr>,
peer_cred: UCred, peer_cred: UCred,
} }
impl connect_info::Connected<&UnixStream> for UdsConnectInfo { impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
fn connect_info(target: &UnixStream) -> Self { fn connect_info(target: &UnixStream) -> Self {
let peer_addr = target.peer_addr().unwrap(); let peer_addr = target.peer_addr().unwrap();
let peer_cred = target.peer_cred().unwrap(); let peer_cred = target.peer_cred().unwrap();
@ -167,4 +176,5 @@ impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
peer_cred, peer_cred,
} }
} }
}
} }