From a3af42e72008cf29a47923e6b083a9a99965f720 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sat, 21 Nov 2026 08:55:25 +1300 Subject: [PATCH 1/2] Move `Handler` into `base-http` as the shared request interface, with server and client contexts. --- benchmarks/hello/src/main.rs | 18 +- crates/client/examples/client_server.rs | 9 +- crates/client/tests/client/idle.rs | 6 +- crates/client/tests/https.rs | 9 +- crates/client/tests/protocol.rs | 6 +- crates/client/tests/writable/main.rs | 7 +- crates/content/tests/server.rs | 13 +- crates/fixtures/readme.md | 10 +- crates/fixtures/src/context.rs | 43 ++-- crates/fixtures/src/context/tests.rs | 11 +- crates/fixtures/src/lib.rs | 2 +- crates/fixtures/src/protocol.rs | 23 +- crates/fixtures/src/scheduler.rs | 7 +- crates/fixtures/tests/context.rs | 18 +- crates/fixtures/tests/protocol.rs | 56 +++-- crates/fixtures/tests/raw.rs | 12 +- crates/fixtures/tests/spawned.rs | 28 +-- crates/server/examples/client_server.rs | 9 +- crates/server/examples/hello.rs | 9 +- crates/server/readme.md | 14 +- crates/server/src/lib.rs | 180 +++++++------ crates/server/tests/accept_errors.rs | 25 +- crates/server/tests/end_to_end.rs | 94 +++---- crates/server/tests/lent_bodies.rs | 24 +- crates/server/tests/listener.rs | 9 +- crates/server/tests/nodelay.rs | 24 +- crates/server/tests/peer.rs | 64 +++++ crates/server/tests/proxy.rs | 14 +- crates/server/tests/support/mod.rs | 5 +- crates/server/tests/tls.rs | 27 +- crates/server/tests/transport_faults.rs | 84 ++++++- design/fixtures.md | 8 +- design/implementation.md | 2 +- design/load-balancer.md | 2 +- design/middleware.md | 5 +- src/handler.rs | 189 ++++++++++++++ src/interim.rs | 3 + src/interim/relay.rs | 318 +++++++++++++++++++++++ src/lib.rs | 10 +- src/peer.rs | 68 +++++ tests/handler.rs | 319 ++++++++++++++++++++++++ 41 files changed, 1454 insertions(+), 330 deletions(-) create mode 100644 crates/server/tests/peer.rs create mode 100644 src/handler.rs create mode 100644 src/interim/relay.rs create mode 100644 src/peer.rs create mode 100644 tests/handler.rs diff --git a/benchmarks/hello/src/main.rs b/benchmarks/hello/src/main.rs index 3e591bfd..354595b0 100644 --- a/benchmarks/hello/src/main.rs +++ b/benchmarks/hello/src/main.rs @@ -1,14 +1,16 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::ServerContext; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_server::Handler; use base_scheduler::{ - Cancellation, SocketAccept, SocketClose, SocketRegistration, SocketSetOption, - SocketStreamReading, SocketStreamWriting, Spawn, TcpNoDelay, + Cancellation, SocketAccept, SocketClose, SocketLocalAddress, SocketPeerAddress, + SocketRegistration, SocketSetOption, SocketStreamReading, SocketStreamWriting, Spawn, + TcpNoDelay, }; use base_scheduler_native::{NativeOptions, NativeScheduler}; use base_scheduler_tokio::TokioScheduler; @@ -30,15 +32,15 @@ const MAX_CONNECTIONS: usize = 1024; const STALL_RESCUE: bool = true; struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = Infallible; type Body = BufferedBody<&'static [u8]>; #[allow(clippy::manual_async_fn)] // Drop the unused request at the service-call boundary. - fn call( + fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> impl std::future::Future>, Infallible>> + Send { @@ -76,7 +78,9 @@ where + SocketSetOption + SocketStreamReading + SocketStreamWriting - + SocketClose, + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, { let listener = TcpListener::bind("127.0.0.1:0")?; diff --git a/crates/client/examples/client_server.rs b/crates/client/examples/client_server.rs index 5a72747f..47e80e11 100644 --- a/crates/client/examples/client_server.rs +++ b/crates/client/examples/client_server.rs @@ -5,11 +5,12 @@ //! through the pooled client, and joins the HTTP and transport cleanup. use base_endpoint::{AddressEndpoint, BindEndpoint, BindOptions}; use base_http::{ - InterimHandler, InterimResponses, Method, Request, RequestMetadata, Response, Status, + Method, Request, RequestMetadata, Response, Status, body::{BodyFrame, BufferedBody, ReadableBody}, }; use base_http_client::{Client, Endpoint}; use base_http_server::Handler; +use base_http_server::ServerContext; use base_scheduler::{Cancellation, SocketAccept, SocketClose, SocketLocalAddress}; use base_scheduler_native::NativeScheduler; use futures_lite::future::{block_on, zip}; @@ -17,13 +18,13 @@ use std::{convert::Infallible, future::Future, net::SocketAddr}; type Result = std::result::Result>; struct Echo; -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = Infallible; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> std::result::Result, Infallible> { Ok(Response::new(Status::OK, request.body)) diff --git a/crates/client/tests/client/idle.rs b/crates/client/tests/client/idle.rs index b183093c..1452c0c7 100644 --- a/crates/client/tests/client/idle.rs +++ b/crates/client/tests/client/idle.rs @@ -4,15 +4,15 @@ //! Pooled connections the server closes or writes to while idle are retired before reuse, and the request runs on a fresh connection. use base_http::{Method, Request, RequestMetadata, Status, body::EmptyBody}; use base_http_client::{Client, Options}; -use base_http_fixtures::{ClientContext, Latch, RawServer, body::payload}; +use base_http_fixtures::{ClientFixture, Latch, RawServer, body::payload}; use base_scheduler::Cancellation; const FIRST: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst"; const NEXT: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nnext"; // One pooled connection, so the second request must either reuse the idle connection or retire it first. -fn client(server: &RawServer) -> ClientContext { - ClientContext::new(server.endpoint()).options(Options { +fn client(server: &RawServer) -> ClientFixture { + ClientFixture::new(server.endpoint()).options(Options { pool: base_pool::Options { max_resources: 1, ..Default::default() diff --git a/crates/client/tests/https.rs b/crates/client/tests/https.rs index 23af7088..ec487731 100644 --- a/crates/client/tests/https.rs +++ b/crates/client/tests/https.rs @@ -2,10 +2,11 @@ // Copyright, 2026, by Samuel Williams. #![cfg(feature = "rustls")] +use base_http_server::ServerContext; use base_endpoint::{AddressEndpoint, BindEndpoint, BindOptions}; use base_http::{ - InterimHandler, InterimResponses, Method, Request, Response, Status, + Method, Request, Response, Status, body::{BodyFrame, BufferedBody, EmptyBody, ReadableBody}, }; use base_http_client::{Client, Endpoint, Error, Options}; @@ -58,13 +59,13 @@ async fn payload(body: &mut impl ReadableBody) -> Vec { } } struct Echo; -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = Infallible; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Infallible> { assert_eq!(request.scheme.as_deref(), Some("https")); diff --git a/crates/client/tests/protocol.rs b/crates/client/tests/protocol.rs index 169d1a6a..18a58f2d 100644 --- a/crates/client/tests/protocol.rs +++ b/crates/client/tests/protocol.rs @@ -3,11 +3,11 @@ //! The shared protocol cases, run between this client and the Base server for each HTTP version and transport. use base_http::Version; -use base_http_fixtures::{Context, ServerContext, protocol::App}; +use base_http_fixtures::{Context, ServerFixture, protocol::App}; use base_scheduler_native::NativeScheduler; -fn serve(app: App, version: Version) -> ServerContext { - ServerContext::new().handler(app).version(version) +fn serve(app: App, version: Version) -> ServerFixture { + ServerFixture::new().handler(app).version(version) } fn http11(app: App, test: impl AsyncFnOnce(&Context<'_, NativeScheduler, App>)) { diff --git a/crates/client/tests/writable/main.rs b/crates/client/tests/writable/main.rs index a0a92fed..91188161 100644 --- a/crates/client/tests/writable/main.rs +++ b/crates/client/tests/writable/main.rs @@ -5,6 +5,7 @@ mod support; mod open; +use base_http_server::ServerContext; use base_http::{ Fields, Method, Request, RequestMetadata, Scheme, @@ -839,13 +840,13 @@ fn cancelled_and_dropped_open_waiters_do_not_abandon_active_exchange() { } struct Echo; -impl<'h> base_http_server::Handler<'h> for Echo { +impl<'h> base_http_server::Handler<'h, ServerContext> for Echo { type Error = std::convert::Infallible; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut base_http::InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Self::Error> { Ok(base_http::Response::new( diff --git a/crates/content/tests/server.rs b/crates/content/tests/server.rs index 04ff1afe..09c63d73 100644 --- a/crates/content/tests/server.rs +++ b/crates/content/tests/server.rs @@ -2,13 +2,14 @@ // Copyright, 2026, by Samuel Williams. //! Reading content in a `base-http-server` handler, over real connections. +use base_http_server::ServerContext; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_content::{FileStore, read_content}; -use base_http_fixtures::{RawPeer, ServerContext}; +use base_http_fixtures::{RawPeer, ServerFixture}; use base_http_server::Handler; use base_scheduler::Cancellation; use base_scheduler_native::NativeScheduler; @@ -40,14 +41,14 @@ struct Profiles { next: Arc, } -impl<'h> Handler<'h> for Profiles { +impl<'h> Handler<'h, ServerContext> for Profiles { type Error = Infallible; type Body = BufferedBody>; - async fn call( + async fn call( &self, mut request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result>, Infallible> { let mut store = FileStore::new(&*self.scheduler, |_: &FieldPath| { @@ -83,7 +84,7 @@ fn serve( directory: directory.path().to_owned(), next: next.clone(), }; - let output = ServerContext::new() + let output = ServerFixture::new() .handler(profiles) .run_spawned(async |context| context.raw(peer).await); futures_lite::future::block_on(scheduler.shutdown()); diff --git a/crates/fixtures/readme.md b/crates/fixtures/readme.md index 97425745..a91af919 100644 --- a/crates/fixtures/readme.md +++ b/crates/fixtures/readme.md @@ -2,14 +2,14 @@ Shared test fixtures and behaviour suites for Base HTTP, following Socketry's `sus-fixtures-async-http` and the `AProtocol` and `AReadableBody` shared contexts of `async-http` and `protocol-http`. This crate is unpublished; the workspace's crates use it as a development dependency. -[`ServerContext`] serves a handler on an OS-selected loopback port and runs a test beside the server and a connected client, then tears both down in order within a bounded time: +[`ServerFixture`] serves a handler on an OS-selected loopback port and runs a test beside the server and a connected client, then tears both down in order within a bounded time: ```rust use base_http::{Method, Status, body::EmptyBody}; -use base_http_fixtures::{ServerContext, body::payload}; +use base_http_fixtures::{ServerFixture, body::payload}; use base_scheduler::Cancellation; -ServerContext::new().run(async |context| { +ServerFixture::new().run(async |context| { let request = context.request(Method::GET, "/", EmptyBody); let mut response = context .client() @@ -21,8 +21,8 @@ ServerContext::new().run(async |context| { }); ``` -[`ServerContext::run`] polls the server, the client and the test together on the test's thread, which makes interleavings reproducible but cannot run them in parallel. [`ServerContext::run_spawned`] instead spawns the server onto the workers of its own Native scheduler and drives the client from the test's thread, with the same bounds and teardown, so cross-thread wake-ups and races can show up. +[`ServerFixture::run`] polls the server, the client and the test together on the test's thread, which makes interleavings reproducible but cannot run them in parallel. [`ServerFixture::run_spawned`] instead spawns the server onto the workers of its own Native scheduler and drives the client from the test's thread, with the same bounds and teardown, so cross-thread wake-ups and races can show up. -[`ClientContext`] runs a client of any endpoint, such as a [`RawServer`]. Raw peers in [`raw`] speak HTTP/1 over blocking `std::net` sockets, so they can misbehave in ways the Base server cannot: responding then closing, stalling after a head, truncating a body, or closing or writing to an idle connection. [`RawPeer::split`] gives a peer separate reading and writing halves, for uploading and downloading at once from two threads. [`socket`] waits until a peer's kernel has acknowledged what was sent, so a test observes a close or unsolicited input without sleeping. +[`ClientFixture`] runs a client of any endpoint, such as a [`RawServer`]. Raw peers in [`raw`] speak HTTP/1 over blocking `std::net` sockets, so they can misbehave in ways the Base server cannot: responding then closing, stalling after a head, truncating a body, or closing or writing to an idle connection. [`RawPeer::split`] gives a peer separate reading and writing halves, for uploading and downloading at once from two threads. [`socket`] waits until a peer's kernel has acknowledged what was sent, so a test observes a close or unsolicited input without sleeping. [`protocol_tests!`] and [`protocol_trailer_tests!`] generate the shared HTTP protocol cases for a runner, and [`readable_body_tests!`] generates the `ReadableBody` contract cases for a body type. diff --git a/crates/fixtures/src/context.rs b/crates/fixtures/src/context.rs index 39d4f111..d3d527e0 100644 --- a/crates/fixtures/src/context.rs +++ b/crates/fixtures/src/context.rs @@ -1,9 +1,10 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::ServerContext; use crate::{Latch, RawPeer, Scheduler, native}; use base_http::{ - InterimHandler, InterimResponses, Method, Request, Response, Status, Version, + Method, Request, Response, Status, Version, body::{BufferedBody, ReadableBody}, }; use base_http_client::{Client, Driver, Endpoint}; @@ -37,14 +38,14 @@ pub const TEARDOWN_TIMEOUT: Duration = Duration::from_secs(5); #[derive(Clone, Copy, Debug, Default)] pub struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = Infallible; type Body = BufferedBody<&'static [u8]>; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result>, Infallible> { Ok(Response::new( @@ -109,11 +110,11 @@ pub const SERVER_NAME: &str = "localhost"; /// A server bound to an OS-selected loopback port, with a client connected to it, for the duration of one test. /// -/// This follows `sus-fixtures-async-http`'s `ServerContext`: builder methods replace its overridable `app`, `protocol`, endpoint and client options. [`ServerContext::run`] binds the listener before serving, so the client never races the server's start, then runs the test beside the server and the client's driver. +/// This follows `sus-fixtures-async-http`'s `ServerContext`: builder methods replace its overridable `app`, `protocol`, endpoint and client options. [`ServerFixture::run`] binds the listener before serving, so the client never races the server's start, then runs the test beside the server and the client's driver. /// -/// Rust has no asynchronous destructor, so teardown happens inside `run`, in order: the client stops accepting calls and retires its connections, then the server stops, closing its listener and joining its connections. Teardown is bounded by [`ServerContext::teardown_timeout`]; when it expires, the client and server are cancelled, still joined, and the test fails. A panic in the test is propagated after teardown. The test must not return a response body it has not finished with, since its connection cannot retire. +/// Rust has no asynchronous destructor, so teardown happens inside `run`, in order: the client stops accepting calls and retires its connections, then the server stops, closing its listener and joining its connections. Teardown is bounded by [`ServerFixture::teardown_timeout`]; when it expires, the client and server are cancelled, still joined, and the test fails. A panic in the test is propagated after teardown. The test must not return a response body it has not finished with, since its connection cannot retire. #[derive(Debug)] -pub struct ServerContext { +pub struct ServerFixture { handler: H, version: Version, server: base_http_server::Options, @@ -123,7 +124,7 @@ pub struct ServerContext { tls: Option, } -impl ServerContext { +impl ServerFixture { /// Serve [`Hello`] over HTTP/1.1 with default options. pub fn new() -> Self { Self { @@ -138,16 +139,16 @@ impl ServerContext { } } -impl Default for ServerContext { +impl Default for ServerFixture { fn default() -> Self { Self::new() } } -impl ServerContext { +impl ServerFixture { /// Serve `handler` instead, as overriding `app` does. - pub fn handler(self, handler: A) -> ServerContext { - ServerContext { + pub fn handler(self, handler: A) -> ServerFixture { + ServerFixture { handler, version: self.version, server: self.server, @@ -196,7 +197,7 @@ impl ServerContext { } } -impl Handler<'h>> ServerContext { +impl Handler<'h, ServerContext>> ServerFixture { /// Run `test` with a fresh Native scheduler, which is shut down afterwards. pub fn run(self, test: impl AsyncFnOnce(&Context<'_, NativeScheduler, H>) -> T) -> T { native(|scheduler| self.run_on(scheduler, test)) @@ -284,12 +285,12 @@ impl Handler<'h>> ServerContext { } } -impl Handler<'h> + Send + Sync + 'static> ServerContext { +impl Handler<'h, ServerContext> + Send + Sync + 'static> ServerFixture { /// Run `test` against a server spawned onto the workers of a fresh two-worker Native scheduler, with the client driven from the test's thread, then stop the server and shut the scheduler down. /// - /// Unlike [`ServerContext::run`], the server makes progress on the scheduler's workers rather than on the test's thread, so it runs in parallel with the client. That exposes cross-thread wake-ups and races which a single `block_on` hides, at the cost of reproducible interleavings. The fixture relies only on the server running on the scheduler's workers; how the server spreads its connections across them is the server's choice and may change. The context owns the scheduler and the application, so the application must be `Send + Sync + 'static`, as a server spawning its own tasks needs. + /// Unlike [`ServerFixture::run`], the server makes progress on the scheduler's workers rather than on the test's thread, so it runs in parallel with the client. That exposes cross-thread wake-ups and races which a single `block_on` hides, at the cost of reproducible interleavings. The fixture relies only on the server running on the scheduler's workers; how the server spreads its connections across them is the server's choice and may change. The context owns the scheduler and the application, so the application must be `Send + Sync + 'static`, as a server spawning its own tasks needs. /// - /// This has the guarantees of [`ServerContext::run`]: the listener is bound before the test starts, the test is bounded, the client retires its connections before the server stops, the server is cancelled and must stop within the teardown timeout, a server error fails the test, a server panic is resumed with its own payload, and a test failure is reported first, with any server failure printed beforehand. The server's teardown timeout is measured on a thread of its own, so a server occupying every worker still fails its join on time. Native's stall rescue, on by default since scheduler 0.5, would let the scheduler's clock bound the join too, but it can be turned off with `stall_rescue: false`, and then a timer is stranded behind the busy worker, so the fixture does not depend on it. The own-thread deadline can be removed once Native fires timers behind a busy worker in every configuration. The test's timeout and the client's teardown are still measured by the scheduler's clock, so they are bounded only while the scheduler's timers can run. + /// This has the guarantees of [`ServerFixture::run`]: the listener is bound before the test starts, the test is bounded, the client retires its connections before the server stops, the server is cancelled and must stop within the teardown timeout, a server error fails the test, a server panic is resumed with its own payload, and a test failure is reported first, with any server failure printed beforehand. The server's teardown timeout is measured on a thread of its own, so a server occupying every worker still fails its join on time. Native's stall rescue, on by default since scheduler 0.5, would let the scheduler's clock bound the join too, but it can be turned off with `stall_rescue: false`, and then a timer is stranded behind the busy worker, so the fixture does not depend on it. The own-thread deadline can be removed once Native fires timers behind a busy worker in every configuration. The test's timeout and the client's teardown are still measured by the scheduler's clock, so they are bounded only while the scheduler's timers can run. /// /// Shutting the scheduler down afterwards waits for every task's current poll to return. A poll which never returns, such as a handler blocked forever, cannot be preempted, so it hangs the test after the failure is reported. pub fn run_spawned( @@ -533,7 +534,7 @@ async fn listen(scheduler: &S) -> S::Socket { socket } -/// What a test receives from [`ServerContext::run`] or [`ServerContext::run_spawned`]. +/// What a test receives from [`ServerFixture::run`] or [`ServerFixture::run_spawned`]. pub struct Context<'s, S, H> { scheduler: &'s S, // Shared with a spawned server's task. @@ -589,7 +590,7 @@ impl<'s, S, H> Context<'s, S, H> { /// Run `work` with a raw client connected to the server, for wire-level requests, on its own thread. It does not use TLS. /// - /// The client's driver, and with [`ServerContext::run`] the server too, runs on the test's thread, so a blocking peer there would stall them; the test instead awaits the peer thread without blocking. A panic in `work` propagates. + /// The client's driver, and with [`ServerFixture::run`] the server too, runs on the test's thread, so a blocking peer there would stall them; the test instead awaits the peer thread without blocking. A panic in `work` propagates. pub async fn raw( &self, work: impl FnOnce(RawPeer) -> T + Send + 'static, @@ -624,15 +625,15 @@ impl Drop for Released { /// A client of an existing endpoint, such as a [`RawServer`](crate::RawServer), for the duration of one test. /// -/// The client's driver runs beside the test. Teardown follows [`ServerContext`]: the client stops accepting calls and retires its connections within a bounded time, the test fails if any connection remains, and a panic in the test is propagated afterwards. +/// The client's driver runs beside the test. Teardown follows [`ServerFixture`]: the client stops accepting calls and retires its connections within a bounded time, the test fails if any connection remains, and a panic in the test is propagated afterwards. #[derive(Debug)] -pub struct ClientContext { +pub struct ClientFixture { endpoint: Endpoint, options: base_http_client::Options, limits: Limits, } -impl ClientContext { +impl ClientFixture { /// A client of `endpoint` with default options. pub fn new(endpoint: Endpoint) -> Self { Self { diff --git a/crates/fixtures/src/context/tests.rs b/crates/fixtures/src/context/tests.rs index 8189a910..f18c986e 100644 --- a/crates/fixtures/src/context/tests.rs +++ b/crates/fixtures/src/context/tests.rs @@ -1,8 +1,9 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::ServerContext; use super::*; -use base_http::{InterimHandler, InterimResponses, Request, Response, Status, body::EmptyBody}; +use base_http::{Request, Response, Status, body::EmptyBody}; use std::{convert::Infallible, io::Write, net::TcpStream}; /// Blocks its worker in every call until released, so the server cannot observe cancellation. @@ -11,14 +12,14 @@ struct Blocking { release: Latch, } -impl<'h> Handler<'h> for Blocking { +impl<'h> Handler<'h, ServerContext> for Blocking { type Error = Infallible; type Body = EmptyBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Infallible> { self.started.release(); @@ -31,7 +32,7 @@ impl<'h> Handler<'h> for Blocking { #[test] fn a_server_occupying_the_only_worker_fails_its_join() { let (started, release) = (Latch::new(), Latch::new()); - let context = ServerContext::new() + let context = ServerFixture::new() .handler(Blocking { started: started.clone(), release: release.clone(), diff --git a/crates/fixtures/src/lib.rs b/crates/fixtures/src/lib.rs index 7730ca32..7ca5c09a 100644 --- a/crates/fixtures/src/lib.rs +++ b/crates/fixtures/src/lib.rs @@ -15,7 +15,7 @@ pub mod socket; #[cfg(feature = "rustls")] pub use context::SERVER_NAME; -pub use context::{ClientContext, Context, Hello, ServerContext, TEARDOWN_TIMEOUT, TEST_TIMEOUT}; +pub use context::{ClientFixture, Context, Hello, ServerFixture, TEARDOWN_TIMEOUT, TEST_TIMEOUT}; pub use latch::{LATCH_TIMEOUT, Latch}; pub use raw::{RawListener, RawPeer, RawReader, RawServer, RawWriter}; pub use scheduler::{Scheduler, native}; diff --git a/crates/fixtures/src/protocol.rs b/crates/fixtures/src/protocol.rs index 814f0d30..698809d7 100644 --- a/crates/fixtures/src/protocol.rs +++ b/crates/fixtures/src/protocol.rs @@ -4,11 +4,11 @@ //! The [`protocol_tests!`](crate::protocol_tests) suite, ported from `async-http`'s `AProtocol` shared behaviour. //! //! One application, [`App`], serves every case on its own route, so a runner only chooses how to serve and connect: the HTTP version, options and transport. Each case is a standalone `pub async fn` taking the running [`Context`], so a partial implementation can call a subset. The cases address the application through `H: Borrow`, so a test can wrap it to change its behaviour. +use base_http_server::{HandlerContext, ServerContext}; use crate::{Context, Latch, Scheduler, body}; use base_http::{ - Fields, InterimHandler, InterimResponses, Method, Request, Response, ResponseMetadata, Status, - Version, + Fields, Method, Request, Response, ResponseMetadata, Status, Version, body::{BodyError, BodyFrame, BodyReader, BufferedBody, ReadableBody}, }; use base_http_server::Handler; @@ -82,14 +82,14 @@ fn text(status: Status, text: impl Into>) -> Response Handler<'h> for App { +impl<'h> Handler<'h, ServerContext> for App { type Error = io::Error; type Body = Reply; - async fn call( + async fn call( &self, mut request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result>, io::Error> { let version = request.version.unwrap_or(Version::Http11); @@ -123,7 +123,10 @@ impl<'h> Handler<'h> for App { let mut hint = ResponseMetadata::new(Status::EARLY_HINTS); hint.fields.add("link", LINK).expect("valid field"); // HTTP/1.0 has no interim responses, so the server refuses this one; a hint is advisory and its failure does not prevent the final response. - let _ = interim.send_interim_response(hint, cancellation).await; + let _ = context + .interim() + .send_interim_response(hint, cancellation) + .await; text(Status::OK, "Hello World") } (_, "/request-trailer") => { @@ -747,15 +750,15 @@ pub async fn response_trailer>(context: &Context<'_ /// Generate `#[test]` functions for the version-independent protocol cases, ported from `async-http`'s `AProtocol`. /// -/// The runner receives a fresh [`App`] and an async closure taking the running [`Context`]. It chooses the version, options and transport, typically by serving the application with a [`ServerContext`](crate::ServerContext), and owns the deadline. [`ServerContext::run`](crate::ServerContext::run) runs the server, the client and the case on the test's thread, which is reproducible; [`ServerContext::run_spawned`](crate::ServerContext::run_spawned) runs the server on the scheduler's workers in parallel with the client, which can expose cross-thread wake-up bugs and races. Invoke it inside a dedicated module: +/// The runner receives a fresh [`App`] and an async closure taking the running [`Context`]. It chooses the version, options and transport, typically by serving the application with a [`ServerFixture`](crate::ServerFixture), and owns the deadline. [`ServerFixture::run`](crate::ServerFixture::run) runs the server, the client and the case on the test's thread, which is reproducible; [`ServerFixture::run_spawned`](crate::ServerFixture::run_spawned) runs the server on the scheduler's workers in parallel with the client, which can expose cross-thread wake-up bugs and races. Invoke it inside a dedicated module: /// /// ``` /// use base_http::Version; -/// use base_http_fixtures::{Context, ServerContext, protocol::App}; +/// use base_http_fixtures::{Context, ServerFixture, protocol::App}; /// use base_scheduler_native::NativeScheduler; /// /// fn http10(app: App, test: impl AsyncFnOnce(&Context<'_, NativeScheduler, App>)) { -/// ServerContext::new() +/// ServerFixture::new() /// .handler(app) /// .version(Version::Http10) /// .run(test); @@ -767,7 +770,7 @@ pub async fn response_trailer>(context: &Context<'_ /// /// // The same cases with the server spawned onto the scheduler's workers, in parallel with the client. /// fn http10_spawned(app: App, test: impl AsyncFnOnce(&Context<'_, NativeScheduler, App>)) { -/// ServerContext::new() +/// ServerFixture::new() /// .handler(app) /// .version(Version::Http10) /// .run_spawned(test); diff --git a/crates/fixtures/src/scheduler.rs b/crates/fixtures/src/scheduler.rs index 481c7e10..16fea8c5 100644 --- a/crates/fixtures/src/scheduler.rs +++ b/crates/fixtures/src/scheduler.rs @@ -3,8 +3,8 @@ use base_scheduler::{ Clock, SocketAccept, SocketBind, SocketClose, SocketConnect, SocketListen, SocketLocalAddress, - SocketOpen, SocketOperation, SocketSetOption, SocketStreamReading, SocketStreamWriting, - TcpNoDelay, + SocketOpen, SocketOperation, SocketPeerAddress, SocketSetOption, SocketStreamReading, + SocketStreamWriting, TcpNoDelay, }; use base_scheduler_native::{NativeOptions, NativeScheduler}; use futures_lite::future::block_on; @@ -18,6 +18,7 @@ pub trait Scheduler: + SocketBind + SocketListen + SocketLocalAddress + + SocketPeerAddress + SocketAccept + SocketConnect + SocketClose @@ -34,6 +35,8 @@ impl Scheduler for S where + SocketBind + SocketListen + SocketLocalAddress + + SocketPeerAddress + + SocketPeerAddress + SocketAccept + SocketConnect + SocketClose diff --git a/crates/fixtures/tests/context.rs b/crates/fixtures/tests/context.rs index 6983b7ca..3113df15 100644 --- a/crates/fixtures/tests/context.rs +++ b/crates/fixtures/tests/context.rs @@ -4,7 +4,7 @@ //! A server context serves, connects, bounds and tears down a test, and reports each way it can fail. use base_http::{Method, Status, body::EmptyBody}; use base_http_fixtures::{ - ClientContext, Hello, Latch, RawServer, ServerContext, TEARDOWN_TIMEOUT, TEST_TIMEOUT, + ClientFixture, Hello, Latch, RawServer, ServerFixture, TEARDOWN_TIMEOUT, TEST_TIMEOUT, body::payload, native, }; use base_scheduler::Cancellation; @@ -12,7 +12,7 @@ use std::time::Duration; #[test] fn the_default_context_serves_hello_to_its_client_and_a_raw_peer() { - let output = ServerContext::default() + let output = ServerFixture::default() .server_options(base_http_server::Options::default()) .client_options(base_http_client::Options::default()) .timeout(TEST_TIMEOUT) @@ -49,13 +49,13 @@ fn the_default_context_serves_hello_to_its_client_and_a_raw_peer() { #[test] #[should_panic(expected = "the test failed")] fn a_test_panic_propagates_after_teardown() { - ServerContext::new().run(async |_| panic!("the test failed")); + ServerFixture::new().run(async |_| panic!("the test failed")); } #[test] #[should_panic(expected = "test exceeded")] fn a_test_exceeding_its_timeout_fails() { - ServerContext::new() + ServerFixture::new() .timeout(Duration::from_millis(10)) .run(async |_| { let _ = Latch::new().wait(&Cancellation::never()).await; @@ -66,7 +66,7 @@ fn a_test_exceeding_its_timeout_fails() { #[test] #[should_panic(expected = "teardown exceeded")] fn a_teardown_exceeding_its_timeout_is_forced_and_fails() { - ServerContext::new() + ServerFixture::new() .teardown_timeout(Duration::from_millis(50)) .run(async |context| { context @@ -83,7 +83,7 @@ fn a_teardown_exceeding_its_timeout_is_forced_and_fails() { #[test] #[should_panic(expected = "server failed")] fn a_server_failure_fails_the_test() { - ServerContext::new() + ServerFixture::new() .server_options(base_http_server::Options { max_connections: 0, ..Default::default() @@ -94,7 +94,7 @@ fn a_server_failure_fails_the_test() { #[test] fn a_client_context_runs_against_a_raw_server() { let server = RawServer::respond_then_close("HTTP/1.1 204 No Content\r\n\r\n"); - let status = ClientContext::new(server.endpoint()) + let status = ClientFixture::new(server.endpoint()) .options(base_http_client::Options::default()) .timeout(TEST_TIMEOUT) .teardown_timeout(TEARDOWN_TIMEOUT) @@ -119,7 +119,7 @@ fn native_shuts_down_before_propagating_a_panic() { #[test] #[should_panic(expected = "the raw peer failed")] fn a_raw_peer_panic_propagates() { - ServerContext::new().run(async |context| { + ServerFixture::new().run(async |context| { context.raw(|_| panic!("the raw peer failed")).await; }); } @@ -128,7 +128,7 @@ fn a_raw_peer_panic_propagates() { #[test] #[should_panic(expected = "the test failed first")] fn a_test_panic_is_reported_before_a_server_failure() { - ServerContext::new() + ServerFixture::new() .server_options(base_http_server::Options { max_connections: 0, ..Default::default() diff --git a/crates/fixtures/tests/protocol.rs b/crates/fixtures/tests/protocol.rs index 33f62c96..993dee2d 100644 --- a/crates/fixtures/tests/protocol.rs +++ b/crates/fixtures/tests/protocol.rs @@ -3,14 +3,15 @@ //! Each protocol case fails, at the assertion it exists for, against an application which breaks that case. use base_http::{ - InterimHandler, InterimResponses, Method, Request, Response, ResponseMetadata, Status, Version, + Method, Request, Response, ResponseMetadata, Status, Version, body::{BodyReader, BufferedBody, ReadableBody}, }; use base_http_fixtures::{ - ServerContext, body, + ServerFixture, body, protocol::{self, App, LARGE_BODY, Reply, Staged, Step}, }; use base_http_server::Handler; +use base_http_server::{HandlerContext, ServerContext}; use base_scheduler::Cancellation; use base_scheduler::Clock; use futures_lite::future::{or, zip}; @@ -34,14 +35,14 @@ fn route(mut request: Request, path: &str) -> Request { request } -impl<'h> Handler<'h> for Sabotaged { +impl<'h> Handler<'h, ServerContext> for Sabotaged { type Error = io::Error; type Body = Reply; - async fn call( + async fn call( &self, mut request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result>, io::Error> { let path = request.path.as_deref().unwrap_or_default().to_owned(); @@ -59,7 +60,8 @@ impl<'h> Handler<'h> for Sabotaged { (_, "/length") => reply("Content Length: 0!"), // Send a hint without its link. (_, "/interim") => { - let _ = interim + let _ = context + .interim() .send_interim_response(ResponseMetadata::new(Status::EARLY_HINTS), cancellation) .await; reply("Hello World") @@ -70,7 +72,7 @@ impl<'h> Handler<'h> for Sabotaged { (_, "/broken") => { return self .0 - .call(route(request, "/"), interim, cancellation) + .call(route(request, "/"), context, cancellation) .await; } // Lose the first chunk of the stream. @@ -125,7 +127,7 @@ macro_rules! sabotaged { #[test] #[should_panic(expected = $message)] fn $name() { - ServerContext::new() + ServerFixture::new() .handler(Sabotaged(App::new())) .run(async |context| protocol::$name(context).await); } @@ -152,7 +154,7 @@ sabotaged! { #[test] #[should_panic(expected = "the request data and trailer the handler received")] fn request_trailer_http10() { - ServerContext::new() + ServerFixture::new() .handler(Sabotaged(App::new())) .version(Version::Http10) .run(async |context| protocol::request_trailer(context).await); @@ -161,7 +163,7 @@ fn request_trailer_http10() { #[test] #[should_panic(expected = "data after the response trailer")] fn response_trailer_http10() { - ServerContext::new() + ServerFixture::new() .handler(Sabotaged(App::new())) .version(Version::Http10) .run(async |context| protocol::response_trailer(context).await); @@ -171,7 +173,7 @@ fn response_trailer_http10() { #[test] #[should_panic(expected = "the echo's framing")] fn duplex_chunked_stream_http10() { - ServerContext::new() + ServerFixture::new() .handler(Sabotaged(App::new())) .version(Version::Http10) .run(async |context| protocol::duplex_chunked_stream(context).await); @@ -186,18 +188,18 @@ impl Borrow for Misrouted { } } -impl<'h> Handler<'h> for Misrouted { +impl<'h> Handler<'h, ServerContext> for Misrouted { type Error = io::Error; type Body = Reply; - async fn call( + async fn call( &self, request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result>, io::Error> { self.0 - .call(route(request, "/missing"), interim, cancellation) + .call(route(request, "/missing"), context, cancellation) .await } } @@ -206,7 +208,7 @@ impl<'h> Handler<'h> for Misrouted { #[test] #[should_panic(expected = "test exceeded")] fn a_misrouted_application_is_not_found() { - ServerContext::new() + ServerFixture::new() .handler(Misrouted(App::new())) .timeout(Duration::from_millis(200)) .run(async |context| { @@ -225,7 +227,7 @@ fn a_misrouted_application_is_not_found() { // An upload truncated after its head fails the handler's read, so the server rejects the request instead of answering it. #[test] fn a_truncated_trailer_upload_fails_the_handler() { - ServerContext::new() + ServerFixture::new() .handler(App::new()) .run(async |context| { let received = context.handler().request_received().clone(); @@ -250,7 +252,7 @@ const SEQUENTIAL_BODY: u64 = 1 << 30; // A client which uploads the whole request before reading the echo stalls once the unread echo fills the buffers between it and the server, which is why the two-way case must read and write at once. #[test] fn a_sequential_duplex_stream_stalls() { - ServerContext::new() + ServerFixture::new() .handler(App::new()) .run(async |context| { let (upload, mut writer) = @@ -314,14 +316,14 @@ impl Borrow for Reframed { } } -impl<'h> Handler<'h> for Reframed { +impl<'h> Handler<'h, ServerContext> for Reframed { type Error = io::Error; type Body = Reply; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result>, io::Error> { Ok(Response::new(Status::OK, Reply::Stream(request.body))) @@ -332,7 +334,7 @@ impl<'h> Handler<'h> for Reframed { #[test] #[should_panic(expected = "the echo's framing")] fn duplex_stream_reframed() { - ServerContext::new() + ServerFixture::new() .handler(Reframed(App::new())) .run(async |context| protocol::duplex_stream(context).await); } @@ -341,7 +343,7 @@ fn duplex_stream_reframed() { #[test] #[should_panic(expected = "the echo's framing")] fn duplex_stream_reframed_http10() { - ServerContext::new() + ServerFixture::new() .handler(Reframed(App::new())) .version(Version::Http10) .run(async |context| protocol::duplex_stream(context).await); @@ -356,14 +358,14 @@ impl Borrow for Buffering { } } -impl<'h> Handler<'h> for Buffering { +impl<'h> Handler<'h, ServerContext> for Buffering { type Error = io::Error; type Body = Reply; - async fn call( + async fn call( &self, mut request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result>, io::Error> { let collected = body::collect(&mut request.body, cancellation) @@ -377,7 +379,7 @@ impl<'h> Handler<'h> for Buffering { #[test] #[should_panic(expected = "test exceeded")] fn the_duplex_stream_stalls_against_a_buffering_server() { - ServerContext::new() + ServerFixture::new() .handler(Buffering(App::new())) .timeout(Duration::from_secs(1)) .run(async |context| protocol::duplex_stream(context).await); diff --git a/crates/fixtures/tests/raw.rs b/crates/fixtures/tests/raw.rs index 00b1aa51..fa263b9e 100644 --- a/crates/fixtures/tests/raw.rs +++ b/crates/fixtures/tests/raw.rs @@ -7,7 +7,7 @@ use base_http::{ body::{EmptyBody, ReadableBody}, }; use base_http_fixtures::{ - ClientContext, Latch, RawPeer, RawServer, ServerContext, + ClientFixture, Latch, RawPeer, RawServer, ServerFixture, body::{self, payload}, error_chain, protocol::{App, DUPLEX_BODY, DUPLEX_CHUNK, duplex_data}, @@ -117,7 +117,7 @@ fn a_raw_server_panic_propagates_on_join() { #[test] fn a_truncated_body_fails_the_client_read() { let server = RawServer::truncate_body(10, b"short"); - ClientContext::new(server.endpoint()).run(async |client| { + ClientFixture::new(server.endpoint()).run(async |client| { let mut response = client.call(get(), &Cancellation::never()).await.unwrap(); let error = body::collect(&mut response.body, &Cancellation::never()) .await @@ -137,7 +137,7 @@ fn a_stalled_body_waits_for_its_release() { "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n", release.clone(), ); - ClientContext::new(server.endpoint()).run(async |client| { + ClientFixture::new(server.endpoint()).run(async |client| { let mut response = client.call(get(), &Cancellation::never()).await.unwrap(); assert_eq!(response.status, Status::OK); assert!(!response.body.is_ready()); @@ -154,7 +154,7 @@ fn a_stalled_body_waits_for_its_release() { #[test] fn respond_then_close_serves_one_response() { let server = RawServer::respond_then_close("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); - ClientContext::new(server.endpoint()).run(async |client| { + ClientFixture::new(server.endpoint()).run(async |client| { let mut response = client.call(get(), &Cancellation::never()).await.unwrap(); assert_eq!(payload(&mut response.body).await, b"ok"); }); @@ -195,7 +195,7 @@ fn upload_head(length: u64) -> String { // The halves of a split peer upload and download at the same time from two threads. Done sequentially on one thread, the upload stalls once the unread echo fills the buffers, as `a_sequential_raw_upload_stalls_under_backpressure` shows. #[test] fn a_split_raw_peer_uploads_and_downloads_at_once() { - ServerContext::new() + ServerFixture::new() .handler(App::new()) .run(async |context| { context @@ -231,7 +231,7 @@ fn a_split_raw_peer_uploads_and_downloads_at_once() { #[test] fn a_sequential_raw_upload_stalls_under_backpressure() { const DECLARED: u64 = 1 << 30; - ServerContext::new() + ServerFixture::new() .handler(App::new()) .run(async |context| { context diff --git a/crates/fixtures/tests/spawned.rs b/crates/fixtures/tests/spawned.rs index 2377b059..4deb0e70 100644 --- a/crates/fixtures/tests/spawned.rs +++ b/crates/fixtures/tests/spawned.rs @@ -2,18 +2,16 @@ // Copyright, 2026, by Samuel Williams. //! A spawned server runs on the scheduler's workers beside a client driven from the test's thread, and reports each way it can fail, in order. -use base_http::{ - InterimHandler, InterimResponses, Method, Request, Response, Status, body::EmptyBody, - body::ReadableBody, -}; -use base_http_fixtures::{Context, Hello, ServerContext, body::payload, protocol::App}; +use base_http::{Method, Request, Response, Status, body::EmptyBody, body::ReadableBody}; +use base_http_fixtures::{Context, Hello, ServerFixture, body::payload, protocol::App}; use base_http_server::Handler; +use base_http_server::ServerContext; use base_scheduler::Cancellation; use base_scheduler_native::NativeScheduler; use std::{convert::Infallible, io::Read}; -fn failing() -> ServerContext { - ServerContext::new().server_options(base_http_server::Options { +fn failing() -> ServerFixture { + ServerFixture::new().server_options(base_http_server::Options { max_connections: 0, ..Default::default() }) @@ -21,7 +19,7 @@ fn failing() -> ServerContext { #[test] fn a_spawned_server_serves_a_client_and_a_raw_peer() { - ServerContext::new().run_spawned(async |context: &Context<'_, NativeScheduler, Hello>| { + ServerFixture::new().run_spawned(async |context: &Context<'_, NativeScheduler, Hello>| { let _: &Hello = context.handler(); let mut response = context .client() @@ -46,7 +44,7 @@ fn a_spawned_server_serves_a_client_and_a_raw_peer() { #[test] fn a_spawned_run_shares_the_application_with_the_server() { - ServerContext::new() + ServerFixture::new() .handler(App::new()) .run_spawned(async |context| { let app: &App = context.handler(); @@ -58,7 +56,7 @@ fn a_spawned_run_shares_the_application_with_the_server() { #[test] #[should_panic(expected = "the test failed")] fn a_test_panic_propagates_from_a_spawned_run() { - ServerContext::new().run_spawned(async |_| panic!("the test failed")); + ServerFixture::new().run_spawned(async |_| panic!("the test failed")); } #[test] @@ -77,14 +75,14 @@ fn a_test_panic_is_reported_before_a_spawned_server_failure() { /// Panics in every call. struct Panicking; -impl<'h> Handler<'h> for Panicking { +impl<'h> Handler<'h, ServerContext> for Panicking { type Error = Infallible; type Body = EmptyBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Infallible> { panic!("the handler panicked") @@ -105,7 +103,7 @@ async fn panic_the_server(context: &Context<'_, NativeScheduler, H>) { #[test] #[should_panic(expected = "the handler panicked")] fn a_spawned_server_panic_is_resumed() { - ServerContext::new() + ServerFixture::new() .handler(Panicking) .run_spawned(async |context| panic_the_server(context).await); } @@ -114,7 +112,7 @@ fn a_spawned_server_panic_is_resumed() { #[test] #[should_panic(expected = "the test failed first")] fn a_test_panic_is_reported_before_a_spawned_server_panic() { - ServerContext::new() + ServerFixture::new() .handler(Panicking) .run_spawned(async |context| { panic_the_server(context).await; diff --git a/crates/server/examples/client_server.rs b/crates/server/examples/client_server.rs index 46bf3b75..17d415de 100644 --- a/crates/server/examples/client_server.rs +++ b/crates/server/examples/client_server.rs @@ -4,10 +4,11 @@ //! Run with `cargo run --example client_server` from base-http-server. //! Starts one local HTTP/1 connection, echoes a POST body, then joins cleanup. use base_http::{ - InterimHandler, InterimResponses, Method, Request, Response, ResponseMetadata, Status, + InterimResponses, Method, Request, Response, ResponseMetadata, Status, body::{BodyFrame, BufferedBody, ReadableBody}, }; use base_http_server::Handler; +use base_http_server::ServerContext; use base_http1::{RequestWriter, ResponseReader}; use base_scheduler::{ Cancellation, SocketAccept, SocketBind, SocketClose, SocketConnect, SocketListen, @@ -21,14 +22,14 @@ type DemoResult = Result>; struct Echo; -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = Infallible; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Infallible> { // The response streams directly from the incoming request body. diff --git a/crates/server/examples/hello.rs b/crates/server/examples/hello.rs index 50214d5c..5a29dc71 100644 --- a/crates/server/examples/hello.rs +++ b/crates/server/examples/hello.rs @@ -1,8 +1,9 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::ServerContext; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_server::{Handler, Options}; @@ -17,14 +18,14 @@ use std::{convert::Infallible, net::SocketAddr}; struct Hello { close: bool, } -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = Infallible; type Body = BufferedBody<&'static [u8]>; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result>, Infallible> { let mut response = Response::new( diff --git a/crates/server/readme.md b/crates/server/readme.md index 17d569cc..84be2dac 100644 --- a/crates/server/readme.md +++ b/crates/server/readme.md @@ -2,23 +2,23 @@ An application server using native `base-http1`, `base-http` semantics and published Base scheduler capabilities. The server owns and joins its connection futures; it requires no hidden tasks, boxed bodies or concrete runtime. -Handlers are generic over incoming body and interim-response hook types. The associated `Body` selects the outgoing representation. For a streaming echo, it is simply `B`: +Applications implement `base-http`'s shared request interface, `Handler`, for `ServerContext`, which the server passes with each request. The context carries the connection's `Peer`, its addresses and, over TLS, the negotiated application protocol, and the hook for sending interim responses, which the server writes while it continues to poll the handler. The same interface is implemented by clients, so middleware generic over the context wraps either. Handlers are generic over the incoming body; the associated `Body` selects the outgoing representation. For a streaming echo, it is simply `B`: ```rust -use base_http::{InterimHandler, InterimResponses, Request, Response, Status, body::ReadableBody}; -use base_http_server::Handler; +use base_http::{Request, Response, Status, body::ReadableBody}; +use base_http_server::{Handler, ServerContext}; use base_scheduler::Cancellation; use std::convert::Infallible; struct Echo; -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = Infallible; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, Infallible> { Ok(Response::new(Status::OK, request.body)) @@ -26,6 +26,8 @@ impl<'h> Handler<'h> for Echo { } ``` +A request body is an independent value: a handler can pass it to work that outlives the call, such as a client forwarding it upstream. The connection reads the next request once that body has ended or been dropped, and takes its input back when it is cancelled or fails. + Static handlers can use `BufferedBody`; imperative producers can return `BodyReader` and supervise their `BodyWriter` producer explicitly. There is one pull-body model. A handler may send interim heads while processing input. Returning a readable body that owns input also supports managed CONNECT and upgrade exchanges. `serve_connection` consumes one accepted socket. `serve` consumes an already-bound listener and enforces `Options::max_connections`. `serve` and `serve_tls` disable Nagle's algorithm on each accepted socket unless `Options::tcp_nodelay` is false, so small streamed frames are not delayed waiting for acknowledgements. This is a best-effort hint: a socket that rejects it is still served. `serve_connection` leaves the options of a socket the caller accepted unchanged. Both retain the scheduler until reader/writer retirement and exclusive socket closure complete. For shutdown, cancel the supplied signal and await the serving future. Listener shutdown closes the listener, then terminates active work and joins cleanup; timed draining is future policy. Transient accept failures do not stop a listener: per-peer failures such as `ECONNABORTED` are retried, backing off after repeated failures, and resource exhaustion such as `EMFILE` pauses acceptance for 100 ms on the scheduler's `Clock`. They are counted in `Statistics::accept_errors`. Other accept failures, including scheduler closure, end serving with an error. diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 54e488e1..39d97446 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -7,13 +7,11 @@ #![forbid(unsafe_code)] use base_endpoint::stream::{ReadableStream, WritableStream}; -use base_http::{ - InterimHandler, InterimResponses, Request, Response, Scheme, Status, body::ReadableBody, -}; +use base_http::{InterimHandler, InterimRelay, Scheme, Status}; use base_http1::{LentInput, RequestReader, ResponseWriter}; use base_scheduler::{ - Cancellation, Clock, OperationError, SocketAccept, SocketClose, SocketSetOption, - SocketStreamReading, SocketStreamWriting, TcpNoDelay, + Cancellation, Clock, OperationError, SocketAccept, SocketClose, SocketLocalAddress, + SocketPeerAddress, SocketSetOption, SocketStreamReading, SocketStreamWriting, TcpNoDelay, }; use futures_util::{ future::{Either, select}, @@ -24,55 +22,14 @@ use std::{ future::{Future, poll_fn}, io, pin::pin, + sync::Arc, task::Poll, time::Duration, }; -/// Generic bodies and hooks keep handlers independent of the HTTP wire version -/// and scheduler. A returned body may retain the request body. -/// -/// The request body is an independent value that lives for `'scope`, the -/// server's borrow of its scheduler, so a handler can pass it to work that -/// outlives the call, such as a client forwarding it upstream. Its connection -/// reads the next request only once the body has ended, or has been closed or -/// dropped; when the connection is cancelled or fails, it takes its input back -/// at once and the body's later reads fail with -/// [`base_http1::Error::Closed`]. -/// -/// Generic code awaiting a handler that is bound to one `'scope` inside its own -/// `Send` future may be rejected by rustc with "implementation of `Handler` is -/// not general enough"; awaiting [`call_send`] instead avoids it. The server's -/// entry points need no such care. -/// -/// An error responds with a bodiless status and closes the connection, which then reports it as [`Error::Handler`]: 400 when a request read failed, such as a malformed or truncated body, even if the error has another cause, and otherwise 500. Return an ordinary response for other client errors. A final response which HTTP/1 cannot send, such as an informational status, conflicting framing, a `Content-Length` field its body contradicts or an unsolicited upgrade, likewise receives a bodiless 500 and closes the connection, which reports it as [`Error::Response`]. -pub trait Handler<'scope>: Sync { - type Error: std::error::Error + Send + Sync + 'static; - type Body: ReadableBody; - - fn call( - &self, - request: Request, - interim: &mut InterimResponses, - cancellation: &Cancellation, - ) -> impl Future>, Self::Error>> + Send; -} - -/// Call `handler` through a future whose type states `Send`, for generic code -/// that awaits a handler bound to one `'scope` within its own `Send` future, -/// which rustc may otherwise reject as "not general enough". -pub fn call_send<'scope, H, B, I>( - handler: &H, - request: Request, - interim: &mut InterimResponses, - cancellation: &Cancellation, -) -> impl Future>, H::Error>> + Send -where - H: Handler<'scope>, - B: ReadableBody + 'scope, - I: InterimHandler, -{ - handler.call(request, interim, cancellation) -} +/// The shared request interface, implemented by server applications for +/// [`ServerContext`], which carries the connection's [`Peer`]. +pub use base_http::{Handler, HandlerContext, Peer, ServerContext, call_send}; #[derive(Clone, Debug)] pub struct Options { @@ -181,9 +138,13 @@ pub fn serve_connection<'scope, S, H>( cancellation: &Cancellation, ) -> impl Future> + Send where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, S: Sync, S::Socket: Send, { @@ -200,9 +161,13 @@ async fn serve_connection_inner<'scope, S, H>( cancellation: &Cancellation, ) -> Result where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { let outcome = connection_outcome(scheduler, socket, handler, options, cancellation).await; outcome.result.map(|()| outcome.requests) @@ -221,9 +186,13 @@ async fn connection_outcome<'scope, S, H>( cancellation: &Cancellation, ) -> Outcome where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { let mut requests = 0; // The outer owner closes the socket even when capability construction fails. @@ -238,6 +207,11 @@ where return Err(Error::Io(error)); } }; + // Addresses a transport cannot report, such as a Unix socket's, are absent. + let peer = Arc::new(Peer::new( + scheduler.socket_peer_address(&socket).ok(), + scheduler.socket_local_address(&socket).ok(), + )); // The plaintext engine is HTTP/1, whose codecs fail to construct only when `options.validate` above fails. let (input, output) = base_http_protocol::HttpProtocols::default() .plaintext() @@ -247,6 +221,7 @@ where input, output, handler, + &peer, cancellation, &mut requests, &Scheme::HTTP, @@ -266,6 +241,7 @@ async fn serve_codecs<'scope, R, W, H>( input: RequestReader, mut output: ResponseWriter, handler: &H, + peer: &Arc, cancellation: &Cancellation, count: &mut u64, scheme: &Scheme, @@ -273,13 +249,14 @@ async fn serve_codecs<'scope, R, W, H>( where R: ReadableStream + Send + 'scope, W: WritableStream, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { let mut input = LentInput::new(input); let result = exchanges( &mut input, &mut output, handler, + peer, cancellation, count, scheme, @@ -304,6 +281,7 @@ async fn exchanges<'scope, R, W, H>( input: &mut LentInput, output: &mut ResponseWriter, handler: &H, + peer: &Arc, cancellation: &Cancellation, count: &mut u64, scheme: &Scheme, @@ -311,8 +289,9 @@ async fn exchanges<'scope, R, W, H>( where R: ReadableStream + Send + 'scope, W: WritableStream, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { + let relay = InterimRelay::new(); loop { let (mut request, exchange) = match input.read_request(cancellation).await { Ok(Some(pair)) => pair, @@ -332,13 +311,29 @@ where }; request.scheme.get_or_insert_with(|| scheme.clone()); let result = { - let mut interim = InterimResponses::new(output.interim(exchange.version())); - let result = { - let called = pin!(handler.call(request, &mut interim, cancellation)); - cancellable(called, cancellation).await? + let mut context = ServerContext::new(peer.clone(), relay.sender()); + let mut called = pin!(handler.call(request, &mut context, cancellation)); + // Write each interim response the handler hands over while still + // polling the handler, which waits for it. + let handled = async { + loop { + let response = match select(called.as_mut(), pin!(relay.next())).await { + Either::Left((result, _)) => break result, + Either::Right((response, _)) => response, + }; + let mut writer = output.interim(exchange.version()); + let written = pin!(writer.on_interim_response(response, cancellation)); + match select(written, called.as_mut()).await { + Either::Left((written, _)) => relay.complete(written), + // The handler abandoned its send; dropping the write + // poisons output if it had started. + Either::Right((result, _)) => break result, + } + } }; - interim.finish(); - result + let result = cancellable(handled, cancellation).await; + relay.finish(); + result? }; // The response can borrow the input lane, which a failure inspects, so only a successful result leaves this block. let mut response = 'handled: { @@ -533,9 +528,11 @@ where + SocketSetOption + SocketStreamReading + SocketStreamWriting - + SocketClose, + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, S: Sync, S::Socket: Send, { @@ -557,9 +554,11 @@ where + SocketSetOption + SocketStreamReading + SocketStreamWriting - + SocketClose, + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { serve_with( scheduler, @@ -684,9 +683,13 @@ pub fn serve_tls_connection<'scope, S, H>( cancellation: &Cancellation, ) -> impl Future> + Send where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, S: Sync, S::Socket: Send, { @@ -704,9 +707,13 @@ async fn serve_tls_connection_inner<'scope, S, H>( cancellation: &Cancellation, ) -> Result where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { let outcome = tls_connection_outcome(scheduler, connection, handler, options, cancellation).await; @@ -722,12 +729,24 @@ async fn tls_connection_outcome<'scope, S, H>( cancellation: &Cancellation, ) -> Outcome where - S: SocketStreamReading + SocketStreamWriting + SocketClose, + S: SocketStreamReading + + SocketStreamWriting + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { use base_endpoint::tls::TlsSession; let selected = connection.negotiated_protocol().map(<[u8]>::to_vec); + let socket = connection.socket(); + let peer = Arc::new( + Peer::new( + scheduler.socket_peer_address(socket).ok(), + scheduler.socket_local_address(socket).ok(), + ) + .encrypted(selected.as_deref()), + ); let mut requests = 0; let result = connection .with_duplex(scheduler, cancellation, |reader, writer| async { @@ -737,6 +756,7 @@ where input, output, handler, + &peer, cancellation, &mut requests, &Scheme::HTTPS, @@ -764,9 +784,11 @@ where + SocketSetOption + SocketStreamReading + SocketStreamWriting - + SocketClose, + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, S: Sync, S::Socket: Send, { @@ -790,9 +812,11 @@ where + SocketSetOption + SocketStreamReading + SocketStreamWriting - + SocketClose, + + SocketClose + + SocketPeerAddress + + SocketLocalAddress, S::Socket: 'static, - H: Handler<'scope>, + H: Handler<'scope, ServerContext>, { use base_endpoint::tls::{TlsAcceptor, rustls::RustlsAcceptor}; let mut config = (*config).clone(); diff --git a/crates/server/tests/accept_errors.rs b/crates/server/tests/accept_errors.rs index fba4365a..984a90f1 100644 --- a/crates/server/tests/accept_errors.rs +++ b/crates/server/tests/accept_errors.rs @@ -5,15 +5,16 @@ // Real TCP connections served through a scheduler that injects scripted accept failures and records the order in which sockets close. use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; +use base_http_server::ServerContext; use base_http_server::{Error, Handler, Options, Statistics}; use base_scheduler::{ BufferPool, BufferPoolOptions, BufferPooling, Cancellation, Clock, IoBuf, OperationError, - OperationResult, SocketAccept, SocketAddress, SocketClose, SocketOperation, SocketPeerAddress, - SocketSetOption, SocketStreamReader, SocketStreamReading, SocketStreamWriter, - SocketStreamWriting, TcpNoDelay, + OperationResult, SocketAccept, SocketAddress, SocketClose, SocketLocalAddress, SocketOperation, + SocketPeerAddress, SocketSetOption, SocketStreamReader, SocketStreamReading, + SocketStreamWriter, SocketStreamWriting, TcpNoDelay, }; use base_scheduler_native::{NativeScheduler, NativeSocket}; use futures_lite::future::block_on; @@ -101,6 +102,16 @@ impl SocketSetOption for Scripted<'_> { .socket_set_option(socket, option, value, cancellation) } } +impl SocketPeerAddress for Scripted<'_> { + fn socket_peer_address(&self, socket: &NativeSocket) -> io::Result { + self.inner.socket_peer_address(socket) + } +} +impl SocketLocalAddress for Scripted<'_> { + fn socket_local_address(&self, socket: &NativeSocket) -> io::Result { + self.inner.socket_local_address(socket) + } +} impl SocketClose for Scripted<'_> { async fn socket_close(&self, socket: NativeSocket) -> io::Result<()> { // Only an accepted connection has a peer. @@ -166,13 +177,13 @@ impl<'a> SocketStreamWriting for Scripted<'a> { } struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { Ok(Response::new( diff --git a/crates/server/tests/end_to_end.rs b/crates/server/tests/end_to_end.rs index ac97d98a..39104754 100644 --- a/crates/server/tests/end_to_end.rs +++ b/crates/server/tests/end_to_end.rs @@ -1,9 +1,9 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::{HandlerContext, ServerContext}; use base_http::{ - Fields, HttpHeaders, InterimHandler, InterimResponses, Method, Request, RequestMetadata, - Response, ResponseMetadata, Status, + Fields, HttpHeaders, Method, Request, RequestMetadata, Response, ResponseMetadata, Status, body::{BodyFrame, BodyReader, BufferedBody, ReadableBody}, }; use base_http_server::{Error, Handler}; @@ -26,17 +26,18 @@ use support::*; struct Collect { seen: Arc>>, } -impl<'h> Handler<'h> for Collect { +impl<'h> Handler<'h, ServerContext> for Collect { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, mut request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { if request.fields.contains("expect") { - interim + context + .interim() .send_interim_response(ResponseMetadata::new(Status::CONTINUE), cancellation) .await .map_err(io::Error::other)?; @@ -46,7 +47,8 @@ impl<'h> Handler<'h> for Collect { hint.fields .add("Link", "; rel=preload") .unwrap(); - interim + context + .interim() .send_interim_response(hint, cancellation) .await .map_err(io::Error::other)?; @@ -168,13 +170,13 @@ fn head_and_bodyless_statuses_do_not_emit_representation_bytes() { } struct Echo; -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = io::Error; type Body = B; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { let status = if request.method == Method::CONNECT { @@ -264,13 +266,13 @@ fn upgrade_keeps_managed_duplex_body_and_buffered_input() { struct Producer { body: Mutex>, } -impl<'h> Handler<'h> for Producer { +impl<'h> Handler<'h, ServerContext> for Producer { type Error = io::Error; type Body = BodyReader; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { Ok(Response::new( @@ -335,13 +337,13 @@ fn http10_unknown_body_is_close_delimited() { /// Responds with `data` and then a trailer, with a known length on `/length`. struct Trailed; -impl<'h> Handler<'h> for Trailed { +impl<'h> Handler<'h, ServerContext> for Trailed { type Error = io::Error; type Body = BodyReader; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { let (reader, mut writer) = match request.path.as_deref() { @@ -441,13 +443,13 @@ fn truncated_and_invalid_chunked_bodies_fail_without_a_successful_response() { /// Fails every request, after sending an early hint for `/hints` or reading the whole body for `/read`. struct Fail; -impl<'h> Handler<'h> for Fail { +impl<'h> Handler<'h, ServerContext> for Fail { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, mut request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { if request.path.as_deref() == Some("/read") { @@ -459,7 +461,8 @@ impl<'h> Handler<'h> for Fail { {} } if request.path.as_deref() == Some("/hints") { - interim + context + .interim() .send_interim_response(ResponseMetadata::new(Status::EARLY_HINTS), cancellation) .await .map_err(io::Error::other)?; @@ -518,18 +521,19 @@ fn handler_errors_respond_with_a_server_error_and_close_the_connection() { } struct Invalid; -impl<'h> Handler<'h> for Invalid { +impl<'h> Handler<'h, ServerContext> for Invalid { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { let response = match request.path.as_deref() { Some("/hints") => { - interim + context + .interim() .send_interim_response(ResponseMetadata::new(Status::EARLY_HINTS), cancellation) .await .map_err(io::Error::other)?; @@ -614,13 +618,13 @@ fn invalid_responses_respond_with_a_server_error_and_close_the_connection() { // A replaced body which keeps the received declaration. struct Stale; -impl<'h> Handler<'h> for Stale { +impl<'h> Handler<'h, ServerContext> for Stale { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _request: Request, - _interim: &mut InterimResponses, + _: &mut ServerContext, _cancellation: &Cancellation, ) -> Result, io::Error> { let mut response = Response::new(Status::OK, BufferedBody::from(b"hello".to_vec())); @@ -688,13 +692,13 @@ fn cancellation_of_pending_output_retires_lanes_and_wakes_producer() { } struct Never(Arc); -impl<'h> Handler<'h> for Never { +impl<'h> Handler<'h, ServerContext> for Never { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { self.0.store(true, Ordering::Release); @@ -722,13 +726,13 @@ fn cancellation_interrupts_a_handler_that_ignores_its_signal() { } struct PendingRead(Arc); -impl<'h> Handler<'h> for PendingRead { +impl<'h> Handler<'h, ServerContext> for PendingRead { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, mut request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { use std::{ @@ -777,13 +781,13 @@ struct Count { active: Arc, maximum: Arc, } -impl<'h> Handler<'h> for Count { +impl<'h> Handler<'h, ServerContext> for Count { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { self.started.fetch_add(1, Ordering::SeqCst); @@ -953,13 +957,13 @@ fn listener_accepts_new_peers_while_previous_connections_retire() { }); block_on(scheduler.shutdown()); } -impl<'h> Handler<'h> for OneThenPending { +impl<'h> Handler<'h, ServerContext> for OneThenPending { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { if request.path.as_deref() == Some("/pending") { @@ -975,13 +979,13 @@ impl<'h> Handler<'h> for OneThenPending { } struct Early; -impl<'h> Handler<'h> for Early { +impl<'h> Handler<'h, ServerContext> for Early { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { Ok(Response::new( @@ -1065,13 +1069,13 @@ struct Racing { clock: Arc, timeouts: Arc, } -impl<'h> Handler<'h> for Racing { +impl<'h> Handler<'h, ServerContext> for Racing { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, mut request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { let mut data = Vec::new(); diff --git a/crates/server/tests/lent_bodies.rs b/crates/server/tests/lent_bodies.rs index e978bc48..13e84531 100644 --- a/crates/server/tests/lent_bodies.rs +++ b/crates/server/tests/lent_bodies.rs @@ -6,9 +6,10 @@ //! cancelled or its handler fails. mod support; +use base_http_server::{HandlerContext, ServerContext}; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BodyFrame, BufferedBody, ReadableBody}, }; use base_http_server::{Error, Handler}; @@ -134,13 +135,13 @@ struct Defer<'q, 'h> { mode: Mode, reads: Arc>>, } -impl<'h> Handler<'h> for Defer<'_, 'h> { +impl<'h> Handler<'h, ServerContext> for Defer<'_, 'h> { type Error = io::Error; type Body = BufferedBody>; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result>>, io::Error> { let mut body = request.body; @@ -373,16 +374,16 @@ fn assert_send(future: F) -> F { /// A pass-through middleware layer. struct Layer(H); -impl<'h, H: Handler<'h>> Handler<'h> for Layer { +impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Layer { type Error = H::Error; type Body = H::Body; - async fn call( + async fn call( &self, request: Request, - interim: &mut InterimResponses, + context: &mut C, cancellation: &Cancellation, ) -> Result>, H::Error> { - self.0.call(request, interim, cancellation).await + self.0.call(request, context, cancellation).await } } @@ -404,12 +405,11 @@ fn call_send_awaits_a_scope_bound_handler_in_a_send_future() { reads: Arc::default(), })); let status = block_on(assert_send(async { - let mut interim = InterimResponses::new(|_: base_http::ResponseMetadata| async { - Ok::<_, io::Error>(()) - }); + let relay = base_http::InterimRelay::new(); + let mut context = ServerContext::new(Arc::default(), relay.sender()); let request = Request::new(base_http::Method::POST, "/", &mut local); let response = - base_http_server::call_send(&handler, request, &mut interim, &Cancellation::never()) + base_http_server::call_send(&handler, request, &mut context, &Cancellation::never()) .await .unwrap(); response.status diff --git a/crates/server/tests/listener.rs b/crates/server/tests/listener.rs index 1624dd51..aec36e9c 100644 --- a/crates/server/tests/listener.rs +++ b/crates/server/tests/listener.rs @@ -1,8 +1,9 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. +use base_http_server::ServerContext; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_server::{Error, Handler, Options}; @@ -17,13 +18,13 @@ mod support; use support::*; struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { Ok(Response::new( diff --git a/crates/server/tests/nodelay.rs b/crates/server/tests/nodelay.rs index 88d1d544..8fcfa4c4 100644 --- a/crates/server/tests/nodelay.rs +++ b/crates/server/tests/nodelay.rs @@ -3,14 +3,16 @@ // Real TCP connections served through a scheduler that reads back each socket's TCP_NODELAY before closing it. use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; +use base_http_server::ServerContext; use base_http_server::{Handler, Options}; use base_scheduler::{ BufferPool, BufferPoolOptions, BufferPooling, Cancellation, Clock, IoBuf, OperationResult, - SocketAccept, SocketAddress, SocketClose, SocketGetOption, SocketOperation, SocketSetOption, - SocketStreamReader, SocketStreamReading, SocketStreamWriter, SocketStreamWriting, TcpNoDelay, + SocketAccept, SocketAddress, SocketClose, SocketGetOption, SocketLocalAddress, SocketOperation, + SocketPeerAddress, SocketSetOption, SocketStreamReader, SocketStreamReading, + SocketStreamWriter, SocketStreamWriting, TcpNoDelay, }; use base_scheduler_native::{NativeScheduler, NativeSocket}; use futures_lite::future::block_on; @@ -70,6 +72,16 @@ impl SocketSetOption for Recording<'_> { .socket_set_option(socket, option, value, cancellation) } } +impl SocketPeerAddress for Recording<'_> { + fn socket_peer_address(&self, socket: &NativeSocket) -> io::Result { + self.inner.socket_peer_address(socket) + } +} +impl SocketLocalAddress for Recording<'_> { + fn socket_local_address(&self, socket: &NativeSocket) -> io::Result { + self.inner.socket_local_address(socket) + } +} impl SocketClose for Recording<'_> { async fn socket_close(&self, socket: NativeSocket) -> io::Result<()> { let nodelay = self @@ -130,13 +142,13 @@ impl<'a> SocketStreamWriting for Recording<'a> { } struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { Ok(Response::new( diff --git a/crates/server/tests/peer.rs b/crates/server/tests/peer.rs new file mode 100644 index 00000000..444c80db --- /dev/null +++ b/crates/server/tests/peer.rs @@ -0,0 +1,64 @@ +// Released under the MIT License. +// Copyright, 2026, by Samuel Williams. + +//! Handlers observe the connection a request arrived on through their context. + +use base_http::{ + Request, Response, Status, + body::{BufferedBody, ReadableBody}, +}; +use base_http_server::{Handler, ServerContext}; +use base_scheduler::Cancellation; +use std::io::{self, Write}; + +mod support; +use support::*; + +struct Reporting; +impl<'h> Handler<'h, ServerContext> for Reporting { + type Error = io::Error; + type Body = BufferedBody; + async fn call( + &self, + _: Request, + context: &mut ServerContext, + _: &Cancellation, + ) -> Result, io::Error> { + let peer = context.peer(); + let mut response = Response::new(Status::OK, BufferedBody::default()); + for (name, value) in [ + ("x-peer", peer.address().map(|address| address.to_string())), + ( + "x-local", + peer.local_address().map(|address| address.to_string()), + ), + ("x-encrypted", Some(peer.is_encrypted().to_string())), + ("x-early-data", Some(peer.is_early_data().to_string())), + ] { + response + .fields + .add(name, value.unwrap_or_default().as_str()) + .unwrap(); + } + Ok(response) + } +} + +#[test] +fn handlers_observe_the_peer_and_local_addresses_of_their_connection() { + let (served, (expected, response)) = connection(Reporting, |mut peer, _| { + let socket = peer.get_ref(); + let expected = (socket.local_addr().unwrap(), socket.peer_addr().unwrap()); + peer.get_mut() + .write_all(b"GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n") + .unwrap(); + (expected, head(&mut peer)) + }); + assert_eq!(served.unwrap(), 1); + assert_eq!(response.status, 200); + let (address, local) = expected; + assert_eq!(response.get("x-peer"), Some(address.to_string().as_str())); + assert_eq!(response.get("x-local"), Some(local.to_string().as_str())); + assert_eq!(response.get("x-encrypted"), Some("false")); + assert_eq!(response.get("x-early-data"), Some("false")); +} diff --git a/crates/server/tests/proxy.rs b/crates/server/tests/proxy.rs index eff26bb8..93555e51 100644 --- a/crates/server/tests/proxy.rs +++ b/crates/server/tests/proxy.rs @@ -4,11 +4,12 @@ //! A deliberately small protocol-driver experiment, not a gateway policy API. //! Upload and download futures remain separately owned and polled until joined. mod support; +use base_http_server::{HandlerContext, ServerContext}; use support::*; use base_http::{ - Fields, InterimHandler, InterimResponses, Request, RequestMetadata, Response, ResponseMetadata, - Status, body::ReadableBody, + Fields, InterimResponses, Request, RequestMetadata, Response, ResponseMetadata, Status, + body::ReadableBody, }; use base_http_server::Handler; use base_http1::{Error, RequestReader, RequestWriter, ResponseReader, ResponseWriter}; @@ -249,19 +250,20 @@ fn request_head(peer: &mut impl BufRead) -> (String, Head) { struct Echo { seen: Arc>>, } -impl<'h> Handler<'h> for Echo { +impl<'h> Handler<'h, ServerContext> for Echo { type Error = io::Error; type Body = B; - async fn call( + async fn call( &self, request: Request, - interim: &mut InterimResponses, + context: &mut ServerContext, cancellation: &Cancellation, ) -> Result, io::Error> { self.seen.lock().unwrap().push(request.metadata.clone()); if request.fields.contains("expect") { for status in [Status::CONTINUE, Status::EARLY_HINTS] { - interim + context + .interim() .send_interim_response(ResponseMetadata::new(status), cancellation) .await .map_err(io::Error::other)?; diff --git a/crates/server/tests/support/mod.rs b/crates/server/tests/support/mod.rs index 2d0ed7ad..7294888e 100644 --- a/crates/server/tests/support/mod.rs +++ b/crates/server/tests/support/mod.rs @@ -2,6 +2,7 @@ // Copyright, 2026, by Samuel Williams. #![allow(dead_code)] +use base_http_server::ServerContext; use base_http_fixtures::raw; use base_http_server::{Error, Handler}; @@ -54,14 +55,14 @@ pub fn connect(address: SocketAddr) -> BufReader { BufReader::new(socket) } -pub fn connection Handler<'h>, T: Send + 'static>( +pub fn connection Handler<'h, ServerContext>, T: Send + 'static>( handler: H, peer: impl FnOnce(BufReader, Cancellation) -> T + Send + 'static, ) -> (Result, T) { connection_options(handler, base_http1::Options::default(), peer) } -pub fn connection_options Handler<'h>, T: Send + 'static>( +pub fn connection_options Handler<'h, ServerContext>, T: Send + 'static>( handler: H, options: base_http1::Options, peer: impl FnOnce(BufReader, Cancellation) -> T + Send + 'static, diff --git a/crates/server/tests/tls.rs b/crates/server/tests/tls.rs index 941ae230..0c203810 100644 --- a/crates/server/tests/tls.rs +++ b/crates/server/tests/tls.rs @@ -2,10 +2,11 @@ // Copyright, 2026, by Samuel Williams. #![cfg(feature = "rustls")] +use base_http_server::ServerContext; use base_endpoint::tls::{TlsAcceptor, rustls::RustlsAcceptor}; use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_protocol::{HttpProtocols, NegotiationError}; @@ -121,13 +122,13 @@ fn rejected(mut peer: Peer) { } struct Hello; -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, request: Request, - _: &mut InterimResponses, + context: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { let scheme = request @@ -136,7 +137,18 @@ impl<'h> Handler<'h> for Hello { .unwrap_or_default() .as_bytes() .to_vec(); - Ok(Response::new(Status::OK, BufferedBody::from(scheme))) + let mut response = Response::new(Status::OK, BufferedBody::from(scheme)); + let peer = context.peer(); + let address = peer.address().unwrap().to_string(); + response.fields.add("x-peer", address.as_str()).unwrap(); + let encrypted = peer.is_encrypted().to_string(); + response + .fields + .add("x-encrypted", encrypted.as_str()) + .unwrap(); + let protocol = peer.application_protocol().unwrap_or(b"none"); + response.fields.add("x-protocol", protocol).unwrap(); + Ok(response) } } @@ -153,11 +165,16 @@ fn negotiated_http1_serves_https_requests_on_an_accepted_connection() { protocols.alpn_protocols(), |mut peer| { let negotiated = peer.conn.alpn_protocol().map(<[u8]>::to_vec); + let local = peer.sock.local_addr().unwrap().to_string(); peer.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") .unwrap(); let mut peer = BufReader::new(peer); let response = head(&mut peer); assert_eq!(response.status, 200); + // The handler's context reports this connection. + assert_eq!(response.get("x-peer"), Some(local.as_str())); + assert_eq!(response.get("x-encrypted"), Some("true")); + assert_eq!(response.get("x-protocol"), Some("http/1.1")); let (data, _) = body(&mut peer, &response); assert_eq!(peer.read(&mut [0]).unwrap(), 0); (negotiated, data) diff --git a/crates/server/tests/transport_faults.rs b/crates/server/tests/transport_faults.rs index 448fd946..fa131459 100644 --- a/crates/server/tests/transport_faults.rs +++ b/crates/server/tests/transport_faults.rs @@ -3,16 +3,17 @@ // A scripted in-memory scheduler serves one connection whose transport capabilities can fail deterministically. The input script is followed by EOF, so every exchange completes without timing assumptions. use base_http::{ - InterimHandler, InterimResponses, Request, Response, Status, + Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_server::{Error, Handler}; +use base_http_server::{HandlerContext, ServerContext}; use base_scheduler::{ BufferLease, BufferPoolOptions, BufferPooling, Cancellation, Cancelled, Clock, HeapBufferPool, IoBuf, IoBufSequence, IoBufSequenceMut, OperationError, OperationResult, SocketAccept, - SocketAddress, SocketClose, SocketOperation, SocketRecvFlags, SocketRecvResult, - SocketSendFlags, SocketSetOption, SocketStreamReader, SocketStreamReading, SocketStreamWriter, - SocketStreamWriting, TcpNoDelay, + SocketAddress, SocketClose, SocketLocalAddress, SocketOperation, SocketPeerAddress, + SocketRecvFlags, SocketRecvResult, SocketSendFlags, SocketSetOption, SocketStreamReader, + SocketStreamReading, SocketStreamWriter, SocketStreamWriting, TcpNoDelay, }; use futures_lite::future::block_on; use std::{ @@ -37,6 +38,8 @@ struct Faults { writer_close_error: bool, socket_close_error: bool, cancel_on_read: Option, + /// The next write waits until it is cancelled or dropped. + stall_next_write: bool, } #[derive(Default)] @@ -159,6 +162,11 @@ impl SocketStreamWriter for Writer<'_, B> { cancellation: &Cancellation, ) -> OperationResult { cancellation.check()?; + let stall = std::mem::take(&mut self.memory.faults().stall_next_write); + if stall { + cancellation.cancelled().await; + return Err(Cancelled.into()); + } self.memory.output.lock().unwrap().extend_from_slice(buffer); Ok(buffer.len()) } @@ -303,6 +311,17 @@ impl SocketSetOption for Memory { } } +// An in-memory transport has no addresses. +impl SocketPeerAddress for Memory { + fn socket_peer_address(&self, _: &()) -> io::Result { + Err(io::ErrorKind::Unsupported.into()) + } +} +impl SocketLocalAddress for Memory { + fn socket_local_address(&self, _: &()) -> io::Result { + Err(io::ErrorKind::Unsupported.into()) + } +} impl SocketClose for Memory { async fn socket_close(&self, _: ()) -> io::Result<()> { self.socket_closes.fetch_add(1, Ordering::SeqCst); @@ -325,13 +344,13 @@ impl SocketClose for Memory { struct Hello { called: AtomicBool, } -impl<'h> Handler<'h> for Hello { +impl<'h> Handler<'h, ServerContext> for Hello { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { self.called.store(true, Ordering::SeqCst); @@ -342,9 +361,36 @@ impl<'h> Handler<'h> for Hello { } } +/// Sends 103 Early Hints, but gives up on it after yielding once, so it returns +/// while the server is still writing the hint. +struct Impatient; +impl<'h> Handler<'h, ServerContext> for Impatient { + type Error = io::Error; + type Body = BufferedBody; + async fn call( + &self, + _: Request, + context: &mut ServerContext, + cancellation: &Cancellation, + ) -> Result, io::Error> { + let hint = base_http::ResponseMetadata::new(Status::EARLY_HINTS); + let sent = context.interim().send_interim_response(hint, cancellation); + let gave_up = futures_lite::future::yield_now(); + let _ = futures_lite::future::or(async { sent.await.map(|_| ()).ok() }, async { + gave_up.await; + None + }) + .await; + Ok(Response::new( + Status::OK, + BufferedBody::from(b"hello".to_vec()), + )) + } +} + fn serve( memory: &Memory, - handler: &impl for<'h> Handler<'h>, + handler: &impl for<'h> Handler<'h, ServerContext>, options: &base_http1::Options, cancellation: &Cancellation, ) -> Result { @@ -494,13 +540,13 @@ fn cancellation_while_a_head_is_read_prevents_handler_admission() { // A handler which stops the server and reports the resulting failure, as one observing a cancelled operation would. struct Shutdown(Cancellation); -impl<'h> Handler<'h> for Shutdown { +impl<'h> Handler<'h, ServerContext> for Shutdown { type Error = io::Error; type Body = BufferedBody; - async fn call( + async fn call( &self, _: Request, - _: &mut InterimResponses, + _: &mut ServerContext, _: &Cancellation, ) -> Result, io::Error> { self.0.cancel(); @@ -519,6 +565,22 @@ fn handler_failure_after_cancellation_is_reported_as_cancellation() { assert_eq!(memory.closes(), (1, 1, 1)); } +#[test] +fn a_handler_returning_while_its_interim_response_is_written_closes_without_a_response() { + let memory = Memory::new(REQUEST); + memory.faults().stall_next_write = true; + let served = serve( + &memory, + &Impatient, + &Default::default(), + &Cancellation::never(), + ); + // The abandoned write leaves output out of sync, so no final response follows. + assert!(served.is_err(), "{served:?}"); + assert_eq!(memory.output(), ""); + assert_eq!(memory.closes(), (1, 1, 1)); +} + #[test] fn listener_close_failure_is_reported_after_cancelled_acceptance() { let memory = Memory::default(); diff --git a/design/fixtures.md b/design/fixtures.md index 0c73d3c9..a0900870 100644 --- a/design/fixtures.md +++ b/design/fixtures.md @@ -24,7 +24,7 @@ Inspect each manifest: the fixtures crate is unpublished and every dependency on ### Requirement -`ServerContext::run` binds its listener before serving and before the test starts, so the client never races the server's start. It runs the test beside the server and the client's driver, then tears down in order: the client stops accepting calls and retires its connections, then the server stops, closing its listener and joining its connections. The test and teardown are each bounded by a configurable time; exceeding either fails the test, and a forced teardown cancels the client and server and still joins them. Joining after a forced teardown relies on the client, server and handlers observing cancellation, and on raw peers' I/O timeouts; it has no second deadline. A panic in the test propagates after teardown, ahead of any server failure. A test also fails when the server fails or a client connection remains after teardown. `ClientContext` gives a client of another endpoint the same bounds and teardown. +`ServerFixture::run` binds its listener before serving and before the test starts, so the client never races the server's start. It runs the test beside the server and the client's driver, then tears down in order: the client stops accepting calls and retires its connections, then the server stops, closing its listener and joining its connections. The test and teardown are each bounded by a configurable time; exceeding either fails the test, and a forced teardown cancels the client and server and still joins them. Joining after a forced teardown relies on the client, server and handlers observing cancellation, and on raw peers' I/O timeouts; it has no second deadline. A panic in the test propagates after teardown, ahead of any server failure. A test also fails when the server fails or a client connection remains after teardown. `ClientFixture` gives a client of another endpoint the same bounds and teardown. ### Rationale @@ -32,7 +32,7 @@ Rust has no asynchronous destructor, so a fixture which leaves teardown to the t ### Scope -`ServerContext`, `ClientContext` and `Context` in `crates/fixtures/src/context.rs`. +`ServerFixture`, `ClientFixture` and `Context` in `crates/fixtures/src/context.rs`. ### Validation @@ -42,7 +42,7 @@ Rust has no asynchronous destructor, so a fixture which leaves teardown to the t ### Requirement -`ServerContext::run_spawned` creates a two-worker Native scheduler, binds the listener, then spawns the server's public entry point, `base_http_server::serve` or `serve_tls`, as one task through `base_scheduler::Spawn`, so the server runs on the scheduler's workers in parallel with a client driven from the test's thread. It takes ownership of the application and owns the scheduler for the whole run; the test receives the same `Context<'_, NativeScheduler, H>` as `run`, with the application as `&H`. Any sharing between the test and the server's task, such as an `Arc`, stays inside the fixture and is not part of its public API. The fixture relies only on the server running on the scheduler's workers. It adds nothing to `base-http-server`'s public API and does not choose how connections are spread across tasks or workers. The application must be `Handler + Send + Sync + 'static`, as a server which spawned its own connection tasks would need. +`ServerFixture::run_spawned` creates a two-worker Native scheduler, binds the listener, then spawns the server's public entry point, `base_http_server::serve` or `serve_tls`, as one task through `base_scheduler::Spawn`, so the server runs on the scheduler's workers in parallel with a client driven from the test's thread. It takes ownership of the application and owns the scheduler for the whole run; the test receives the same `Context<'_, NativeScheduler, H>` as `run`, with the application as `&H`. Any sharing between the test and the server's task, such as an `Arc`, stays inside the fixture and is not part of its public API. The fixture relies only on the server running on the scheduler's workers. It adds nothing to `base-http-server`'s public API and does not choose how connections are spread across tasks or workers. The application must be `Handler + Send + Sync + 'static`, as a server which spawned its own connection tasks would need. `run_spawned` has the guarantees of `run`: the listener is bound before the test starts, the test is bounded, the client retires its connections before the server stops, a server error fails the test, a server panic is resumed with its original payload, and a test failure is reported before any server failure, which is printed to stderr first. After the test, the server is cancelled and joined for at most the teardown timeout, and fails the test if it overruns. That timeout is measured on its own thread rather than by the scheduler's clock, so a server occupying every worker, such as a handler which blocks, still fails on time. Native's stall rescue, on by default since scheduler 0.5, also lets the scheduler's clock bound the join, but it can be turned off with `stall_rescue: false`, and Native then strands a timer behind the busy worker. The fixture keeps the own-thread deadline so it does not depend on rescue; it can be removed once Native fires timers behind a busy worker in every configuration. The test's timeout and the client's teardown, in `supervise` and `bounded`, are still measured by the scheduler's clock, so they are bounded only while the scheduler's timers can run. The scheduler is then shut down, and Native drains its tasks, so the call does not return until an overrunning server's current poll returns. A poll which never returns cannot be preempted and hangs the test after the failure is reported, so teardown is bounded only for servers whose polls return. The scoped `run` and `run_on` are unchanged. @@ -52,7 +52,7 @@ Rust has no asynchronous destructor, so a fixture which leaves teardown to the t ### Scope -`ServerContext::run_spawned` and its private spawning, joining and scheduler helpers in `crates/fixtures/src/context.rs`. +`ServerFixture::run_spawned` and its private spawning, joining and scheduler helpers in `crates/fixtures/src/context.rs`. ### Validation diff --git a/design/implementation.md b/design/implementation.md index 89349bc9..fd0050a8 100644 --- a/design/implementation.md +++ b/design/implementation.md @@ -57,7 +57,7 @@ No request queue, endpoint establishment, pool or Expect/Continue wait policy is ## Application and scheduler lifecycle -`Handler<'scope>` is generic over incoming body and interim hook types, with request bodies that outlive `'scope`, the server's borrow of its scheduler. Its connection waits for a request body that outlives the handler call before reading the next request, and after a normal end before retiring input; when the connection is cancelled, or its handler or response fails, it reclaims the input at once. The public `serve*` functions state `Send` on the futures they return, requiring a `Sync` scheduler with `Send` sockets, because rustc otherwise cannot prove `Send` for every request body lifetime in callers' futures; `call_send` does the same for generic code awaiting a handler bound to one scope. Its associated `Body` selects the outgoing body type without boxing; echo uses `B`, static handlers use `BufferedBody`, and imperative producers use `BodyReader`. The associated response type depends on the incoming body, while the interim hook is borrowed only during `call`. This prevents a returned body from retaining the response writer needed to serialize it. +Server applications implement `base-http`'s shared request interface, `Handler<'scope, ServerContext>`, which `base-http-server` re-exports; [middleware](middleware.md#shared-request-interface) records its shape. It is generic over the incoming body, with request bodies that outlive `'scope`, the server's borrow of its scheduler. Each connection builds its `Peer` once, from the scheduler's peer and local addresses, which a scheduler therefore implements, and, over TLS, the negotiated application protocol, and allocates one `InterimRelay`. Each request's `ServerContext` shares the `Peer` and holds a sender for the relay, and the server writes each interim response the handler hands over while it continues to poll the handler; a handler that returns while its interim response is being written abandons it, which leaves output out of sync, so the connection closes. Its connection waits for a request body that outlives the handler call before reading the next request, and after a normal end before retiring input; when the connection is cancelled, or its handler or response fails, it reclaims the input at once. The public `serve*` functions state `Send` on the futures they return, requiring a `Sync` scheduler with `Send` sockets, because rustc otherwise cannot prove `Send` for every request body lifetime in callers' futures; `call_send` does the same for generic code awaiting a handler bound to one scope. Its associated `Body` selects the outgoing body type without boxing; echo uses `B`, static handlers use `BufferedBody`, and imperative producers use `BodyReader`. The associated response type depends on the incoming body, while the context is borrowed only during `call` and itself borrows nothing from the server. This prevents a returned body from retaining the response writer needed to serialize it. `serve_connection` consumes an accepted scheduler socket. It constructs independent bound reader/writer handles once, serves exchanges, awaits both uncancellable lane closures even after error or cancellation, drops the handles, then exclusively closes the socket. Cancelling interrupts handler and output-body futures even if they ignore the passed signal. Dropping the whole serving future is not a cleanup join; callers cancel cooperatively and await it. diff --git a/design/load-balancer.md b/design/load-balancer.md index 1526ec09..76ca953c 100644 --- a/design/load-balancer.md +++ b/design/load-balancer.md @@ -216,7 +216,7 @@ With the `orca` feature, tests parse each form, the three `endpoint-load-metrics ### Requirement -`base-http-server` makes each request's connection information available to its handler: the peer and local addresses, TLS or QUIC details where present, such as the server name, the negotiated protocol and whether the request arrived as early data, as [early data](http3.md#early-data-0-rtt) defines that flag, and what a PROXY protocol header supplied. Over HTTP/3, the peer address is the connection's current peer address when the request stream is received. Handlers currently receive no connection information, so this extends the server's handler interface, which [clients and connections](client-connection.md#exchange-completion-and-reuse) describes as receiving the request. The information is a `Peer` value, named after `protocol-http`'s [`Peer`](https://github.com/socketry/protocol-http/blob/6b9b3d84f4e6261068fac7b52e567d70eb3909e5/lib/protocol/http/peer.rb) and defined in `base-http`, passed to the handler in the `ServerContext` of the shared [request interface](middleware.md#shared-request-interface), not as part of the request or its metadata, so a forwarded request cannot carry it upstream; decided on 2026-11-20. The proxy uses it for host routing, forwarding fields and early data, and passes it to policy objects. +`base-http-server` makes each request's connection information available to its handler: the peer and local addresses, TLS or QUIC details where present, such as the server name, the negotiated protocol and whether the request arrived as early data, as [early data](http3.md#early-data-0-rtt) defines that flag, and what a PROXY protocol header supplied. Over HTTP/3, the peer address is the connection's current peer address when the request stream is received. Handlers currently receive no connection information, so this extends the server's handler interface, which [clients and connections](client-connection.md#exchange-completion-and-reuse) describes as receiving the request. The information is a `Peer` value, named after `protocol-http`'s [`Peer`](https://github.com/socketry/protocol-http/blob/6b9b3d84f4e6261068fac7b52e567d70eb3909e5/lib/protocol/http/peer.rb) and defined in `base-http`, passed to the handler in the `ServerContext` of the shared [request interface](middleware.md#shared-request-interface), not as part of the request or its metadata, so a forwarded request cannot carry it upstream; decided on 2026-11-20. The proxy uses it for host routing, forwarding fields and early data, and passes it to policy objects. The `Peer` implemented on 2026-11-21 reports the addresses, encryption and negotiated application protocol, and early data, which is always false until HTTP/3; the TLS server name needs an accessor in `base-endpoint`, whose 0.3 TLS connection does not expose it, and PROXY protocol details arrive with the listener wrapper. Listeners can be configured to require the [PROXY protocol](https://www.haproxy.org/download/2.9/doc/proxy-protocol.txt), version 1, version 2 or either, from configured trusted source addresses: diff --git a/design/middleware.md b/design/middleware.md index 2821e1ac..966f241d 100644 --- a/design/middleware.md +++ b/design/middleware.md @@ -44,13 +44,15 @@ The interface lives in `base-http`, which depends on no protocol crate, client, The interface is the current `base_http_server::Handler`, moved into `base-http` and made generic over the context, as `Handler`, keeping its associated `Error` and `Body` types, with the signature `call(request, &mut C, &Cancellation)`; `base-http-server` re-exports it. The interim-hook type, a generic parameter of `call` now, becomes a parameter of each context type. A middleware forwards the context to its delegate, changing only what it handles, and can give its delegate a narrower cancellation. Decided on 2026-11-20, after first considering one shared context with optional fields for each side. +As implemented on 2026-11-21, the interface is `Handler<'scope, C: HandlerContext>`, with request bodies that outlive `'scope` as [above](#shared-request-interface) records, and `HandlerContext` is the small trait both contexts implement, giving `interim()`. `ServerContext` takes no type or lifetime parameter. The user chose on 2026-11-21 to hide the interim hook's type rather than name each protocol engine's writer in the server's bounds, accepting an allocation for each interim response sent; the relay below hides it without that allocation. A context borrowing the connection's writer instead would make a handler's response type depend on that borrow, so the server could not write the response. It holds the connection's `Peer`, shared by its requests, and an `InterimSender`, which hands each interim response to the connection's `InterimRelay`; the server writes it while it continues to poll the handler, and the send returns once the response is written. A send allocates nothing, and the connection allocates its relay and `Peer` once. A hook used after its exchange fails with `InterimRelayError::Finished`. `ClientContext` carries the application's observer and `RequestOptions`, which has no options yet and cannot be constructed field by field, so options can be added: the user accepted on 2026-11-21 that the planned options all belong to later transports, such as early data with HTTP/3, so the test of a middleware setting an option the client honours waits for the first option. The client reports its own `Error` as the interface's error type, also accepted that day. `call_send` lives in `base-http` with the interface. `Peer` reports the peer and local addresses, whether the connection is encrypted and its negotiated application protocol, and whether a request arrived as early data, always false until HTTP/3; its fields are private, so the TLS server name, which `base-endpoint` 0.3 does not expose, and PROXY protocol details can be added. + ### Rationale Async::HTTP composes applications and clients through protocol-http's [`Middleware`](https://github.com/socketry/protocol-http/blob/6b9b3d84f4e6261068fac7b52e567d70eb3909e5/lib/protocol/http/middleware.rb#L23-L54), which holds a `delegate` and forwards `call(request)`. Because server applications and `Async::HTTP::Client` both answer `call(request)`, one middleware can sit in front of either; Falcon's [proxy](https://github.com/socketry/falcon/blob/5107b0713fd78dbe8b08ee123391b1f4bcffdf12/lib/falcon/middleware/proxy.rb#L32-L79) is a middleware whose delegates, per host, are clients. Base has no such abstraction: its only request-to-response trait is the server's `Handler`, and the client's `call` is an inherent method with a different signature. The user decided on 2026-11-20 to follow the protocol-http model, so that the load balancer's request and response transformations are middleware layers around each upstream group's client. Separate context types, decided the same day, serve the user's goals of runtime efficiency followed by simplicity: each side carries only the data it has, with no optional fields to check or ignore, dispatch stays static, and the context's type states which side a layer is for, while middleware generic over the context keeps the reuse across sides that protocol-http's model provides. ### Scope -The request interface in `base-http`, its implementations in `base-http-server` and `base-http-client`, and middleware built on it, including the load balancer's layers. When the interface is implemented, the unrelated `ServerContext` test type in [`base-http-fixtures`](fixtures.md) is renamed, for example to `ServerFixture`, so the two are not confused. +The request interface in `base-http`, its implementations in `base-http-server` and `base-http-client`, and middleware built on it, including the load balancer's layers. The unrelated `ServerContext` and `ClientContext` test types in [`base-http-fixtures`](fixtures.md) were renamed `ServerFixture` and `ClientFixture` when the interface was implemented, so the two are not confused. ### Validation @@ -78,6 +80,5 @@ With the layer, WebSocket echo passes through the load balancer for every pair o ## Open questions -- `ClientContext`'s exact request options, and how the client reports its errors through the interface's associated error type. - An adapter for middleware stacks composed at runtime from configuration, which static nesting cannot express, such as an enum or boxed layer. - Whether optional adapters to other middleware interfaces, such as Tower's `Service`, are provided. diff --git a/src/handler.rs b/src/handler.rs new file mode 100644 index 00000000..8c71d805 --- /dev/null +++ b/src/handler.rs @@ -0,0 +1,189 @@ +// Released under the MIT License. +// Copyright, 2026, by Samuel Williams. + +//! One request interface for servers, clients and the middleware between them. +//! +//! A [`Handler`] takes a request, a mutable context and cancellation, and +//! produces a response, as `protocol-http`'s `call(request)` does. A server +//! calls its application with a [`ServerContext`]; a client is called with a +//! [`ClientContext`]. A middleware is a handler that holds another and calls +//! through to it. Middleware compose by wrapping, with static dispatch: a stack +//! is a nested type, and no layer boxes, requires `'static` or spawns a task. +//! +//! ```rust +//! use base_http::{ +//! Handler, HandlerContext, Request, Response, Status, +//! body::{BufferedBody, ReadableBody}, +//! }; +//! use base_scheduler::Cancellation; +//! use std::convert::Infallible; +//! +//! /// Adds a field to every response, for a server or a client alike. +//! struct Tagged(H); +//! impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Tagged { +//! type Error = H::Error; +//! type Body = H::Body; +//! async fn call( +//! &self, +//! request: Request, +//! context: &mut C, +//! cancellation: &Cancellation, +//! ) -> Result>, H::Error> { +//! let mut response = self.0.call(request, context, cancellation).await?; +//! response.fields.add("x-tagged", "yes").unwrap(); +//! Ok(response) +//! } +//! } +//! ``` +use crate::{ + InterimHandler, InterimResponses, Peer, Request, Response, body::ReadableBody, + interim::InterimSender, +}; +use base_scheduler::Cancellation; +use std::{error::Error, future::Future, sync::Arc}; + +/// Produce a response for a request, given a context of type `C`. +/// +/// Bodies and contexts stay generic, so a layer passes a body through without +/// copying, and a returned body may retain the request body. A request body +/// lives for `'scope`, such as a server's borrow of its scheduler, so a handler +/// can pass it to work that outlives the call, such as a client forwarding it +/// upstream. +/// +/// A middleware written for any context implements `Handler<'h, C>` for every +/// `C: HandlerContext`, so it wraps a server application or a client alike. One +/// that needs a side's own data, such as the [`Peer`], is written for that +/// side's context, so placing it on the other side does not compile. +/// +/// A middleware for one side cannot be placed on the other: +/// +/// ```rust,compile_fail,E0277 +/// use base_http::{ +/// ClientContext, Handler, InterimHandler, Request, Response, ServerContext, +/// body::ReadableBody, +/// }; +/// use base_scheduler::Cancellation; +/// +/// /// Reads the server's peer, so it is written for `ServerContext` only. +/// struct PeerLogged(H); +/// impl<'h, H: Handler<'h, ServerContext>> Handler<'h, ServerContext> for PeerLogged { +/// type Error = H::Error; +/// type Body = H::Body; +/// async fn call( +/// &self, +/// request: Request, +/// context: &mut ServerContext, +/// cancellation: &Cancellation, +/// ) -> Result>, H::Error> { +/// println!("{:?}", context.peer().address()); +/// self.0.call(request, context, cancellation).await +/// } +/// } +/// +/// fn client_side<'h, I: InterimHandler, H: Handler<'h, ClientContext>>(_: &H) {} +/// +/// fn place<'h, I: InterimHandler, H: Handler<'h, ClientContext>>(client: H) { +/// client_side::(&PeerLogged(client)); +/// } +/// ``` +/// +/// Generic code awaiting a handler bound to one `'scope` inside its own `Send` +/// future may be rejected by rustc with "implementation of `Handler` is not +/// general enough"; awaiting [`call_send`] instead avoids it. +pub trait Handler<'scope, C: HandlerContext>: Sync { + type Error: Error + Send + Sync + 'static; + type Body: ReadableBody; + + fn call( + &self, + request: Request, + context: &mut C, + cancellation: &Cancellation, + ) -> impl Future>, Self::Error>> + Send; +} + +/// What every context gives a handler: the exchange's interim-response hook. +/// A server's hook sends informational responses to the peer, such as 103 +/// Early Hints; a client's observes those the upstream sends. +pub trait HandlerContext: Send { + type Interim: InterimHandler; + fn interim(&mut self) -> &mut InterimResponses; +} + +/// Call `handler` through a future whose type states `Send`, for generic code +/// that awaits a handler bound to one `'scope` within its own `Send` future, +/// which rustc may otherwise reject as "not general enough". +pub fn call_send<'scope, C, H, B>( + handler: &H, + request: Request, + context: &mut C, + cancellation: &Cancellation, +) -> impl Future>, H::Error>> + Send +where + C: HandlerContext, + H: Handler<'scope, C>, + B: ReadableBody + 'scope, +{ + handler.call(request, context, cancellation) +} + +/// The context a server passes to its handler for one exchange: the +/// connection's [`Peer`] and the hook for sending interim responses, such as +/// 103 Early Hints, which the server writes. +/// +/// It borrows nothing from the server, so a handler's response cannot depend +/// on it, and handlers need not name each protocol engine's writer. +pub struct ServerContext { + peer: Arc, + interim: InterimResponses, +} + +impl ServerContext { + pub fn new(peer: Arc, interim: InterimSender) -> Self { + Self { + peer, + interim: InterimResponses::new(interim), + } + } + + /// The connection the request arrived on. + pub fn peer(&self) -> &Arc { + &self.peer + } +} + +impl HandlerContext for ServerContext { + type Interim = InterimSender; + fn interim(&mut self) -> &mut InterimResponses { + &mut self.interim + } +} + +/// The context an application passes when calling a client: the observer of +/// interim responses the upstream sends, and options for this request. +pub struct ClientContext { + interim: InterimResponses, + pub options: RequestOptions, +} + +impl ClientContext { + pub fn new(observer: I) -> Self { + Self { + interim: InterimResponses::new(observer), + options: RequestOptions::default(), + } + } +} + +impl HandlerContext for ClientContext { + type Interim = I; + fn interim(&mut self) -> &mut InterimResponses { + &mut self.interim + } +} + +/// Per-request client options. None exist yet; options such as whether a +/// request may be sent as early data arrive with the transports that need them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct RequestOptions {} diff --git a/src/interim.rs b/src/interim.rs index 21a4242c..1d5c7e21 100644 --- a/src/interim.rs +++ b/src/interim.rs @@ -21,7 +21,10 @@ //! # Ok::<(), base_http::InterimError>(()) //! ``` use crate::{ResponseMetadata, Status, future::cancellable}; + +mod relay; use base_scheduler::Cancellation; +pub use relay::{InterimRelay, InterimRelayError, InterimSender}; use std::{error::Error, fmt, future::Future}; /// A protocol writer or client observer for an interim response head. diff --git a/src/interim/relay.rs b/src/interim/relay.rs new file mode 100644 index 00000000..945b80e0 --- /dev/null +++ b/src/interim/relay.rs @@ -0,0 +1,318 @@ +// Released under the MIT License. +// Copyright, 2026, by Samuel Williams. + +//! Interim responses handed from a handler to the server that writes them. +//! +//! A server creates one [`InterimRelay`] per connection and gives each +//! exchange's handler an [`InterimSender`]. A send hands its response head to +//! the relay and waits until the server has written it. The server writes the +//! head while it continues to poll the handler, so the handler's other work +//! proceeds meanwhile. The sender borrows nothing from the server, so a context +//! holding it has no lifetime, and handing a head over allocates nothing. +use super::InterimHandler; +use crate::ResponseMetadata; +use base_scheduler::Cancellation; +use std::{ + error::Error, + fmt, + future::poll_fn, + sync::{Arc, Mutex, MutexGuard, PoisonError}, + task::{Poll, Waker}, +}; + +struct State { + /// The exchange whose senders may hand over responses. + exchange: u64, + /// A response handed over and not yet taken by the server. + pending: Option, + /// The server is writing the response it took. + writing: bool, + /// How writing the taken response ended, until its sender collects it. + result: Option>, + /// The server waiting for a response, or a no-op waker. + relay: Waker, + /// The sender waiting for its result, or a no-op waker. + sender: Waker, +} + +struct Shared { + state: Mutex, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +fn register(slot: &mut Waker, waker: &Waker) { + slot.clone_from(waker); +} + +/// Take the registered waker, leaving a no-op one. +fn take(slot: &mut Waker) -> Waker { + std::mem::replace(slot, Waker::noop().clone()) +} + +/// The server's end of a connection's interim responses. +pub struct InterimRelay { + shared: Arc, +} + +impl Default for InterimRelay { + fn default() -> Self { + Self::new() + } +} + +impl InterimRelay { + pub fn new() -> Self { + Self { + shared: Arc::new(Shared { + state: Mutex::new(State { + exchange: 0, + pending: None, + writing: false, + result: None, + relay: Waker::noop().clone(), + sender: Waker::noop().clone(), + }), + }), + } + } + + /// A hook for the current exchange's handler. + pub fn sender(&self) -> InterimSender { + InterimSender { + shared: self.shared.clone(), + exchange: self.shared.lock().exchange, + } + } + + /// Wait for the next response a sender hands over. Dropping the wait takes + /// nothing. Report how writing it ended with [`complete`](Self::complete). + pub async fn next(&self) -> ResponseMetadata { + poll_fn(|cx| { + let mut state = self.shared.lock(); + match state.pending.take() { + Some(response) => { + state.writing = true; + Poll::Ready(response) + } + None => { + register(&mut state.relay, cx.waker()); + Poll::Pending + } + } + }) + .await + } + + /// Report how writing the response taken by [`next`](Self::next) ended, + /// waking its sender. + pub fn complete(&self, result: Result<(), E>) { + let sender = { + let mut state = self.shared.lock(); + if !state.writing { + return; + } + state.writing = false; + state.result = Some(result.map_err(|error| InterimRelayError::Failed(Box::new(error)))); + take(&mut state.sender) + }; + sender.wake(); + } + + /// End the current exchange. Its senders' later sends fail with + /// [`InterimRelayError::Finished`], and one not yet taken is discarded. + pub fn finish(&self) { + let sender = { + let mut state = self.shared.lock(); + state.exchange += 1; + state.pending = None; + state.writing = false; + state.result = None; + take(&mut state.sender) + }; + sender.wake(); + } +} + +/// A handler's hook for one exchange's interim responses, which the server +/// writes. Each send returns once the server has written and flushed the head. +pub struct InterimSender { + shared: Arc, + exchange: u64, +} + +/// Withdraws a handed-over response that the server has not taken, when its +/// send is dropped. +struct Withdraw<'a>(&'a InterimSender); + +impl Drop for Withdraw<'_> { + fn drop(&mut self) { + let mut state = self.0.shared.lock(); + if state.exchange == self.0.exchange { + state.pending = None; + state.result = None; + } + } +} + +impl InterimHandler for InterimSender { + type Error = InterimRelayError; + async fn on_interim_response( + &mut self, + response: ResponseMetadata, + _: &Cancellation, + ) -> Result<(), InterimRelayError> { + let relay = { + let mut state = self.shared.lock(); + if state.exchange != self.exchange { + return Err(InterimRelayError::Finished); + } + state.pending = Some(response); + state.result = None; + take(&mut state.relay) + }; + relay.wake(); + let _withdraw = Withdraw(self); + poll_fn(|cx| { + let mut state = self.shared.lock(); + if state.exchange != self.exchange { + return Poll::Ready(Err(InterimRelayError::Finished)); + } + if let Some(result) = state.result.take() { + return Poll::Ready(result); + } + register(&mut state.sender, cx.waker()); + Poll::Pending + }) + .await + } +} + +/// Why a relayed interim response was not sent. `Failed` is transparent: it +/// displays the server's error and reports that error's source. +#[derive(Debug)] +pub enum InterimRelayError { + /// The exchange ended, so it accepts no more interim responses. + Finished, + /// The server failed to write the response. + Failed(Box), +} + +impl fmt::Display for InterimRelayError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Finished => formatter.write_str("the exchange has finished"), + Self::Failed(error) => error.fmt(formatter), + } + } +} + +impl Error for InterimRelayError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Finished => None, + Self::Failed(error) => error.source(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{InterimResponses, Status}; + use futures_lite::future::{block_on, poll_once, zip}; + use std::{io, pin::pin}; + + /// An error with a source, as protocol writers report I/O failures. + #[derive(Debug)] + struct Wrapped(io::Error); + impl fmt::Display for Wrapped { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("interim write failed") + } + } + impl Error for Wrapped { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.0) + } + } + + fn hint() -> ResponseMetadata { + ResponseMetadata::new(Status::EARLY_HINTS) + } + + #[test] + fn a_send_returns_once_the_server_has_written_its_response() { + let relay = InterimRelay::default(); + let mut interim = InterimResponses::new(relay.sender()); + let never = Cancellation::never(); + let (sent, ()) = block_on(zip(interim.send_interim_response(hint(), &never), async { + let response = relay.next().await; + assert_eq!(response.status, Status::EARLY_HINTS); + relay.complete(Ok::<_, io::Error>(())); + })); + sent.unwrap(); + // A completion with nothing being written changes nothing. + relay.complete(Ok::<_, io::Error>(())); + } + + #[test] + fn a_failed_write_is_reported_transparently() { + let relay = InterimRelay::new(); + let mut sender = relay.sender(); + let never = Cancellation::never(); + let (sent, ()) = block_on(zip(sender.on_interim_response(hint(), &never), async { + relay.next().await; + relay.complete(Err(Wrapped(io::Error::other("connection reset")))); + })); + let error = sent.unwrap_err(); + assert_eq!(error.to_string(), "interim write failed"); + assert_eq!(error.source().unwrap().to_string(), "connection reset"); + assert!(InterimRelayError::Finished.source().is_none()); + } + + #[test] + fn senders_of_a_finished_exchange_are_refused() { + let relay = InterimRelay::new(); + let mut stale = relay.sender(); + let never = Cancellation::never(); + { + // A send waiting when its exchange finishes is refused too. + let mut waiting = pin!(stale.on_interim_response(hint(), &never)); + assert!(block_on(poll_once(waiting.as_mut())).is_none()); + relay.finish(); + let refused = block_on(waiting).unwrap_err(); + assert_eq!(refused.to_string(), "the exchange has finished"); + } + let refused = block_on(stale.on_interim_response(hint(), &never)).unwrap_err(); + assert_eq!(refused.to_string(), "the exchange has finished"); + // The next exchange's sender is accepted. + let mut interim = InterimResponses::new(relay.sender()); + let (sent, ()) = block_on(zip(interim.send_interim_response(hint(), &never), async { + relay.next().await; + relay.complete(Ok::<_, io::Error>(())); + })); + sent.unwrap(); + } + + #[test] + fn a_dropped_send_withdraws_its_response() { + let relay = InterimRelay::new(); + let mut sender = relay.sender(); + let never = Cancellation::never(); + { + let mut sending = pin!(sender.on_interim_response(hint(), &never)); + assert!(block_on(poll_once(sending.as_mut())).is_none()); + } + assert!(block_on(poll_once(pin!(relay.next()))).is_none()); + let cancelled = Cancellation::new(); + cancelled.cancel(); + let mut interim = InterimResponses::new(relay.sender()); + let refused = block_on(interim.send_interim_response(hint(), &cancelled)).unwrap_err(); + assert_eq!(refused.to_string(), "interim response cancelled"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 660c41cb..4e8a5d42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,9 +6,11 @@ pub mod body; pub mod fields; +pub mod handler; pub mod headers; pub mod interim; pub mod method; +pub mod peer; pub mod protocol; pub mod request; pub mod response; @@ -20,9 +22,15 @@ mod future; mod syntax; pub use fields::{Field, FieldError, Fields}; +pub use handler::{ + ClientContext, Handler, HandlerContext, RequestOptions, ServerContext, call_send, +}; pub use headers::HttpHeaders; -pub use interim::{InterimError, InterimHandler, InterimResponses}; +pub use interim::{ + InterimError, InterimHandler, InterimRelay, InterimRelayError, InterimResponses, InterimSender, +}; pub use method::Method; +pub use peer::Peer; pub use protocol::Protocol; pub use request::{Request, RequestMetadata}; pub use response::{Response, ResponseMetadata}; diff --git a/src/peer.rs b/src/peer.rs new file mode 100644 index 00000000..1c52537d --- /dev/null +++ b/src/peer.rs @@ -0,0 +1,68 @@ +// Released under the MIT License. +// Copyright, 2026, by Samuel Williams. + +//! What a server knows about the connection a request arrived on. +//! +//! A [`Peer`] reaches a handler through its [`ServerContext`](crate::ServerContext), +//! not through the request, so forwarding a request cannot carry it upstream. +//! It is named after `protocol-http`'s `Peer`. +use std::net::SocketAddr; + +/// Connection information for the requests a server receives on one connection. +/// +/// Fields are private so later details, such as those a PROXY protocol header +/// or QUIC supplies, can be added without breaking callers. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Peer { + address: Option, + local_address: Option, + encrypted: bool, + application_protocol: Option>, +} + +impl Peer { + /// A peer at `address`, received on `local_address`. Either is `None` when + /// the transport has no IP address, such as a Unix socket, or reported none. + pub fn new(address: Option, local_address: Option) -> Self { + Self { + address, + local_address, + ..Self::default() + } + } + + /// The same peer over an encrypted transport, which negotiated + /// `application_protocol`, such as `http/1.1`, when the peer offered one. + pub fn encrypted(mut self, application_protocol: Option<&[u8]>) -> Self { + self.encrypted = true; + self.application_protocol = application_protocol.map(Box::from); + self + } + + /// The remote address of the connection. + pub fn address(&self) -> Option { + self.address + } + + /// The local address the connection was received on. + pub fn local_address(&self) -> Option { + self.local_address + } + + /// Whether the connection is encrypted, such as by TLS. + pub fn is_encrypted(&self) -> bool { + self.encrypted + } + + /// The application protocol an encrypted connection negotiated, such as + /// `h2` or `http/1.1`. + pub fn application_protocol(&self) -> Option<&[u8]> { + self.application_protocol.as_deref() + } + + /// Whether the request arrived as TLS early data, which a replay could + /// repeat. No current transport accepts early data, so this is false. + pub fn is_early_data(&self) -> bool { + false + } +} diff --git a/tests/handler.rs b/tests/handler.rs new file mode 100644 index 00000000..4449a69e --- /dev/null +++ b/tests/handler.rs @@ -0,0 +1,319 @@ +// Released under the MIT License. +// Copyright, 2026, by Samuel Williams. + +//! The shared request interface: middleware generic over the context wraps a +//! server's handler and a client's alike. + +use base_http::{ + ClientContext, Fields, Handler, HandlerContext, InterimRelay, Method, Peer, Request, + RequestOptions, Response, ResponseMetadata, ServerContext, Status, + body::{BodyFrame, BufferedBody, Chunk, ReadableBody}, +}; +use base_scheduler::Cancellation; +use futures_lite::future::{block_on, zip}; +use std::{ + convert::Infallible, + io, + sync::{Arc, Mutex}, +}; + +/// Echoes the request body, and its fields as response fields, for any context. +struct Echo; +impl<'h, C: HandlerContext> Handler<'h, C> for Echo { + type Error = io::Error; + type Body = B; + async fn call( + &self, + request: Request, + _: &mut C, + cancellation: &Cancellation, + ) -> Result, io::Error> { + if cancellation.is_cancelled() { + return Err(io::Error::other("cancelled")); + } + let (metadata, body) = request.into_parts(); + let mut response = Response::new(Status::OK, body); + response.fields = metadata.fields; + Ok(response) + } +} + +/// Adds its name to the request on the way in and the response on the way out. +struct Tagged(&'static str, H); +impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Tagged { + type Error = H::Error; + type Body = H::Body; + async fn call( + &self, + mut request: Request, + context: &mut C, + cancellation: &Cancellation, + ) -> Result>, H::Error> { + request.fields.add("x-in", self.0).unwrap(); + let mut response = self.1.call(request, context, cancellation).await?; + response.fields.add("x-out", self.0).unwrap(); + Ok(response) + } +} + +/// Answers `/answered` itself, with a body of its own, without its delegate. +struct Answering(H); +enum Either { + Delegated(A), + Answered(BufferedBody>), +} +impl ReadableBody for Either { + type Data = Vec; + type Error = io::Error; + async fn read(&mut self, cancellation: &Cancellation) -> Result>, io::Error> { + match self { + Self::Delegated(body) => body + .read(cancellation) + .await + .map(|frame| frame.map_data(Chunk::into_vec)) + .map_err(io::Error::other), + Self::Answered(body) => body.read(cancellation).await.map_err(io::Error::other), + } + } + fn close(&mut self, error: Option) { + match self { + Self::Delegated(body) => body.close(None), + Self::Answered(body) => body.close(None), + } + drop(error); + } +} +impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Answering { + type Error = H::Error; + type Body = Either>; + async fn call( + &self, + request: Request, + context: &mut C, + cancellation: &Cancellation, + ) -> Result>>, H::Error> { + if request.path.as_deref() == Some("/answered") { + let body = BufferedBody::from(b"answered".to_vec()); + return Ok(Response::new(Status::OK, Either::Answered(body))); + } + Ok(self + .0 + .call(request, context, cancellation) + .await? + .map_body(Either::Delegated)) + } +} + +fn read_all(body: &mut B) -> Vec { + let mut data = Vec::new(); + while let BodyFrame::Data { data: chunk, .. } = + block_on(body.read(&Cancellation::never())).unwrap() + { + data.extend_from_slice(chunk.as_ref()); + } + data +} + +/// Gives its delegate a cancellation of its own, already cancelled. +struct Narrowing(H); +impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Narrowing { + type Error = H::Error; + type Body = H::Body; + async fn call( + &self, + request: Request, + context: &mut C, + cancellation: &Cancellation, + ) -> Result>, H::Error> { + let narrower = cancellation.child(); + narrower.cancel(); + self.0.call(request, context, &narrower).await + } +} + +/// Sends 103 Early Hints through whichever context it is given. +struct Hinting(H); +impl<'h, C: HandlerContext, H: Handler<'h, C>> Handler<'h, C> for Hinting { + type Error = H::Error; + type Body = H::Body; + async fn call( + &self, + request: Request, + context: &mut C, + cancellation: &Cancellation, + ) -> Result>, H::Error> { + context + .interim() + .send_interim_response(ResponseMetadata::new(Status::EARLY_HINTS), cancellation) + .await + .unwrap(); + self.0.call(request, context, cancellation).await + } +} + +/// A server-only middleware: it reads the connection's peer. +struct PeerTagged(H); +impl<'h, H: Handler<'h, ServerContext>> Handler<'h, ServerContext> for PeerTagged { + type Error = H::Error; + type Body = H::Body; + async fn call( + &self, + request: Request, + context: &mut ServerContext, + cancellation: &Cancellation, + ) -> Result>, H::Error> { + let peer = context.peer().clone(); + let mut response = self.0.call(request, context, cancellation).await?; + let address = peer.address().unwrap().to_string(); + response.fields.add("x-peer", address.as_str()).unwrap(); + Ok(response) + } +} + +fn server_context() -> (ServerContext, InterimRelay) { + let relay = InterimRelay::new(); + (ServerContext::new(Arc::default(), relay.sender()), relay) +} + +fn client_context() -> ClientContext { + ClientContext::new(|_: ResponseMetadata| async { Ok::<_, Infallible>(()) }) +} + +fn values(fields: &Fields, name: &str) -> Vec { + fields + .values(name) + .map(|value| String::from_utf8(value.to_vec()).unwrap()) + .collect() +} + +#[test] +fn the_same_middleware_wraps_a_server_handler_and_a_client_and_applies_in_order() { + let stack = Tagged("outer", Tagged("inner", Echo)); + let never = Cancellation::never(); + let request = || Request::new(Method::POST, "/", BufferedBody::from(b"hello".to_vec())); + let (mut server, _relay) = server_context(); + let served = block_on(stack.call(request(), &mut server, &never)).unwrap(); + let mut client = client_context(); + let called = block_on(stack.call(request(), &mut client, &never)).unwrap(); + for response in [served, called] { + // Requests pass the outer layer first; responses leave the inner first. + assert_eq!(values(&response.fields, "x-in"), ["outer", "inner"]); + assert_eq!(values(&response.fields, "x-out"), ["inner", "outer"]); + } +} + +#[test] +fn a_layer_answers_without_calling_its_delegate() { + let stack = Answering(Tagged("delegate", Echo)); + let (mut context, _relay) = server_context(); + let never = Cancellation::never(); + let mut answered = block_on(stack.call( + Request::new( + Method::GET, + "/answered", + BufferedBody::from(b"unread".to_vec()), + ), + &mut context, + &never, + )) + .unwrap(); + assert!(values(&answered.fields, "x-out").is_empty()); + assert_eq!(read_all(&mut answered.body), b"answered"); + let mut delegated = block_on(stack.call( + Request::new(Method::POST, "/", BufferedBody::from(b"echoed".to_vec())), + &mut context, + &never, + )) + .unwrap(); + assert_eq!(values(&delegated.fields, "x-out"), ["delegate"]); + assert_eq!(read_all(&mut delegated.body), b"echoed"); + answered.body.close(None); + delegated.body.close(None); +} + +#[test] +fn a_layer_gives_its_delegate_a_narrower_cancellation() { + let stack = Narrowing(Echo); + let mut context = client_context(); + let outer = Cancellation::new(); + let refused = block_on(stack.call( + Request::new(Method::GET, "/", BufferedBody::>::default()), + &mut context, + &outer, + )); + assert!(refused.is_err()); + assert!(!outer.is_cancelled()); +} + +#[test] +fn a_borrowed_request_body_passes_through_layers_without_copying() { + let stack = Tagged("outer", Tagged("inner", Echo)); + let mut local = BufferedBody::from(b"borrowed".to_vec()); + let address = &local as *const BufferedBody; + let mut context = client_context(); + let response = block_on(stack.call( + Request::new(Method::POST, "/", &mut local), + &mut context, + &Cancellation::never(), + )) + .unwrap(); + assert!(std::ptr::eq(&*response.body, address)); +} + +#[test] +fn generic_middleware_sends_interim_responses_through_either_context() { + let stack = Hinting(Echo); + let never = Cancellation::never(); + let request = || Request::new(Method::GET, "/", BufferedBody::>::default()); + + let observed = Arc::new(Mutex::new(Vec::new())); + let seen = observed.clone(); + let mut client = ClientContext::new(move |response: ResponseMetadata| { + let seen = seen.clone(); + async move { + seen.lock().unwrap().push(response.status); + Ok::<_, Infallible>(()) + } + }); + block_on(stack.call(request(), &mut client, &never)).unwrap(); + assert_eq!(*observed.lock().unwrap(), [Status::EARLY_HINTS]); + assert_eq!(client.options, RequestOptions::default()); + + let (mut server, relay) = server_context(); + let (response, written) = block_on(zip(stack.call(request(), &mut server, &never), async { + let written = relay.next().await; + relay.complete(Ok::<_, Infallible>(())); + written + })); + response.unwrap(); + assert_eq!(written.status, Status::EARLY_HINTS); +} + +#[test] +fn a_server_middleware_reads_the_peer() { + let peer = Peer::new( + Some("192.0.2.1:4433".parse().unwrap()), + Some("198.51.100.2:443".parse().unwrap()), + ) + .encrypted(Some(b"http/1.1")); + assert_eq!( + peer.local_address(), + Some("198.51.100.2:443".parse().unwrap()) + ); + assert!(peer.is_encrypted()); + assert_eq!(peer.application_protocol(), Some(&b"http/1.1"[..])); + assert!(!peer.is_early_data()); + let relay = InterimRelay::new(); + let mut context = ServerContext::new(Arc::new(peer), relay.sender()); + let response = block_on(PeerTagged(Echo).call( + Request::new(Method::GET, "/", BufferedBody::>::default()), + &mut context, + &Cancellation::never(), + )) + .unwrap(); + assert_eq!(values(&response.fields, "x-peer"), ["192.0.2.1:4433"]); + let plain = Peer::new(None, None); + assert!(!plain.is_encrypted()); + assert_eq!(plain.application_protocol(), None); + assert_eq!(plain, Peer::default()); +} From 2bed2208414594e75368924e6cbecd2457ccbecd Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sat, 21 Nov 2026 09:02:01 +1300 Subject: [PATCH 2/2] Merge the new `ServerContext` imports into each file's existing ones, keeping source headers intact. --- benchmarks/hello/src/main.rs | 3 +-- crates/client/examples/client_server.rs | 3 +-- crates/client/tests/https.rs | 4 +--- crates/client/tests/writable/main.rs | 2 +- crates/content/tests/server.rs | 4 +--- crates/fixtures/src/context.rs | 3 +-- crates/fixtures/src/context/tests.rs | 2 +- crates/fixtures/src/protocol.rs | 4 +--- crates/fixtures/tests/protocol.rs | 3 +-- crates/fixtures/tests/spawned.rs | 3 +-- crates/server/examples/client_server.rs | 3 +-- crates/server/examples/hello.rs | 3 +-- crates/server/tests/accept_errors.rs | 3 +-- crates/server/tests/end_to_end.rs | 3 +-- crates/server/tests/lent_bodies.rs | 4 +--- crates/server/tests/listener.rs | 3 +-- crates/server/tests/nodelay.rs | 3 +-- crates/server/tests/proxy.rs | 3 +-- crates/server/tests/support/mod.rs | 4 +--- crates/server/tests/tls.rs | 4 +--- crates/server/tests/transport_faults.rs | 3 +-- 21 files changed, 21 insertions(+), 46 deletions(-) diff --git a/benchmarks/hello/src/main.rs b/benchmarks/hello/src/main.rs index 354595b0..095f149d 100644 --- a/benchmarks/hello/src/main.rs +++ b/benchmarks/hello/src/main.rs @@ -1,12 +1,11 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::ServerContext; use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::Handler; +use base_http_server::{Handler, ServerContext}; use base_scheduler::{ Cancellation, SocketAccept, SocketClose, SocketLocalAddress, SocketPeerAddress, SocketRegistration, SocketSetOption, SocketStreamReading, SocketStreamWriting, Spawn, diff --git a/crates/client/examples/client_server.rs b/crates/client/examples/client_server.rs index 47e80e11..56ff4347 100644 --- a/crates/client/examples/client_server.rs +++ b/crates/client/examples/client_server.rs @@ -9,8 +9,7 @@ use base_http::{ body::{BodyFrame, BufferedBody, ReadableBody}, }; use base_http_client::{Client, Endpoint}; -use base_http_server::Handler; -use base_http_server::ServerContext; +use base_http_server::{Handler, ServerContext}; use base_scheduler::{Cancellation, SocketAccept, SocketClose, SocketLocalAddress}; use base_scheduler_native::NativeScheduler; use futures_lite::future::{block_on, zip}; diff --git a/crates/client/tests/https.rs b/crates/client/tests/https.rs index ec487731..2a94140b 100644 --- a/crates/client/tests/https.rs +++ b/crates/client/tests/https.rs @@ -2,8 +2,6 @@ // Copyright, 2026, by Samuel Williams. #![cfg(feature = "rustls")] -use base_http_server::ServerContext; - use base_endpoint::{AddressEndpoint, BindEndpoint, BindOptions}; use base_http::{ Method, Request, Response, Status, @@ -11,7 +9,7 @@ use base_http::{ }; use base_http_client::{Client, Endpoint, Error, Options}; use base_http_fixtures::socket::wait_acknowledged; -use base_http_server::Handler; +use base_http_server::{Handler, ServerContext}; use base_scheduler::{Cancellation, Clock, SocketLocalAddress}; use base_scheduler_native::NativeScheduler; use futures_lite::future::{block_on, zip}; diff --git a/crates/client/tests/writable/main.rs b/crates/client/tests/writable/main.rs index 91188161..323b3a11 100644 --- a/crates/client/tests/writable/main.rs +++ b/crates/client/tests/writable/main.rs @@ -5,13 +5,13 @@ mod support; mod open; -use base_http_server::ServerContext; use base_http::{ Fields, Method, Request, RequestMetadata, Scheme, body::{BodyFrame, EmptyBody, ReadableBody, WritableBody}, }; use base_http_client::{Client, Endpoint, Error, Options}; +use base_http_server::ServerContext; use base_scheduler::Cancellation; use base_scheduler_native::NativeScheduler; use futures_lite::future::{block_on, poll_once, zip}; diff --git a/crates/content/tests/server.rs b/crates/content/tests/server.rs index 09c63d73..949fc886 100644 --- a/crates/content/tests/server.rs +++ b/crates/content/tests/server.rs @@ -2,15 +2,13 @@ // Copyright, 2026, by Samuel Williams. //! Reading content in a `base-http-server` handler, over real connections. -use base_http_server::ServerContext; - use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_content::{FileStore, read_content}; use base_http_fixtures::{RawPeer, ServerFixture}; -use base_http_server::Handler; +use base_http_server::{Handler, ServerContext}; use base_scheduler::Cancellation; use base_scheduler_native::NativeScheduler; use base_web_content::{Content, ContentFormat, FieldPath, Upload}; diff --git a/crates/fixtures/src/context.rs b/crates/fixtures/src/context.rs index d3d527e0..9cf70c1d 100644 --- a/crates/fixtures/src/context.rs +++ b/crates/fixtures/src/context.rs @@ -1,6 +1,5 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::ServerContext; use crate::{Latch, RawPeer, Scheduler, native}; use base_http::{ @@ -8,7 +7,7 @@ use base_http::{ body::{BufferedBody, ReadableBody}, }; use base_http_client::{Client, Driver, Endpoint}; -use base_http_server::Handler; +use base_http_server::{Handler, ServerContext}; use base_scheduler::{Cancellation, Clock, SocketType, Spawn, TaskError}; use base_scheduler_native::{NativeOptions, NativeScheduler}; use futures_lite::future::{block_on, or, zip}; diff --git a/crates/fixtures/src/context/tests.rs b/crates/fixtures/src/context/tests.rs index f18c986e..c6fbb9bf 100644 --- a/crates/fixtures/src/context/tests.rs +++ b/crates/fixtures/src/context/tests.rs @@ -1,9 +1,9 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::ServerContext; use super::*; use base_http::{Request, Response, Status, body::EmptyBody}; +use base_http_server::ServerContext; use std::{convert::Infallible, io::Write, net::TcpStream}; /// Blocks its worker in every call until released, so the server cannot observe cancellation. diff --git a/crates/fixtures/src/protocol.rs b/crates/fixtures/src/protocol.rs index 698809d7..81ca4461 100644 --- a/crates/fixtures/src/protocol.rs +++ b/crates/fixtures/src/protocol.rs @@ -4,14 +4,12 @@ //! The [`protocol_tests!`](crate::protocol_tests) suite, ported from `async-http`'s `AProtocol` shared behaviour. //! //! One application, [`App`], serves every case on its own route, so a runner only chooses how to serve and connect: the HTTP version, options and transport. Each case is a standalone `pub async fn` taking the running [`Context`], so a partial implementation can call a subset. The cases address the application through `H: Borrow`, so a test can wrap it to change its behaviour. -use base_http_server::{HandlerContext, ServerContext}; - use crate::{Context, Latch, Scheduler, body}; use base_http::{ Fields, Method, Request, Response, ResponseMetadata, Status, Version, body::{BodyError, BodyFrame, BodyReader, BufferedBody, ReadableBody}, }; -use base_http_server::Handler; +use base_http_server::{Handler, HandlerContext, ServerContext}; use base_scheduler::Cancellation; use event_listener::{Event, listener}; use futures_lite::future::zip; diff --git a/crates/fixtures/tests/protocol.rs b/crates/fixtures/tests/protocol.rs index 993dee2d..d67475b0 100644 --- a/crates/fixtures/tests/protocol.rs +++ b/crates/fixtures/tests/protocol.rs @@ -10,8 +10,7 @@ use base_http_fixtures::{ ServerFixture, body, protocol::{self, App, LARGE_BODY, Reply, Staged, Step}, }; -use base_http_server::Handler; -use base_http_server::{HandlerContext, ServerContext}; +use base_http_server::{Handler, HandlerContext, ServerContext}; use base_scheduler::Cancellation; use base_scheduler::Clock; use futures_lite::future::{or, zip}; diff --git a/crates/fixtures/tests/spawned.rs b/crates/fixtures/tests/spawned.rs index 4deb0e70..3d807a2c 100644 --- a/crates/fixtures/tests/spawned.rs +++ b/crates/fixtures/tests/spawned.rs @@ -4,8 +4,7 @@ //! A spawned server runs on the scheduler's workers beside a client driven from the test's thread, and reports each way it can fail, in order. use base_http::{Method, Request, Response, Status, body::EmptyBody, body::ReadableBody}; use base_http_fixtures::{Context, Hello, ServerFixture, body::payload, protocol::App}; -use base_http_server::Handler; -use base_http_server::ServerContext; +use base_http_server::{Handler, ServerContext}; use base_scheduler::Cancellation; use base_scheduler_native::NativeScheduler; use std::{convert::Infallible, io::Read}; diff --git a/crates/server/examples/client_server.rs b/crates/server/examples/client_server.rs index 17d415de..1eaa1c11 100644 --- a/crates/server/examples/client_server.rs +++ b/crates/server/examples/client_server.rs @@ -7,8 +7,7 @@ use base_http::{ InterimResponses, Method, Request, Response, ResponseMetadata, Status, body::{BodyFrame, BufferedBody, ReadableBody}, }; -use base_http_server::Handler; -use base_http_server::ServerContext; +use base_http_server::{Handler, ServerContext}; use base_http1::{RequestWriter, ResponseReader}; use base_scheduler::{ Cancellation, SocketAccept, SocketBind, SocketClose, SocketConnect, SocketListen, diff --git a/crates/server/examples/hello.rs b/crates/server/examples/hello.rs index 5a29dc71..8e595636 100644 --- a/crates/server/examples/hello.rs +++ b/crates/server/examples/hello.rs @@ -1,12 +1,11 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::ServerContext; use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::{Handler, Options}; +use base_http_server::{Handler, Options, ServerContext}; use base_scheduler::{ Cancellation, SocketAccept, SocketBind, SocketClose, SocketListen, SocketLocalAddress, SocketOpen, SocketType, diff --git a/crates/server/tests/accept_errors.rs b/crates/server/tests/accept_errors.rs index 984a90f1..7b959a28 100644 --- a/crates/server/tests/accept_errors.rs +++ b/crates/server/tests/accept_errors.rs @@ -8,8 +8,7 @@ use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::ServerContext; -use base_http_server::{Error, Handler, Options, Statistics}; +use base_http_server::{Error, Handler, Options, ServerContext, Statistics}; use base_scheduler::{ BufferPool, BufferPoolOptions, BufferPooling, Cancellation, Clock, IoBuf, OperationError, OperationResult, SocketAccept, SocketAddress, SocketClose, SocketLocalAddress, SocketOperation, diff --git a/crates/server/tests/end_to_end.rs b/crates/server/tests/end_to_end.rs index 39104754..8e158789 100644 --- a/crates/server/tests/end_to_end.rs +++ b/crates/server/tests/end_to_end.rs @@ -1,12 +1,11 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::{HandlerContext, ServerContext}; use base_http::{ Fields, HttpHeaders, Method, Request, RequestMetadata, Response, ResponseMetadata, Status, body::{BodyFrame, BodyReader, BufferedBody, ReadableBody}, }; -use base_http_server::{Error, Handler}; +use base_http_server::{Error, Handler, HandlerContext, ServerContext}; use base_scheduler::{Cancellation, Clock}; use futures_lite::future::block_on; use std::{ diff --git a/crates/server/tests/lent_bodies.rs b/crates/server/tests/lent_bodies.rs index 13e84531..e455c8b6 100644 --- a/crates/server/tests/lent_bodies.rs +++ b/crates/server/tests/lent_bodies.rs @@ -6,13 +6,11 @@ //! cancelled or its handler fails. mod support; -use base_http_server::{HandlerContext, ServerContext}; - use base_http::{ Request, Response, Status, body::{BodyFrame, BufferedBody, ReadableBody}, }; -use base_http_server::{Error, Handler}; +use base_http_server::{Error, Handler, HandlerContext, ServerContext}; use base_scheduler::{Cancellation, Clock, SocketAccept, SocketClose}; use futures_lite::future::block_on; use futures_util::{StreamExt, stream::FuturesUnordered}; diff --git a/crates/server/tests/listener.rs b/crates/server/tests/listener.rs index aec36e9c..24ecbf7e 100644 --- a/crates/server/tests/listener.rs +++ b/crates/server/tests/listener.rs @@ -1,12 +1,11 @@ // Released under the MIT License. // Copyright, 2026, by Samuel Williams. -use base_http_server::ServerContext; use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::{Error, Handler, Options}; +use base_http_server::{Error, Handler, Options, ServerContext}; use base_scheduler::Cancellation; use futures_lite::future::block_on; use std::{ diff --git a/crates/server/tests/nodelay.rs b/crates/server/tests/nodelay.rs index 8fcfa4c4..7a72c395 100644 --- a/crates/server/tests/nodelay.rs +++ b/crates/server/tests/nodelay.rs @@ -6,8 +6,7 @@ use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::ServerContext; -use base_http_server::{Handler, Options}; +use base_http_server::{Handler, Options, ServerContext}; use base_scheduler::{ BufferPool, BufferPoolOptions, BufferPooling, Cancellation, Clock, IoBuf, OperationResult, SocketAccept, SocketAddress, SocketClose, SocketGetOption, SocketLocalAddress, SocketOperation, diff --git a/crates/server/tests/proxy.rs b/crates/server/tests/proxy.rs index 93555e51..9e331799 100644 --- a/crates/server/tests/proxy.rs +++ b/crates/server/tests/proxy.rs @@ -4,14 +4,13 @@ //! A deliberately small protocol-driver experiment, not a gateway policy API. //! Upload and download futures remain separately owned and polled until joined. mod support; -use base_http_server::{HandlerContext, ServerContext}; +use base_http_server::{Handler, HandlerContext, ServerContext}; use support::*; use base_http::{ Fields, InterimResponses, Request, RequestMetadata, Response, ResponseMetadata, Status, body::ReadableBody, }; -use base_http_server::Handler; use base_http1::{Error, RequestReader, RequestWriter, ResponseReader, ResponseWriter}; use base_scheduler::{ Cancellation, SocketAccept, SocketClose, SocketConnect, SocketOpen, SocketStreamReading, diff --git a/crates/server/tests/support/mod.rs b/crates/server/tests/support/mod.rs index 7294888e..c4d7798e 100644 --- a/crates/server/tests/support/mod.rs +++ b/crates/server/tests/support/mod.rs @@ -2,10 +2,8 @@ // Copyright, 2026, by Samuel Williams. #![allow(dead_code)] -use base_http_server::ServerContext; - use base_http_fixtures::raw; -use base_http_server::{Error, Handler}; +use base_http_server::{Error, Handler, ServerContext}; use base_scheduler::{ Cancellation, SocketAccept, SocketBind, SocketClose, SocketListen, SocketLocalAddress, SocketOpen, SocketType, diff --git a/crates/server/tests/tls.rs b/crates/server/tests/tls.rs index 0c203810..7c2deab8 100644 --- a/crates/server/tests/tls.rs +++ b/crates/server/tests/tls.rs @@ -2,15 +2,13 @@ // Copyright, 2026, by Samuel Williams. #![cfg(feature = "rustls")] -use base_http_server::ServerContext; - use base_endpoint::tls::{TlsAcceptor, rustls::RustlsAcceptor}; use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; use base_http_protocol::{HttpProtocols, NegotiationError}; -use base_http_server::{Error, Handler, Options}; +use base_http_server::{Error, Handler, Options, ServerContext}; use base_scheduler::{Cancellation, SocketAccept, SocketClose}; use futures_lite::future::block_on; use rustls::{ diff --git a/crates/server/tests/transport_faults.rs b/crates/server/tests/transport_faults.rs index fa131459..a3f8a16e 100644 --- a/crates/server/tests/transport_faults.rs +++ b/crates/server/tests/transport_faults.rs @@ -6,8 +6,7 @@ use base_http::{ Request, Response, Status, body::{BufferedBody, ReadableBody}, }; -use base_http_server::{Error, Handler}; -use base_http_server::{HandlerContext, ServerContext}; +use base_http_server::{Error, Handler, HandlerContext, ServerContext}; use base_scheduler::{ BufferLease, BufferPoolOptions, BufferPooling, Cancellation, Cancelled, Clock, HeapBufferPool, IoBuf, IoBufSequence, IoBufSequenceMut, OperationError, OperationResult, SocketAccept,