//! 独立 Rust 资源对照:使用原生 Hyper 值,不导入或复制 Dever 运行库。 use bytes::Bytes; use futures_util::FutureExt; use http_body_util::{BodyExt, Full, Limited}; use hyper::{Request, Response, Uri, body::Incoming}; use hyper_util::{ client::legacy::{ Client, connect::{Connected, Connection, HttpConnector, dns::Name}, }, rt::{TokioIo, TokioTimer}, }; use std::{ any::Any, future::{Future, Ready, ready}, io, net::{SocketAddr, ToSocketAddrs}, panic::AssertUnwindSafe, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll}, time::Duration, }; use tokio::{ net::TcpStream, sync::{OwnedSemaphorePermit, Semaphore}, }; use tokio_util::{sync::CancellationToken, task::TaskTracker}; use tower_service::Service; const TIMEOUT: Duration = Duration::from_secs(5); const READ_TIMEOUT: Duration = Duration::from_secs(60); type Fault = Box; #[derive(Clone, Default)] struct Owner { cancel: CancellationToken, tasks: TaskTracker, faults: Arc>>, } impl Owner { async fn close(&self) { self.cancel.cancel(); self.tasks.close(); self.tasks.wait().await; } fn take_faults(&self) -> Vec { std::mem::take(&mut *self.faults.lock().unwrap()) } async fn run( &self, duration: Duration, work: impl Future>, ) -> io::Result { tokio::select! { biased; () = self.cancel.cancelled() => Err(io::Error::new(io::ErrorKind::NotConnected, "closed")), result = tokio::time::timeout(duration, work) => result.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?, } } } impl + Send + 'static> hyper::rt::Executor for Owner { fn execute(&self, work: F) { let owner = self.clone(); self.tasks.spawn(async move { let result = AssertUnwindSafe(async { tokio::select! { biased; () = owner.cancel.cancelled() => {}, () = work => {}, } }) .catch_unwind() .await; if let Err(fault) = result { owner.faults.lock().unwrap().push(fault); } }); } } #[derive(Clone)] struct FixedDns(Arc>); impl Service for FixedDns { type Response = std::vec::IntoIter; type Error = io::Error; type Future = Ready>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, _: Name) -> Self::Future { ready(Ok(self.0.as_ref().clone().into_iter())) } } #[derive(Clone)] struct Connector { tcp: HttpConnector, slots: Arc, } impl Service for Connector { type Response = Socket; type Error = io::Error; type Future = Pin> + Send>>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { self.tcp.poll_ready(cx).map_err(io::Error::other) } fn call(&mut self, uri: Uri) -> Self::Future { let slots = self.slots.clone(); let connect = self.tcp.call(uri); Box::pin(async move { tokio::time::timeout(TIMEOUT, async { let permit = slots.acquire_owned().await.map_err(io::Error::other)?; Ok(Socket { io: connect.await.map_err(io::Error::other)?, _permit: permit, }) }) .await .map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))? }) } } // HttpConnector 没有总连接限额;许可随真实传输释放,不把空闲连接上限当作总量。 struct Socket { io: TokioIo, _permit: OwnedSemaphorePermit, } impl Connection for Socket { fn connected(&self) -> Connected { self.io.connected() } } impl hyper::rt::Read for Socket { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: hyper::rt::ReadBufCursor<'_>, ) -> Poll> { Pin::new(&mut self.io).poll_read(cx, buf) } } impl hyper::rt::Write for Socket { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { Pin::new(&mut self.io).poll_write(cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.io).poll_flush(cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.io).poll_shutdown(cx) } fn is_write_vectored(&self) -> bool { self.io.is_write_vectored() } fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll> { Pin::new(&mut self.io).poll_write_vectored(cx, bufs) } } struct Pool { client: Client>, owner: Owner, requests: Arc, physical: Arc, origin: hyper::http::uri::Authority, } impl Pool { async fn new(host: String, port: u16, capacity: usize) -> io::Result { let origin = format!("{host}:{port}").parse().map_err(io::Error::other)?; // DNS 只解析一次;超时也等待已启动的阻塞查询退出。 let query = tokio::task::spawn_blocking(move || { (host.as_str(), port) .to_socket_addrs() .map(Iterator::collect::>) }); tokio::pin!(query); let addresses = match tokio::time::timeout(TIMEOUT, &mut query).await { Ok(result) => result.map_err(io::Error::other)??, Err(error) => { query.await.map_err(io::Error::other)??; return Err(io::Error::new(io::ErrorKind::TimedOut, error)); } }; let owner = Owner::default(); let physical = Arc::new(Semaphore::new(capacity)); let mut tcp = HttpConnector::new_with_resolver(FixedDns(Arc::new(addresses))); tcp.set_nodelay(true); tcp.set_connect_timeout(Some(TIMEOUT)); let client = Client::builder(owner.clone()) .pool_timer(TokioTimer::new()) .timer(TokioTimer::new()) .pool_idle_timeout(Duration::from_secs(10)) .pool_max_idle_per_host(capacity) .http1_max_buf_size(8192) .retry_canceled_requests(false) .build(Connector { tcp, slots: physical.clone(), }); Ok(Self { client, owner, requests: Arc::new(Semaphore::new(capacity)), physical, origin, }) } async fn request(&self, request: Request>) -> io::Result> { self.check_request(&request)?; self.owner .run(TIMEOUT, async { let _permit = self.requests.acquire().await.map_err(io::Error::other)?; let response = self .client .request(request) .await .map_err(io::Error::other)?; let (parts, body) = response.into_parts(); check_head(&parts)?; let collected = Limited::new(body, 1048576) .collect() .await .map_err(io::Error::other)?; if let Some(trailers) = collected.trailers() { check_headers(trailers, 0)?; } let body = collected.to_bytes(); if matches!(parts.status.as_u16(), 204 | 205 | 304) && !body.is_empty() { return Err(io::Error::other("body forbidden for status")); } Ok(Response::from_parts(parts, body)) }) .await } async fn open( &self, request: Request>, ) -> io::Result<( hyper::http::response::Parts, streaming::SharedDownload< impl futures_util::Stream> + Send + 'static, >, )> { self.check_request(&request)?; self.owner .run(TIMEOUT, async { let permit = self .requests .clone() .acquire_owned() .await .map_err(io::Error::other)?; let (parts, body) = self .client .request(request) .await .map_err(io::Error::other)? .into_parts(); check_head(&parts)?; let forbidden = matches!(parts.status.as_u16(), 204 | 205 | 304); let download = Download { state: Some((body, permit)), pending: Bytes::new(), owner: self.owner.clone(), forbidden, }; let source = futures_util::stream::unfold(Some(download), |state| async move { let mut download = state?; match download.next().await { Ok(Some(bytes)) => { let next = if download.state.is_some() { Some(download) } else { None }; Some((Ok(bytes), next)) } Ok(None) => None, Err(error) => Some((Err(error), None)), } }); Ok((parts, streaming::SharedDownload::new(source))) }) .await } async fn close(&self) { self.requests.close(); self.owner.close().await; } fn check_request(&self, request: &Request>) -> io::Result<()> { use hyper::body::Body; if request.uri().scheme_str() != Some("http") || request.uri().authority() != Some(&self.origin) || request.method() == hyper::Method::CONNECT { return Err(io::Error::other("request differs from fixed origin")); } if request.body().size_hint().exact().unwrap() > 1048576 { return Err(io::Error::other("request body exceeds limit")); } if ["content-length", "transfer-encoding", "upgrade"] .iter() .any(|name| request.headers().contains_key(*name)) { return Err(io::Error::other("framing headers belong to Hyper")); } let mut hosts = request.headers().get_all("host").iter(); let implicit_host = if let Some(host) = hosts.next() { if hosts.next().is_some() || !host .as_bytes() .eq_ignore_ascii_case(self.origin.as_str().as_bytes()) { return Err(io::Error::other("Host differs from fixed origin")); } 0 } else { // Hyper 自动加入 Host;发送预算必须包含它,不为了计时再造一份头。 8 + self.origin.as_str().len() }; check_headers( request.headers(), 80 + request.method().as_str().len() + request.uri().path_and_query().unwrap().as_str().len() + implicit_host, ) } } impl Drop for Pool { fn drop(&mut self) { self.owner.cancel.cancel(); } } struct Download { state: Option<(Incoming, OwnedSemaphorePermit)>, pending: Bytes, owner: Owner, forbidden: bool, } impl Download { async fn next(&mut self) -> io::Result> { use hyper::body::Body; let Some((body, _permit)) = self.state.as_mut() else { return Ok(None); }; let result = self .owner .run(READ_TIMEOUT, async { loop { if !self.pending.is_empty() { return Ok(Some(self.pending.split_to(self.pending.len().min(65536)))); } let Some(frame) = body.frame().await else { return Ok(None); }; match frame.map_err(io::Error::other)?.into_data() { Ok(bytes) => { if self.forbidden && !bytes.is_empty() { return Err(io::Error::other("body forbidden for status")); } self.pending = bytes; } Err(frame) => check_headers(frame.trailers_ref().unwrap(), 0)?, } } }) .await; if !matches!(result, Ok(Some(_))) || (self.pending.is_empty() && body.is_end_stream()) { self.state.take(); } result } } fn check_headers(headers: &hyper::HeaderMap, initial: usize) -> io::Result<()> { let size = headers.iter().fold(initial, |size, (name, value)| { size + name.as_str().len() + value.as_bytes().len() + 4 }); if size > 8192 { return Err(io::Error::other("headers exceed limit")); } Ok(()) } fn check_head(parts: &hyper::http::response::Parts) -> io::Result<()> { check_headers(&parts.headers, 32)?; if !(200..=599).contains(&parts.status.as_u16()) { return Err(io::Error::other("invalid response status")); } Ok(()) } fn main() { entry::run(); } #[path = "http_resource_entry.rs"] mod entry; #[path = "http_resource_stream.rs"] mod streaming; #[path = "http_resource_server.rs"] mod server; #[path = "http_resource_single.rs"] mod single; #[cfg(test)] #[path = "http_resource_tests.rs"] mod tests;