| 
 | 1 | +//! This example runs a server that responds to any request with "Hello, world!".  | 
 | 2 | +//! Unlike it's server.rs counter part, it demonstrates using a !Send executor (i.e. gloomio,  | 
 | 3 | +//! monoio).  | 
 | 4 | +
  | 
 | 5 | +use std::{convert::Infallible, error::Error};  | 
 | 6 | + | 
 | 7 | +use std::marker::PhantomData;  | 
 | 8 | +use std::pin::Pin;  | 
 | 9 | +use std::task::{Context, Poll};  | 
 | 10 | +use std::thread;  | 
 | 11 | + | 
 | 12 | +use bytes::Bytes;  | 
 | 13 | +use http::{header::CONTENT_TYPE, Request, Response};  | 
 | 14 | +use http_body_util::{combinators::BoxBody, BodyExt, Full};  | 
 | 15 | +use hyper::{body::Incoming, service::service_fn};  | 
 | 16 | +use hyper_util::{  | 
 | 17 | +    rt::{TokioExecutor, TokioIo},  | 
 | 18 | +    server::conn::auto::Builder,  | 
 | 19 | +};  | 
 | 20 | +use tokio::{net::TcpListener, net::TcpStream, task::JoinSet};  | 
 | 21 | + | 
 | 22 | +/// Function from an incoming request to an outgoing response  | 
 | 23 | +///  | 
 | 24 | +/// This function gets turned into a [`hyper::service::Service`] later via  | 
 | 25 | +/// [`service_fn`]. Instead of doing this, you could also write a type that  | 
 | 26 | +/// implements [`hyper::service::Service`] directly and pass that in place of  | 
 | 27 | +/// writing a function like this and calling [`service_fn`].  | 
 | 28 | +async fn handle_request(_request: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {  | 
 | 29 | +    let response = Response::builder()  | 
 | 30 | +        .header(CONTENT_TYPE, "text/plain")  | 
 | 31 | +        .body(Full::new(Bytes::from("Hello, world!\n")))  | 
 | 32 | +        .expect("values provided to the builder should be valid");  | 
 | 33 | + | 
 | 34 | +    Ok(response)  | 
 | 35 | +}  | 
 | 36 | + | 
 | 37 | +async fn upgradable_server() -> Result<(), Box<dyn Error + 'static>> {  | 
 | 38 | +    let listen_addr = "127.0.0.1:8000";  | 
 | 39 | +    let tcp_listener = TcpListener::bind(listen_addr).await?;  | 
 | 40 | +    println!("listening on http://{listen_addr}");  | 
 | 41 | + | 
 | 42 | +    loop {  | 
 | 43 | +        let (stream, addr) = match tcp_listener.accept().await {  | 
 | 44 | +            Ok(x) => x,  | 
 | 45 | +            Err(e) => {  | 
 | 46 | +                eprintln!("failed to accept connection: {e}");  | 
 | 47 | +                continue;  | 
 | 48 | +            }  | 
 | 49 | +        };  | 
 | 50 | + | 
 | 51 | +        let serve_connection = async move {  | 
 | 52 | +            println!("handling a request from {addr}");  | 
 | 53 | + | 
 | 54 | +            let result = Builder::new(LocalExec)  | 
 | 55 | +                .serve_connection(TokioIo::new(stream), service_fn(handle_request))  | 
 | 56 | +                .await;  | 
 | 57 | + | 
 | 58 | +            if let Err(e) = result {  | 
 | 59 | +                eprintln!("error serving {addr}: {e}");  | 
 | 60 | +            }  | 
 | 61 | + | 
 | 62 | +            println!("handled a request from {addr}");  | 
 | 63 | +        };  | 
 | 64 | + | 
 | 65 | +        tokio::task::spawn_local(serve_connection);  | 
 | 66 | +    }  | 
 | 67 | +}  | 
 | 68 | + | 
 | 69 | +fn main() {  | 
 | 70 | +    let server = thread::spawn(move || {  | 
 | 71 | +        // Configure a runtime for the server that runs everything on the current thread  | 
 | 72 | +        let rt = tokio::runtime::Builder::new_current_thread()  | 
 | 73 | +            .enable_all()  | 
 | 74 | +            .build()  | 
 | 75 | +            .expect("build runtime");  | 
 | 76 | + | 
 | 77 | +        // Combine it with a `LocalSet,  which means it can spawn !Send futures...  | 
 | 78 | +        let local = tokio::task::LocalSet::new();  | 
 | 79 | +        local.block_on(&rt, upgradable_server()).unwrap();  | 
 | 80 | +    });  | 
 | 81 | + | 
 | 82 | +    server.join().unwrap()  | 
 | 83 | +}  | 
 | 84 | + | 
 | 85 | +// NOTE: This part is only needed for HTTP/2. HTTP/1 doesn't need an executor.  | 
 | 86 | +//  | 
 | 87 | +// Since the Server needs to spawn some background tasks, we needed  | 
 | 88 | +// to configure an Executor that can spawn !Send futures...  | 
 | 89 | +#[derive(Clone, Copy, Debug)]  | 
 | 90 | +struct LocalExec;  | 
 | 91 | + | 
 | 92 | +impl<F> hyper::rt::Executor<F> for LocalExec  | 
 | 93 | +where  | 
 | 94 | +    F: std::future::Future + 'static, // not requiring `Send`  | 
 | 95 | +{  | 
 | 96 | +    fn execute(&self, fut: F) {  | 
 | 97 | +        // This will spawn into the currently running `LocalSet`.  | 
 | 98 | +        tokio::task::spawn_local(fut);  | 
 | 99 | +    }  | 
 | 100 | +}  | 
 | 101 | + | 
 | 102 | +struct IOTypeNotSend {  | 
 | 103 | +    _marker: PhantomData<*const ()>,  | 
 | 104 | +    stream: TokioIo<TcpStream>,  | 
 | 105 | +}  | 
 | 106 | + | 
 | 107 | +impl IOTypeNotSend {  | 
 | 108 | +    fn new(stream: TokioIo<TcpStream>) -> Self {  | 
 | 109 | +        Self {  | 
 | 110 | +            _marker: PhantomData,  | 
 | 111 | +            stream,  | 
 | 112 | +        }  | 
 | 113 | +    }  | 
 | 114 | +}  | 
 | 115 | + | 
 | 116 | +impl hyper::rt::Write for IOTypeNotSend {  | 
 | 117 | +    fn poll_write(  | 
 | 118 | +        mut self: Pin<&mut Self>,  | 
 | 119 | +        cx: &mut Context<'_>,  | 
 | 120 | +        buf: &[u8],  | 
 | 121 | +    ) -> Poll<Result<usize, std::io::Error>> {  | 
 | 122 | +        Pin::new(&mut self.stream).poll_write(cx, buf)  | 
 | 123 | +    }  | 
 | 124 | + | 
 | 125 | +    fn poll_flush(  | 
 | 126 | +        mut self: Pin<&mut Self>,  | 
 | 127 | +        cx: &mut Context<'_>,  | 
 | 128 | +    ) -> Poll<Result<(), std::io::Error>> {  | 
 | 129 | +        Pin::new(&mut self.stream).poll_flush(cx)  | 
 | 130 | +    }  | 
 | 131 | + | 
 | 132 | +    fn poll_shutdown(  | 
 | 133 | +        mut self: Pin<&mut Self>,  | 
 | 134 | +        cx: &mut Context<'_>,  | 
 | 135 | +    ) -> Poll<Result<(), std::io::Error>> {  | 
 | 136 | +        Pin::new(&mut self.stream).poll_shutdown(cx)  | 
 | 137 | +    }  | 
 | 138 | +}  | 
 | 139 | + | 
 | 140 | +impl hyper::rt::Read for IOTypeNotSend {  | 
 | 141 | +    fn poll_read(  | 
 | 142 | +        mut self: Pin<&mut Self>,  | 
 | 143 | +        cx: &mut Context<'_>,  | 
 | 144 | +        buf: hyper::rt::ReadBufCursor<'_>,  | 
 | 145 | +    ) -> Poll<std::io::Result<()>> {  | 
 | 146 | +        Pin::new(&mut self.stream).poll_read(cx, buf)  | 
 | 147 | +    }  | 
 | 148 | +}  | 
0 commit comments