This commit is contained in:
Mateusz Gruszczyński committed 2026-10-04 11:15:58 +02:00
1 parent 87e571c170
commit fa7abc9e53
308 files changed
+49746 -50237

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
impl<B> HttpBody for H2TrackedBody<B>
where
B: HttpBody,
{
type Data = B::Data;
type Error = B::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut TaskContext<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
let this = self.get_mut();
match this.inner.as_mut().poll_frame(cx) {
Poll::Ready(None) => {
this.stream.take();
Poll::Ready(None)
}
Poll::Ready(Some(Err(error))) => {
this.stream.take();
Poll::Ready(Some(Err(error)))
}
other => other,
}
}
fn is_end_stream(&self) -> bool {
self.inner.as_ref().get_ref().is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.as_ref().get_ref().size_hint()
}
}
async fn wait_for_h2_idle(state: Arc<H2ConnectionState>, idle: Duration) {
loop {
// Register for a notification before inspecting the state. This avoids
// losing the final stream-drop notification between the load and await.
let notified = state.notify.notified();
tokio::pin!(notified);
if state.active_streams.load(Ordering::Acquire) > 0 {
notified.as_mut().await;
continue;
}
let idle_for = state.idle_for();
if idle_for >= idle {
return;
}
tokio::select! {
_ = tokio::time::sleep(idle.saturating_sub(idle_for)) => {},
_ = notified.as_mut() => {},
}
}
}
struct ActiveHttp2Connection(Option<Arc<Metrics>>);
impl ActiveHttp2Connection {
fn begin(metrics: Option<Arc<Metrics>>) -> Self {
if let Some(metrics) = &metrics {
metrics
.http2_active_connections
.fetch_add(1, Ordering::Relaxed);
}
Self(metrics)
}
}
impl Drop for ActiveHttp2Connection {
fn drop(&mut self) {
if let Some(metrics) = &self.0 {
metrics
.http2_active_connections
.fetch_sub(1, Ordering::Relaxed);
}
}
}
fn h2_prior_knowledge_prefix(bytes: &[u8]) -> bool {
bytes.len() <= HTTP2_PRIOR_KNOWLEDGE_PREFACE.len()
&& HTTP2_PRIOR_KNOWLEDGE_PREFACE.starts_with(bytes)
}
#[derive(Clone, Copy)]
pub struct PeerAddr(pub SocketAddr);
#[derive(Clone, Copy)]
pub struct LocalAddr(pub SocketAddr);
#[derive(Clone, Copy, Default)]
pub struct Transport {
pub tls: bool,
}
#[derive(Clone)]
pub struct ServerShutdown(pub CancellationToken);
#[derive(Clone)]
enum TlsMode {
Frontend(Arc<App>, bool),
Fixed(Arc<rustls::ServerConfig>, Option<Router>),
}
/// Upgraded tunnels hold this lease after Hyper finishes its HTTP connection.
/// This prevents WebSockets from escaping the public connection limit/counter.
pub struct ConnectionLease {
_permit: OwnedSemaphorePermit,
metrics: Option<Arc<Metrics>>,
}
impl Drop for ConnectionLease {
fn drop(&mut self) {
if let Some(m) = &self.metrics {
m.active_connections.fetch_sub(1, Ordering::Relaxed);
}
}
}
pub async fn serve(
listener: TcpListener,
router: Router,
shutdown: CancellationToken,
max_connections: usize,
grace: Duration,
metrics: Option<Arc<Metrics>>,
) -> Result<()> {
serve_inner(
listener,
router,
shutdown,
Arc::new(Semaphore::new(max_connections)),
grace,
metrics,
None,
false,
None,
Http2Connections::default(),
)
.await
}
pub async fn serve_public(
listener: TcpListener,
router: Router,
shutdown: CancellationToken,
permits: Arc<Semaphore>,
grace: Duration,
metrics: Arc<Metrics>,
tls: Option<Arc<App>>,
) -> Result<()> {
serve_frontend(
listener,
router,
shutdown,
permits,
grace,
metrics,
tls.clone().map(|app| (app, true)),
false,
tls,
)
.await
}
pub async fn serve_frontend(
listener: TcpListener,
router: Router,
shutdown: CancellationToken,
permits: Arc<Semaphore>,
grace: Duration,
metrics: Arc<Metrics>,
tls: Option<(Arc<App>, bool)>,
h2c: bool,
frontend_state: Option<Arc<App>>,
) -> Result<()> {
let http2_settings = frontend_state
.as_ref()
.map(|state| state.config.load().envelope.config.http2)
.unwrap_or_default();
serve_frontend_with_http2(
listener,
router,
shutdown,
permits,
grace,
metrics,
tls,
h2c,
frontend_state,
http2_settings,
)
.await
}
/// Start one compiled frontend listener with its immutable per-listener H2
/// lifecycle policy. The public `serve_frontend` wrapper retains the legacy
/// global fallback for callers that do not provide a compiled listener plan.
pub async fn serve_frontend_with_http2(
listener: TcpListener,
router: Router,
shutdown: CancellationToken,
permits: Arc<Semaphore>,
grace: Duration,
metrics: Arc<Metrics>,
tls: Option<(Arc<App>, bool)>,
h2c: bool,
frontend_state: Option<Arc<App>>,
http2_settings: Http2Connections,
) -> Result<()> {
serve_inner(
listener,
router,
shutdown,
permits,
grace,
Some(metrics),
tls.map(|(app, http2)| TlsMode::Frontend(app, http2)),
h2c,
frontend_state,
http2_settings,
)
.await
}
pub async fn serve_tls(
listener: TcpListener,
router: Router,
shutdown: CancellationToken,
max_connections: usize,
grace: Duration,
tls: Arc<rustls::ServerConfig>,
) -> Result<()> {
serve_inner(
listener,
router,
shutdown,
Arc::new(Semaphore::new(max_connections)),
grace,
None,
Some(TlsMode::Fixed(tls, None)),
false,
None,
Http2Connections::default(),
)
.await
}
/// Serve an HTTPS socket while turning accidental/plain HTTP requests on the
/// same port into redirects. No administration handler is exposed through the
/// plaintext router.
pub async fn serve_tls_with_plain_redirect(
listener: TcpListener,
router: Router,
plaintext_router: Router,
shutdown: CancellationToken,
max_connections: usize,
grace: Duration,
tls: Arc<rustls::ServerConfig>,
) -> Result<()> {
serve_inner(
listener,
router,
shutdown,
Arc::new(Semaphore::new(max_connections)),
grace,
None,
Some(TlsMode::Fixed(tls, Some(plaintext_router))),
false,
None,
Http2Connections::default(),
)
.await
}