| 1 |
use std::error::Error as StdError; |
| 2 |
use std::fmt; |
| 3 |
#[cfg(feature = "tcp")] |
| 4 |
use std::net::{SocketAddr, TcpListener as StdTcpListener}; |
| 5 |
|
| 6 |
#[cfg(feature = "tcp")] |
| 7 |
use std::time::Duration; |
| 8 |
|
| 9 |
use pin_project_lite::pin_project; |
| 10 |
|
| 11 |
use tokio::io::{AsyncRead, AsyncWrite}; |
| 12 |
use tracing::trace; |
| 13 |
|
| 14 |
use super::accept::Accept; |
| 15 |
#[cfg(all(feature = "tcp"))] |
| 16 |
use super::tcp::AddrIncoming; |
| 17 |
use crate::body::{Body, HttpBody}; |
| 18 |
use crate::common::exec::Exec; |
| 19 |
use crate::common::exec::{ConnStreamExec, NewSvcExec}; |
| 20 |
use crate::common::{task, Future, Pin, Poll, Unpin}; |
| 21 |
// Renamed `Http` as `Http_` for now so that people upgrading don't see an |
| 22 |
// error that `hyper::server::Http` is private... |
| 23 |
use super::conn::{Connection, Http as Http_, UpgradeableConnection}; |
| 24 |
use super::shutdown::{Graceful, GracefulWatcher}; |
| 25 |
use crate::service::{HttpService, MakeServiceRef}; |
| 26 |
|
| 27 |
use self::new_svc::NewSvcTask; |
| 28 |
|
| 29 |
pin_project! { |
| 30 |
/// A listening HTTP server that accepts connections in both HTTP1 and HTTP2 by default. |
| 31 |
/// |
| 32 |
/// `Server` is a `Future` mapping a bound listener with a set of service |
| 33 |
/// handlers. It is built using the [`Builder`](Builder), and the future |
| 34 |
/// completes when the server has been shutdown. It should be run by an |
| 35 |
/// `Executor`. |
| 36 |
pub struct Server<I, S, E = Exec> { |
| 37 |
#[pin] |
| 38 |
incoming: I, |
| 39 |
make_service: S, |
| 40 |
protocol: Http_<E>, |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
/// A builder for a [`Server`](Server). |
| 45 |
#[derive(Debug)] |
| 46 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 47 |
pub struct Builder<I, E = Exec> { |
| 48 |
incoming: I, |
| 49 |
protocol: Http_<E>, |
| 50 |
} |
| 51 |
|
| 52 |
// ===== impl Server ===== |
| 53 |
|
| 54 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 55 |
impl<I> Server<I, ()> { |
| 56 |
/// Starts a [`Builder`](Builder) with the provided incoming stream. |
| 57 |
pub fn builder(incoming: I) -> Builder<I> { |
| 58 |
Builder { |
| 59 |
incoming, |
| 60 |
protocol: Http_::new(), |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
#[cfg(feature = "tcp")] |
| 66 |
#[cfg_attr( |
| 67 |
docsrs, |
| 68 |
doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2")))) |
| 69 |
)] |
| 70 |
impl Server<AddrIncoming, ()> { |
| 71 |
/// Binds to the provided address, and returns a [`Builder`](Builder). |
| 72 |
/// |
| 73 |
/// # Panics |
| 74 |
/// |
| 75 |
/// This method will panic if binding to the address fails. For a method |
| 76 |
/// to bind to an address and return a `Result`, see `Server::try_bind`. |
| 77 |
pub fn bind(addr: &SocketAddr) -> Builder<AddrIncoming> { |
| 78 |
let incoming = AddrIncoming::new(addr).unwrap_or_else(|e| { |
| 79 |
panic!("error binding to {}: {}", addr, e); |
| 80 |
}); |
| 81 |
Server::builder(incoming) |
| 82 |
} |
| 83 |
|
| 84 |
/// Tries to bind to the provided address, and returns a [`Builder`](Builder). |
| 85 |
pub fn try_bind(addr: &SocketAddr) -> crate::Result<Builder<AddrIncoming>> { |
| 86 |
AddrIncoming::new(addr).map(Server::builder) |
| 87 |
} |
| 88 |
|
| 89 |
/// Create a new instance from a `std::net::TcpListener` instance. |
| 90 |
pub fn from_tcp(listener: StdTcpListener) -> Result<Builder<AddrIncoming>, crate::Error> { |
| 91 |
AddrIncoming::from_std(listener).map(Server::builder) |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
#[cfg(feature = "tcp")] |
| 96 |
#[cfg_attr( |
| 97 |
docsrs, |
| 98 |
doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2")))) |
| 99 |
)] |
| 100 |
impl<S, E> Server<AddrIncoming, S, E> { |
| 101 |
/// Returns the local address that this server is bound to. |
| 102 |
pub fn local_addr(&self) -> SocketAddr { |
| 103 |
self.incoming.local_addr() |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 108 |
impl<I, IO, IE, S, E, B> Server<I, S, E> |
| 109 |
where |
| 110 |
I: Accept<Conn = IO, Error = IE>, |
| 111 |
IE: Into<Box<dyn StdError + Send + Sync>>, |
| 112 |
IO: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 113 |
S: MakeServiceRef<IO, Body, ResBody = B>, |
| 114 |
S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 115 |
B: HttpBody + 'static, |
| 116 |
B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 117 |
E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>, |
| 118 |
{ |
| 119 |
/// Prepares a server to handle graceful shutdown when the provided future |
| 120 |
/// completes. |
| 121 |
/// |
| 122 |
/// # Example |
| 123 |
/// |
| 124 |
/// ``` |
| 125 |
/// # fn main() {} |
| 126 |
/// # #[cfg(feature = "tcp")] |
| 127 |
/// # async fn run() { |
| 128 |
/// # use hyper::{Body, Response, Server, Error}; |
| 129 |
/// # use hyper::service::{make_service_fn, service_fn}; |
| 130 |
/// # let make_service = make_service_fn(|_| async { |
| 131 |
/// # Ok::<_, Error>(service_fn(|_req| async { |
| 132 |
/// # Ok::<_, Error>(Response::new(Body::from("Hello World"))) |
| 133 |
/// # })) |
| 134 |
/// # }); |
| 135 |
/// // Make a server from the previous examples... |
| 136 |
/// let server = Server::bind(&([127, 0, 0, 1], 3000).into()) |
| 137 |
/// .serve(make_service); |
| 138 |
/// |
| 139 |
/// // Prepare some signal for when the server should start shutting down... |
| 140 |
/// let (tx, rx) = tokio::sync::oneshot::channel::<()>(); |
| 141 |
/// let graceful = server |
| 142 |
/// .with_graceful_shutdown(async { |
| 143 |
/// rx.await.ok(); |
| 144 |
/// }); |
| 145 |
/// |
| 146 |
/// // Await the `server` receiving the signal... |
| 147 |
/// if let Err(e) = graceful.await { |
| 148 |
/// eprintln!("server error: {}", e); |
| 149 |
/// } |
| 150 |
/// |
| 151 |
/// // And later, trigger the signal by calling `tx.send(())`. |
| 152 |
/// let _ = tx.send(()); |
| 153 |
/// # } |
| 154 |
/// ``` |
| 155 |
pub fn with_graceful_shutdown<F>(self, signal: F) -> Graceful<I, S, F, E> |
| 156 |
where |
| 157 |
F: Future<Output = ()>, |
| 158 |
E: NewSvcExec<IO, S::Future, S::Service, E, GracefulWatcher>, |
| 159 |
{ |
| 160 |
Graceful::new(self, signal) |
| 161 |
} |
| 162 |
|
| 163 |
fn poll_next_( |
| 164 |
self: Pin<&mut Self>, |
| 165 |
cx: &mut task::Context<'_>, |
| 166 |
) -> Poll<Option<crate::Result<Connecting<IO, S::Future, E>>>> { |
| 167 |
let me = self.project(); |
| 168 |
match ready!(me.make_service.poll_ready_ref(cx)) { |
| 169 |
Ok(()) => (), |
| 170 |
Err(e) => { |
| 171 |
trace!("make_service closed"); |
| 172 |
return Poll::Ready(Some(Err(crate::Error::new_user_make_service(e)))); |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
if let Some(item) = ready!(me.incoming.poll_accept(cx)) { |
| 177 |
let io = item.map_err(crate::Error::new_accept)?; |
| 178 |
let new_fut = me.make_service.make_service_ref(&io); |
| 179 |
Poll::Ready(Some(Ok(Connecting { |
| 180 |
future: new_fut, |
| 181 |
io: Some(io), |
| 182 |
protocol: me.protocol.clone(), |
| 183 |
}))) |
| 184 |
} else { |
| 185 |
Poll::Ready(None) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
pub(super) fn poll_watch<W>( |
| 190 |
mut self: Pin<&mut Self>, |
| 191 |
cx: &mut task::Context<'_>, |
| 192 |
watcher: &W, |
| 193 |
) -> Poll<crate::Result<()>> |
| 194 |
where |
| 195 |
E: NewSvcExec<IO, S::Future, S::Service, E, W>, |
| 196 |
W: Watcher<IO, S::Service, E>, |
| 197 |
{ |
| 198 |
loop { |
| 199 |
if let Some(connecting) = ready!(self.as_mut().poll_next_(cx)?) { |
| 200 |
let fut = NewSvcTask::new(connecting, watcher.clone()); |
| 201 |
self.as_mut().project().protocol.exec.execute_new_svc(fut); |
| 202 |
} else { |
| 203 |
return Poll::Ready(Ok(())); |
| 204 |
} |
| 205 |
} |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 210 |
impl<I, IO, IE, S, B, E> Future for Server<I, S, E> |
| 211 |
where |
| 212 |
I: Accept<Conn = IO, Error = IE>, |
| 213 |
IE: Into<Box<dyn StdError + Send + Sync>>, |
| 214 |
IO: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 215 |
S: MakeServiceRef<IO, Body, ResBody = B>, |
| 216 |
S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 217 |
B: HttpBody + 'static, |
| 218 |
B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 219 |
E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>, |
| 220 |
E: NewSvcExec<IO, S::Future, S::Service, E, NoopWatcher>, |
| 221 |
{ |
| 222 |
type Output = crate::Result<()>; |
| 223 |
|
| 224 |
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { |
| 225 |
self.poll_watch(cx, &NoopWatcher) |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
impl<I: fmt::Debug, S: fmt::Debug> fmt::Debug for Server<I, S> { |
| 230 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 231 |
let mut st = f.debug_struct("Server"); |
| 232 |
st.field("listener", &self.incoming); |
| 233 |
st.finish() |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
// ===== impl Builder ===== |
| 238 |
|
| 239 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 240 |
impl<I, E> Builder<I, E> { |
| 241 |
/// Start a new builder, wrapping an incoming stream and low-level options. |
| 242 |
/// |
| 243 |
/// For a more convenient constructor, see [`Server::bind`](Server::bind). |
| 244 |
pub fn new(incoming: I, protocol: Http_<E>) -> Self { |
| 245 |
Builder { incoming, protocol } |
| 246 |
} |
| 247 |
|
| 248 |
/// Sets whether to use keep-alive for HTTP/1 connections. |
| 249 |
/// |
| 250 |
/// Default is `true`. |
| 251 |
#[cfg(feature = "http1")] |
| 252 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 253 |
pub fn http1_keepalive(mut self, val: bool) -> Self { |
| 254 |
self.protocol.http1_keep_alive(val); |
| 255 |
self |
| 256 |
} |
| 257 |
|
| 258 |
/// Set whether HTTP/1 connections should support half-closures. |
| 259 |
/// |
| 260 |
/// Clients can chose to shutdown their write-side while waiting |
| 261 |
/// for the server to respond. Setting this to `true` will |
| 262 |
/// prevent closing the connection immediately if `read` |
| 263 |
/// detects an EOF in the middle of a request. |
| 264 |
/// |
| 265 |
/// Default is `false`. |
| 266 |
#[cfg(feature = "http1")] |
| 267 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 268 |
pub fn http1_half_close(mut self, val: bool) -> Self { |
| 269 |
self.protocol.http1_half_close(val); |
| 270 |
self |
| 271 |
} |
| 272 |
|
| 273 |
/// Set the maximum buffer size. |
| 274 |
/// |
| 275 |
/// Default is ~ 400kb. |
| 276 |
#[cfg(feature = "http1")] |
| 277 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 278 |
pub fn http1_max_buf_size(mut self, val: usize) -> Self { |
| 279 |
self.protocol.max_buf_size(val); |
| 280 |
self |
| 281 |
} |
| 282 |
|
| 283 |
// Sets whether to bunch up HTTP/1 writes until the read buffer is empty. |
| 284 |
// |
| 285 |
// This isn't really desirable in most cases, only really being useful in |
| 286 |
// silly pipeline benchmarks. |
| 287 |
#[doc(hidden)] |
| 288 |
#[cfg(feature = "http1")] |
| 289 |
pub fn http1_pipeline_flush(mut self, val: bool) -> Self { |
| 290 |
self.protocol.pipeline_flush(val); |
| 291 |
self |
| 292 |
} |
| 293 |
|
| 294 |
/// Set whether HTTP/1 connections should try to use vectored writes, |
| 295 |
/// or always flatten into a single buffer. |
| 296 |
/// |
| 297 |
/// Note that setting this to false may mean more copies of body data, |
| 298 |
/// but may also improve performance when an IO transport doesn't |
| 299 |
/// support vectored writes well, such as most TLS implementations. |
| 300 |
/// |
| 301 |
/// Setting this to true will force hyper to use queued strategy |
| 302 |
/// which may eliminate unnecessary cloning on some TLS backends |
| 303 |
/// |
| 304 |
/// Default is `auto`. In this mode hyper will try to guess which |
| 305 |
/// mode to use |
| 306 |
#[cfg(feature = "http1")] |
| 307 |
pub fn http1_writev(mut self, enabled: bool) -> Self { |
| 308 |
self.protocol.http1_writev(enabled); |
| 309 |
self |
| 310 |
} |
| 311 |
|
| 312 |
/// Set whether HTTP/1 connections will write header names as title case at |
| 313 |
/// the socket level. |
| 314 |
/// |
| 315 |
/// Note that this setting does not affect HTTP/2. |
| 316 |
/// |
| 317 |
/// Default is false. |
| 318 |
#[cfg(feature = "http1")] |
| 319 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 320 |
pub fn http1_title_case_headers(mut self, val: bool) -> Self { |
| 321 |
self.protocol.http1_title_case_headers(val); |
| 322 |
self |
| 323 |
} |
| 324 |
|
| 325 |
/// Set whether to support preserving original header cases. |
| 326 |
/// |
| 327 |
/// Currently, this will record the original cases received, and store them |
| 328 |
/// in a private extension on the `Request`. It will also look for and use |
| 329 |
/// such an extension in any provided `Response`. |
| 330 |
/// |
| 331 |
/// Since the relevant extension is still private, there is no way to |
| 332 |
/// interact with the original cases. The only effect this can have now is |
| 333 |
/// to forward the cases in a proxy-like fashion. |
| 334 |
/// |
| 335 |
/// Note that this setting does not affect HTTP/2. |
| 336 |
/// |
| 337 |
/// Default is false. |
| 338 |
#[cfg(feature = "http1")] |
| 339 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 340 |
pub fn http1_preserve_header_case(mut self, val: bool) -> Self { |
| 341 |
self.protocol.http1_preserve_header_case(val); |
| 342 |
self |
| 343 |
} |
| 344 |
|
| 345 |
/// Set a timeout for reading client request headers. If a client does not |
| 346 |
/// transmit the entire header within this time, the connection is closed. |
| 347 |
/// |
| 348 |
/// Default is None. |
| 349 |
#[cfg(all(feature = "http1", feature = "runtime"))] |
| 350 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "http1", feature = "runtime"))))] |
| 351 |
pub fn http1_header_read_timeout(mut self, read_timeout: Duration) -> Self { |
| 352 |
self.protocol.http1_header_read_timeout(read_timeout); |
| 353 |
self |
| 354 |
} |
| 355 |
|
| 356 |
/// Sets whether HTTP/1 is required. |
| 357 |
/// |
| 358 |
/// Default is `false`. |
| 359 |
#[cfg(feature = "http1")] |
| 360 |
#[cfg_attr(docsrs, doc(cfg(feature = "http1")))] |
| 361 |
pub fn http1_only(mut self, val: bool) -> Self { |
| 362 |
self.protocol.http1_only(val); |
| 363 |
self |
| 364 |
} |
| 365 |
|
| 366 |
/// Sets whether HTTP/2 is required. |
| 367 |
/// |
| 368 |
/// Default is `false`. |
| 369 |
#[cfg(feature = "http2")] |
| 370 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 371 |
pub fn http2_only(mut self, val: bool) -> Self { |
| 372 |
self.protocol.http2_only(val); |
| 373 |
self |
| 374 |
} |
| 375 |
|
| 376 |
/// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2 |
| 377 |
/// stream-level flow control. |
| 378 |
/// |
| 379 |
/// Passing `None` will do nothing. |
| 380 |
/// |
| 381 |
/// If not set, hyper will use a default. |
| 382 |
/// |
| 383 |
/// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE |
| 384 |
#[cfg(feature = "http2")] |
| 385 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 386 |
pub fn http2_initial_stream_window_size(mut self, sz: impl Into<Option<u32>>) -> Self { |
| 387 |
self.protocol.http2_initial_stream_window_size(sz.into()); |
| 388 |
self |
| 389 |
} |
| 390 |
|
| 391 |
/// Sets the max connection-level flow control for HTTP2 |
| 392 |
/// |
| 393 |
/// Passing `None` will do nothing. |
| 394 |
/// |
| 395 |
/// If not set, hyper will use a default. |
| 396 |
#[cfg(feature = "http2")] |
| 397 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 398 |
pub fn http2_initial_connection_window_size(mut self, sz: impl Into<Option<u32>>) -> Self { |
| 399 |
self.protocol |
| 400 |
.http2_initial_connection_window_size(sz.into()); |
| 401 |
self |
| 402 |
} |
| 403 |
|
| 404 |
/// Sets whether to use an adaptive flow control. |
| 405 |
/// |
| 406 |
/// Enabling this will override the limits set in |
| 407 |
/// `http2_initial_stream_window_size` and |
| 408 |
/// `http2_initial_connection_window_size`. |
| 409 |
#[cfg(feature = "http2")] |
| 410 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 411 |
pub fn http2_adaptive_window(mut self, enabled: bool) -> Self { |
| 412 |
self.protocol.http2_adaptive_window(enabled); |
| 413 |
self |
| 414 |
} |
| 415 |
|
| 416 |
/// Sets the maximum frame size to use for HTTP2. |
| 417 |
/// |
| 418 |
/// Passing `None` will do nothing. |
| 419 |
/// |
| 420 |
/// If not set, hyper will use a default. |
| 421 |
#[cfg(feature = "http2")] |
| 422 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 423 |
pub fn http2_max_frame_size(mut self, sz: impl Into<Option<u32>>) -> Self { |
| 424 |
self.protocol.http2_max_frame_size(sz); |
| 425 |
self |
| 426 |
} |
| 427 |
|
| 428 |
/// Sets the max size of received header frames. |
| 429 |
/// |
| 430 |
/// Default is currently ~16MB, but may change. |
| 431 |
#[cfg(feature = "http2")] |
| 432 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 433 |
pub fn http2_max_header_list_size(mut self, max: u32) -> Self { |
| 434 |
self.protocol.http2_max_header_list_size(max); |
| 435 |
self |
| 436 |
} |
| 437 |
|
| 438 |
/// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2 |
| 439 |
/// connections. |
| 440 |
/// |
| 441 |
/// Default is no limit (`std::u32::MAX`). Passing `None` will do nothing. |
| 442 |
/// |
| 443 |
/// [spec]: https://http2.github.io/http2-spec/#SETTINGS_MAX_CONCURRENT_STREAMS |
| 444 |
#[cfg(feature = "http2")] |
| 445 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 446 |
pub fn http2_max_concurrent_streams(mut self, max: impl Into<Option<u32>>) -> Self { |
| 447 |
self.protocol.http2_max_concurrent_streams(max.into()); |
| 448 |
self |
| 449 |
} |
| 450 |
|
| 451 |
/// Sets an interval for HTTP2 Ping frames should be sent to keep a |
| 452 |
/// connection alive. |
| 453 |
/// |
| 454 |
/// Pass `None` to disable HTTP2 keep-alive. |
| 455 |
/// |
| 456 |
/// Default is currently disabled. |
| 457 |
/// |
| 458 |
/// # Cargo Feature |
| 459 |
/// |
| 460 |
/// Requires the `runtime` cargo feature to be enabled. |
| 461 |
#[cfg(all(feature = "runtime", feature = "http2"))] |
| 462 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 463 |
pub fn http2_keep_alive_interval(mut self, interval: impl Into<Option<Duration>>) -> Self { |
| 464 |
self.protocol.http2_keep_alive_interval(interval); |
| 465 |
self |
| 466 |
} |
| 467 |
|
| 468 |
/// Sets a timeout for receiving an acknowledgement of the keep-alive ping. |
| 469 |
/// |
| 470 |
/// If the ping is not acknowledged within the timeout, the connection will |
| 471 |
/// be closed. Does nothing if `http2_keep_alive_interval` is disabled. |
| 472 |
/// |
| 473 |
/// Default is 20 seconds. |
| 474 |
/// |
| 475 |
/// # Cargo Feature |
| 476 |
/// |
| 477 |
/// Requires the `runtime` cargo feature to be enabled. |
| 478 |
#[cfg(all(feature = "runtime", feature = "http2"))] |
| 479 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 480 |
pub fn http2_keep_alive_timeout(mut self, timeout: Duration) -> Self { |
| 481 |
self.protocol.http2_keep_alive_timeout(timeout); |
| 482 |
self |
| 483 |
} |
| 484 |
|
| 485 |
/// Set the maximum write buffer size for each HTTP/2 stream. |
| 486 |
/// |
| 487 |
/// Default is currently ~400KB, but may change. |
| 488 |
/// |
| 489 |
/// # Panics |
| 490 |
/// |
| 491 |
/// The value must be no larger than `u32::MAX`. |
| 492 |
#[cfg(feature = "http2")] |
| 493 |
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))] |
| 494 |
pub fn http2_max_send_buf_size(mut self, max: usize) -> Self { |
| 495 |
self.protocol.http2_max_send_buf_size(max); |
| 496 |
self |
| 497 |
} |
| 498 |
|
| 499 |
/// Enables the [extended CONNECT protocol]. |
| 500 |
/// |
| 501 |
/// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4 |
| 502 |
#[cfg(feature = "http2")] |
| 503 |
pub fn http2_enable_connect_protocol(mut self) -> Self { |
| 504 |
self.protocol.http2_enable_connect_protocol(); |
| 505 |
self |
| 506 |
} |
| 507 |
|
| 508 |
/// Sets the `Executor` to deal with connection tasks. |
| 509 |
/// |
| 510 |
/// Default is `tokio::spawn`. |
| 511 |
pub fn executor<E2>(self, executor: E2) -> Builder<I, E2> { |
| 512 |
Builder { |
| 513 |
incoming: self.incoming, |
| 514 |
protocol: self.protocol.with_executor(executor), |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
/// Consume this `Builder`, creating a [`Server`](Server). |
| 519 |
/// |
| 520 |
/// # Example |
| 521 |
/// |
| 522 |
/// ``` |
| 523 |
/// # #[cfg(feature = "tcp")] |
| 524 |
/// # async fn run() { |
| 525 |
/// use hyper::{Body, Error, Response, Server}; |
| 526 |
/// use hyper::service::{make_service_fn, service_fn}; |
| 527 |
/// |
| 528 |
/// // Construct our SocketAddr to listen on... |
| 529 |
/// let addr = ([127, 0, 0, 1], 3000).into(); |
| 530 |
/// |
| 531 |
/// // And a MakeService to handle each connection... |
| 532 |
/// let make_svc = make_service_fn(|_| async { |
| 533 |
/// Ok::<_, Error>(service_fn(|_req| async { |
| 534 |
/// Ok::<_, Error>(Response::new(Body::from("Hello World"))) |
| 535 |
/// })) |
| 536 |
/// }); |
| 537 |
/// |
| 538 |
/// // Then bind and serve... |
| 539 |
/// let server = Server::bind(&addr) |
| 540 |
/// .serve(make_svc); |
| 541 |
/// |
| 542 |
/// // Run forever-ish... |
| 543 |
/// if let Err(err) = server.await { |
| 544 |
/// eprintln!("server error: {}", err); |
| 545 |
/// } |
| 546 |
/// # } |
| 547 |
/// ``` |
| 548 |
pub fn serve<S, B>(self, make_service: S) -> Server<I, S, E> |
| 549 |
where |
| 550 |
I: Accept, |
| 551 |
I::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 552 |
I::Conn: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 553 |
S: MakeServiceRef<I::Conn, Body, ResBody = B>, |
| 554 |
S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 555 |
B: HttpBody + 'static, |
| 556 |
B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 557 |
E: NewSvcExec<I::Conn, S::Future, S::Service, E, NoopWatcher>, |
| 558 |
E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>, |
| 559 |
{ |
| 560 |
Server { |
| 561 |
incoming: self.incoming, |
| 562 |
make_service, |
| 563 |
protocol: self.protocol.clone(), |
| 564 |
} |
| 565 |
} |
| 566 |
} |
| 567 |
|
| 568 |
#[cfg(feature = "tcp")] |
| 569 |
#[cfg_attr( |
| 570 |
docsrs, |
| 571 |
doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2")))) |
| 572 |
)] |
| 573 |
impl<E> Builder<AddrIncoming, E> { |
| 574 |
/// Set the duration to remain idle before sending TCP keepalive probes. |
| 575 |
/// |
| 576 |
/// If `None` is specified, keepalive is disabled. |
| 577 |
pub fn tcp_keepalive(mut self, keepalive: Option<Duration>) -> Self { |
| 578 |
self.incoming.set_keepalive(keepalive); |
| 579 |
self |
| 580 |
} |
| 581 |
|
| 582 |
/// Set the duration between two successive TCP keepalive retransmissions, |
| 583 |
/// if acknowledgement to the previous keepalive transmission is not received. |
| 584 |
pub fn tcp_keepalive_interval(mut self, interval: Option<Duration>) -> Self { |
| 585 |
self.incoming.set_keepalive_interval(interval); |
| 586 |
self |
| 587 |
} |
| 588 |
|
| 589 |
/// Set the number of retransmissions to be carried out before declaring that remote end is not available. |
| 590 |
pub fn tcp_keepalive_retries(mut self, retries: Option<u32>) -> Self { |
| 591 |
self.incoming.set_keepalive_retries(retries); |
| 592 |
self |
| 593 |
} |
| 594 |
|
| 595 |
/// Set the value of `TCP_NODELAY` option for accepted connections. |
| 596 |
pub fn tcp_nodelay(mut self, enabled: bool) -> Self { |
| 597 |
self.incoming.set_nodelay(enabled); |
| 598 |
self |
| 599 |
} |
| 600 |
|
| 601 |
/// Set whether to sleep on accept errors. |
| 602 |
/// |
| 603 |
/// A possible scenario is that the process has hit the max open files |
| 604 |
/// allowed, and so trying to accept a new connection will fail with |
| 605 |
/// EMFILE. In some cases, it's preferable to just wait for some time, if |
| 606 |
/// the application will likely close some files (or connections), and try |
| 607 |
/// to accept the connection again. If this option is true, the error will |
| 608 |
/// be logged at the error level, since it is still a big deal, and then |
| 609 |
/// the listener will sleep for 1 second. |
| 610 |
/// |
| 611 |
/// In other cases, hitting the max open files should be treat similarly |
| 612 |
/// to being out-of-memory, and simply error (and shutdown). Setting this |
| 613 |
/// option to false will allow that. |
| 614 |
/// |
| 615 |
/// For more details see [`AddrIncoming::set_sleep_on_errors`] |
| 616 |
pub fn tcp_sleep_on_accept_errors(mut self, val: bool) -> Self { |
| 617 |
self.incoming.set_sleep_on_errors(val); |
| 618 |
self |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
// Used by `Server` to optionally watch a `Connection` future. |
| 623 |
// |
| 624 |
// The regular `hyper::Server` just uses a `NoopWatcher`, which does |
| 625 |
// not need to watch anything, and so returns the `Connection` untouched. |
| 626 |
// |
| 627 |
// The `Server::with_graceful_shutdown` needs to keep track of all active |
| 628 |
// connections, and signal that they start to shutdown when prompted, so |
| 629 |
// it has a `GracefulWatcher` implementation to do that. |
| 630 |
pub trait Watcher<I, S: HttpService<Body>, E>: Clone { |
| 631 |
type Future: Future<Output = crate::Result<()>>; |
| 632 |
|
| 633 |
fn watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future; |
| 634 |
} |
| 635 |
|
| 636 |
#[allow(missing_debug_implementations)] |
| 637 |
#[derive(Copy, Clone)] |
| 638 |
pub struct NoopWatcher; |
| 639 |
|
| 640 |
impl<I, S, E> Watcher<I, S, E> for NoopWatcher |
| 641 |
where |
| 642 |
I: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 643 |
S: HttpService<Body>, |
| 644 |
E: ConnStreamExec<S::Future, S::ResBody>, |
| 645 |
S::ResBody: 'static, |
| 646 |
<S::ResBody as HttpBody>::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 647 |
{ |
| 648 |
type Future = UpgradeableConnection<I, S, E>; |
| 649 |
|
| 650 |
fn watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future { |
| 651 |
conn |
| 652 |
} |
| 653 |
} |
| 654 |
|
| 655 |
// used by exec.rs |
| 656 |
pub(crate) mod new_svc { |
| 657 |
use std::error::Error as StdError; |
| 658 |
use tokio::io::{AsyncRead, AsyncWrite}; |
| 659 |
use tracing::debug; |
| 660 |
|
| 661 |
use super::{Connecting, Watcher}; |
| 662 |
use crate::body::{Body, HttpBody}; |
| 663 |
use crate::common::exec::ConnStreamExec; |
| 664 |
use crate::common::{task, Future, Pin, Poll, Unpin}; |
| 665 |
use crate::service::HttpService; |
| 666 |
use pin_project_lite::pin_project; |
| 667 |
|
| 668 |
// This is a `Future<Item=(), Error=()>` spawned to an `Executor` inside |
| 669 |
// the `Server`. By being a nameable type, we can be generic over the |
| 670 |
// user's `Service::Future`, and thus an `Executor` can execute it. |
| 671 |
// |
| 672 |
// Doing this allows for the server to conditionally require `Send` futures, |
| 673 |
// depending on the `Executor` configured. |
| 674 |
// |
| 675 |
// Users cannot import this type, nor the associated `NewSvcExec`. Instead, |
| 676 |
// a blanket implementation for `Executor<impl Future>` is sufficient. |
| 677 |
|
| 678 |
pin_project! { |
| 679 |
#[allow(missing_debug_implementations)] |
| 680 |
pub struct NewSvcTask<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> { |
| 681 |
#[pin] |
| 682 |
state: State<I, N, S, E, W>, |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
pin_project! { |
| 687 |
#[project = StateProj] |
| 688 |
pub(super) enum State<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> { |
| 689 |
Connecting { |
| 690 |
#[pin] |
| 691 |
connecting: Connecting<I, N, E>, |
| 692 |
watcher: W, |
| 693 |
}, |
| 694 |
Connected { |
| 695 |
#[pin] |
| 696 |
future: W::Future, |
| 697 |
}, |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
impl<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> NewSvcTask<I, N, S, E, W> { |
| 702 |
pub(super) fn new(connecting: Connecting<I, N, E>, watcher: W) -> Self { |
| 703 |
NewSvcTask { |
| 704 |
state: State::Connecting { |
| 705 |
connecting, |
| 706 |
watcher, |
| 707 |
}, |
| 708 |
} |
| 709 |
} |
| 710 |
} |
| 711 |
|
| 712 |
impl<I, N, S, NE, B, E, W> Future for NewSvcTask<I, N, S, E, W> |
| 713 |
where |
| 714 |
I: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 715 |
N: Future<Output = Result<S, NE>>, |
| 716 |
NE: Into<Box<dyn StdError + Send + Sync>>, |
| 717 |
S: HttpService<Body, ResBody = B>, |
| 718 |
B: HttpBody + 'static, |
| 719 |
B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 720 |
E: ConnStreamExec<S::Future, B>, |
| 721 |
W: Watcher<I, S, E>, |
| 722 |
{ |
| 723 |
type Output = (); |
| 724 |
|
| 725 |
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { |
| 726 |
// If it weren't for needing to name this type so the `Send` bounds |
| 727 |
// could be projected to the `Serve` executor, this could just be |
| 728 |
// an `async fn`, and much safer. Woe is me. |
| 729 |
|
| 730 |
let mut me = self.project(); |
| 731 |
loop { |
| 732 |
let next = { |
| 733 |
match me.state.as_mut().project() { |
| 734 |
StateProj::Connecting { |
| 735 |
connecting, |
| 736 |
watcher, |
| 737 |
} => { |
| 738 |
let res = ready!(connecting.poll(cx)); |
| 739 |
let conn = match res { |
| 740 |
Ok(conn) => conn, |
| 741 |
Err(err) => { |
| 742 |
let err = crate::Error::new_user_make_service(err); |
| 743 |
debug!("connecting error: {}", err); |
| 744 |
return Poll::Ready(()); |
| 745 |
} |
| 746 |
}; |
| 747 |
let future = watcher.watch(conn.with_upgrades()); |
| 748 |
State::Connected { future } |
| 749 |
} |
| 750 |
StateProj::Connected { future } => { |
| 751 |
return future.poll(cx).map(|res| { |
| 752 |
if let Err(err) = res { |
| 753 |
debug!("connection error: {}", err); |
| 754 |
} |
| 755 |
}); |
| 756 |
} |
| 757 |
} |
| 758 |
}; |
| 759 |
|
| 760 |
me.state.set(next); |
| 761 |
} |
| 762 |
} |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
pin_project! { |
| 767 |
/// A future building a new `Service` to a `Connection`. |
| 768 |
/// |
| 769 |
/// Wraps the future returned from `MakeService` into one that returns |
| 770 |
/// a `Connection`. |
| 771 |
#[must_use = "futures do nothing unless polled"] |
| 772 |
#[derive(Debug)] |
| 773 |
#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))] |
| 774 |
pub struct Connecting<I, F, E = Exec> { |
| 775 |
#[pin] |
| 776 |
future: F, |
| 777 |
io: Option<I>, |
| 778 |
protocol: Http_<E>, |
| 779 |
} |
| 780 |
} |
| 781 |
|
| 782 |
impl<I, F, S, FE, E, B> Future for Connecting<I, F, E> |
| 783 |
where |
| 784 |
I: AsyncRead + AsyncWrite + Unpin, |
| 785 |
F: Future<Output = Result<S, FE>>, |
| 786 |
S: HttpService<Body, ResBody = B>, |
| 787 |
B: HttpBody + 'static, |
| 788 |
B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 789 |
E: ConnStreamExec<S::Future, B>, |
| 790 |
{ |
| 791 |
type Output = Result<Connection<I, S, E>, FE>; |
| 792 |
|
| 793 |
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { |
| 794 |
let mut me = self.project(); |
| 795 |
let service = ready!(me.future.poll(cx))?; |
| 796 |
let io = Option::take(&mut me.io).expect("polled after complete"); |
| 797 |
Poll::Ready(Ok(me.protocol.serve_connection(io, service))) |
| 798 |
} |
| 799 |
} |