hyperdriver 0.12.3

The missing middle for Hyper - Servers and Clients with ergonomic APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! This example closely follows the parent example from the `hyper` repository,
//! to demonstrate using a single-threaded runtime.
//!

use std::cell::Cell;
use std::future::Future;
use std::marker::PhantomData;
use std::net::{SocketAddr, ToSocketAddrs as _};
use std::pin::{Pin, pin};
use std::rc::Rc;
use std::task::{Context, Poll, ready};
use std::thread;

use chateau::client::conn::Transport;
use chateau::client::conn::service::ClientExecutorService;
use chateau::client::conn::transport::tcp::{TcpConnectionError, TcpTransport};
use chateau::services::make_service_fn;
use chateau::stream::tcp::TcpStream;
use futures_util::FutureExt;
use http_body_util::BodyExt;
use hyper::Request;
use hyper::body::{Body as HttpBody, Bytes, Frame, Incoming};
use hyper::{Error, Response};
use hyperdriver::bridge::io::TokioIo;
use hyperdriver::bridge::service::TowerHyperService;
use hyperdriver::client::conn::AutoTlsTransport;
use hyperdriver::client::conn::dns::GaiResolver;
use hyperdriver::client::conn::protocol::auto;
use hyperdriver::client::{ConnectionPoolLayer, UriKey};
use hyperdriver::info::HasConnectionInfo;
use hyperdriver::server::Accept;
use pin_project::pin_project;
use tokio::io::{self, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tower::ServiceExt;
use tower::service_fn;

struct Body {
    // Our Body type is !Send and !Sync:
    // _marker: PhantomData<*const ()>,
    _marker: PhantomData<()>,
    data: Option<Bytes>,
}

impl From<String> for Body {
    fn from(a: String) -> Self {
        Body {
            _marker: PhantomData,
            data: Some(a.into()),
        }
    }
}

impl HttpBody for Body {
    type Data = Bytes;
    type Error = Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        _: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        Poll::Ready(self.get_mut().data.take().map(|d| Ok(Frame::data(d))))
    }
}

fn main() {
    // pretty_env_logger::init();

    let (tx, rx) = oneshot::channel::<()>();
    let server_http2 = thread::spawn(move || {
        // Configure a runtime for the server that runs everything on the current thread
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build runtime");

        // Combine it with a `LocalSet,  which means it can spawn !Send futures...
        let local = tokio::task::LocalSet::new();
        local.block_on(&rt, http2_server(rx)).unwrap();
    });

    let client_http2 = thread::spawn(move || {
        // Configure a runtime for the client that runs everything on the current thread
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build runtime");

        // Combine it with a `LocalSet,  which means it can spawn !Send futures...
        let local = tokio::task::LocalSet::new();
        local
            .block_on(
                &rt,
                http2_client("http://localhost:3000".parse::<hyper::Uri>().unwrap(), tx),
            )
            .unwrap();
    });

    let (tx, rx) = oneshot::channel::<()>();

    let server_http1 = thread::spawn(move || {
        // Configure a runtime for the server that runs everything on the current thread
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build runtime");

        // Combine it with a `LocalSet,  which means it can spawn !Send futures...
        let local = tokio::task::LocalSet::new();
        local.block_on(&rt, http1_server(rx)).unwrap();
    });

    let client_http1 = thread::spawn(move || {
        // Configure a runtime for the client that runs everything on the current thread
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build runtime");

        // Combine it with a `LocalSet,  which means it can spawn !Send futures...
        let local = tokio::task::LocalSet::new();
        local
            .block_on(
                &rt,
                http1_client("http://localhost:3001".parse::<hyper::Uri>().unwrap(), tx),
            )
            .unwrap();
    });

    server_http2.join().unwrap();
    client_http2.join().unwrap();

    server_http1.join().unwrap();
    client_http1.join().unwrap();
}

async fn http1_server(rx: oneshot::Receiver<()>) -> Result<(), Box<dyn std::error::Error>> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3001));

    let listener = TcpListener::bind(addr).await?;

    // For each connection, clone the counter to use in our service...
    let counter = Rc::new(Cell::new(0));

    let mut rx = pin!(rx);

    loop {
        let (stream, addr) = tokio::select! {
            _ = &mut rx => return Ok(()),
            res = listener.accept() => res?,
        };

        let io = IOTypeNotSend::new(TcpStream::server(stream, addr));

        let cnt = counter.clone();

        let service = service_fn(move |_| {
            let prev = cnt.get();
            cnt.set(prev + 1);
            let value = cnt.get();
            async move {
                Ok::<_, Error>(Response::new(Body::from(format!(
                    "HTTP/1.1 Request #{value}"
                ))))
            }
        });

        tokio::task::spawn_local(async move {
            if let Err(err) = hyper::server::conn::http1::Builder::new()
                .serve_connection(TokioIo::new(io), TowerHyperService::new(service))
                .await
            {
                println!("Error serving connection: {err:?}");
            }
        });
    }
}

async fn http1_client(
    url: hyper::Uri,
    tx: oneshot::Sender<()>,
) -> Result<(), Box<dyn std::error::Error>> {
    let host = url.host().expect("uri has no host");
    let port = url.port_u16().unwrap_or(80);
    let addr = format!("{host}:{port}");
    let stream =
        TcpStream::connect(addr.to_socket_addrs()?.next().expect("No resolved address")).await?;

    let io = TokioIo::new(IOTypeNotSend::new(stream));

    let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;

    tokio::task::spawn_local(async move {
        if let Err(err) = conn.await {
            let mut stdout = io::stdout();
            stdout
                .write_all(format!("Connection failed: {err:?}").as_bytes())
                .await
                .unwrap();
            stdout.flush().await.unwrap();
        }
    });

    let authority = url.authority().unwrap().clone();

    // Make 4 requests
    for _ in 0..4 {
        let req = Request::builder()
            .uri(url.clone())
            .header(hyper::header::HOST, authority.as_str())
            .body(Body::from("test".to_string()))?;

        let mut res = sender.send_request(req).await?;

        let mut stdout = io::stdout();
        stdout
            .write_all(format!("Response: {}\n", res.status()).as_bytes())
            .await
            .unwrap();
        stdout
            .write_all(format!("Headers: {:#?}\n", res.headers()).as_bytes())
            .await
            .unwrap();
        stdout.flush().await.unwrap();

        // Print the response body
        while let Some(next) = res.frame().await {
            let frame = next?;
            if let Some(chunk) = frame.data_ref() {
                stdout.write_all(chunk).await.unwrap();
            }
        }
        stdout.write_all(b"\n-----------------\n").await.unwrap();
        stdout.flush().await.unwrap();
    }

    let _ = tx.send(());

    Ok(())
}

async fn http2_server(rx: oneshot::Receiver<()>) -> Result<(), Box<dyn std::error::Error>> {
    use hyperdriver::server::conn::Http2Builder;

    let mut stdout = io::stdout();

    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
    // Using a !Send request counter is fine on 1 thread...
    let counter = Rc::new(Cell::new(0));

    let listener = TcpListener::bind(addr).await?;

    stdout
        .write_all(format!("Listening on http://{addr}").as_bytes())
        .await
        .unwrap();
    stdout.flush().await.unwrap();

    let server = hyperdriver::Server::builder()
        .with_acceptor(AcceptNotSend::new(listener))
        .with_protocol(Http2Builder::new(LocalExec))
        .with_make_service(make_service_fn(|_| {
            let counter = counter.clone();
            async move {
                Ok::<_, Error>(service_fn(move |_: http::Request<Incoming>| {
                    let prev = counter.get();
                    counter.set(prev + 1);
                    let value = counter.get();
                    async move {
                        Ok::<_, Error>(Response::new(Body::from(format!(
                            "HTTP/2 Request #{value}"
                        ))))
                    }
                }))
            }
        }))
        .with_executor(LocalExec);

    // static_assertions::assert_impl_one!(http2::Builder<LocalExec>: hyperdriver::server::Protocol<SharedService<http::Request<hyper::body::Incoming>, http::Response<Body>, io::Error>, IOTypeNotSend, hyper::body::Incoming>);
    // static_assertions::assert_impl_one!(LocalExec: ServerExecutor<http2::Builder<LocalExec>, BoxMakeServiceRef<IOTypeNotSend, SharedService<http::Request<Body>, http::Response<Body>, io::Error>, io::Error>, AcceptNotSend, Body>);

    server
        .with_graceful_shutdown(async {
            let _ = rx.await;
        })
        .await?;

    Ok(())
}

async fn http2_client(
    url: hyper::Uri,
    tx: oneshot::Sender<()>,
) -> Result<(), Box<dyn std::error::Error>> {
    let client = tower::ServiceBuilder::new()
        .layer(
            ConnectionPoolLayer::<_, _, _, UriKey>::new(
                AutoTlsTransport::new(TransportNotSend {
                    tcp: TcpTransport::<GaiResolver>::default(),
                }),
                auto::AlpnHttpConnectionBuilder::<Body>::default(),
            )
            .with_optional_pool(Some(Default::default())),
        )
        .service(ClientExecutorService::new());

    let authority = url.authority().unwrap().clone();

    // Make 4 requests
    for _ in 0..4 {
        let req = Request::builder()
            .uri(url.clone())
            .version(http::Version::HTTP_2)
            .header(http::header::HOST, authority.as_str())
            .body(Body::from("test".to_string()))?;

        let mut res = client.clone().oneshot(req).await?;

        let mut stdout = io::stdout();
        stdout
            .write_all(format!("Response: {}\n", res.status()).as_bytes())
            .await
            .unwrap();
        stdout
            .write_all(format!("Headers: {:#?}\n", res.headers()).as_bytes())
            .await
            .unwrap();
        stdout.flush().await.unwrap();

        // Print the response body
        while let Some(next) = res.frame().await {
            let frame = next?;
            if let Some(chunk) = frame.data_ref() {
                stdout.write_all(chunk).await.unwrap();
            }
        }
        stdout.write_all(b"\n-----------------\n").await.unwrap();
        stdout.flush().await.unwrap();
    }

    let _ = tx.send(());
    Ok(())
}

#[derive(Clone, Copy, Debug)]
struct LocalExec;

impl<F> hyper::rt::Executor<F> for LocalExec
where
    F: std::future::Future + 'static, // not requiring `Send`
    F::Output: 'static,
{
    fn execute(&self, fut: F) {
        // This will spawn into the currently running `LocalSet`.
        tokio::task::spawn_local(fut);
    }
}

impl<F> chateau::rt::Executor<F> for LocalExec
where
    F: std::future::Future + 'static,
    F::Output: 'static,
{
    fn execute(&self, fut: F) {
        tokio::task::spawn_local(fut);
    }
}

#[derive(Debug)]
#[pin_project]
struct AcceptNotSend(#[pin] TcpListener);

impl AcceptNotSend {
    fn new(listener: TcpListener) -> Self {
        Self(listener)
    }
}

impl Accept for AcceptNotSend {
    type Connection = IOTypeNotSend;

    type Error = std::io::Error;

    fn poll_accept(
        self: std::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Self::Connection, Self::Error>> {
        let stream = ready!(self.project().0.poll_accept(cx)).map(IOTypeNotSend::new);
        Poll::Ready(stream)
    }
}

#[derive(Clone)]
struct TransportNotSend {
    tcp: TcpTransport<GaiResolver>,
}

impl<B> Transport<http::Request<B>> for TransportNotSend
where
    B: Send + 'static,
{
    type IO = TcpStream;

    type Error = TcpConnectionError;

    type Future = Pin<Box<dyn Future<Output = Result<Self::IO, Self::Error>> + Send>>;

    fn connect(&mut self, req: &http::Request<B>) -> Self::Future {
        self.tcp.connect(req).boxed()
    }

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        Transport::<http::Request<B>>::poll_ready(&mut self.tcp, cx)
    }
}

struct IOTypeNotSend {
    _marker: PhantomData<*const ()>,
    stream: TcpStream,
}

impl IOTypeNotSend {
    fn new(stream: TcpStream) -> Self {
        Self {
            _marker: PhantomData,
            stream,
        }
    }
}

impl HasConnectionInfo for IOTypeNotSend {
    type Addr = <TcpStream as HasConnectionInfo>::Addr;

    fn info(&self) -> hyperdriver::info::ConnectionInfo<Self::Addr> {
        self.stream.info()
    }
}

impl tokio::io::AsyncWrite for IOTypeNotSend {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        Pin::new(&mut self.stream).poll_write(cx, buf)
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.stream).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.stream).poll_shutdown(cx)
    }
}

impl tokio::io::AsyncRead for IOTypeNotSend {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.stream).poll_read(cx, buf)
    }
}