Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion benchmarks/client/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion benchmarks/hello/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion benchmarks/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ where
ready(&listener)?;
let listener = scheduler.register_listener(listener)?;
let cancellation = Cancellation::never();
let options = base_http1::Options::default();
let options = base_http_server::Options::default();
let mut connections = FuturesUnordered::new();
loop {
if connections.len() == MAX_CONNECTIONS {
Expand Down
117 changes: 74 additions & 43 deletions crates/client/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use base_endpoint::{
AddressEndpoint, ConnectEndpoint,
stream::{ReadableStream, WritableStream},
};
use base_http_protocol::HttpProtocol;
use base_http1::{RequestWriter, ResponseReader};
use base_pool::{Admission, MultiplexBuildPermit, MultiplexResource};
use base_scheduler::{
Expand All @@ -26,24 +27,24 @@ use std::sync::{
};

struct Inner<'scope> {
direct: Mutex<Option<Arc<dyn DirectConnection<'scope> + 'scope>>>,
selected: Mutex<Option<ClientConnection<'scope>>>,
changed: Event,
stop: Cancellation,
result: Mutex<Option<Result<(), Error>>>,
}

/// An established HTTP/1 session retaining its transport and codec buffers.
/// Requests take and return its directions in the calling task; supervised
/// work handles construction and retirement.
/// An endpoint pool's entry for one established connection, holding the
/// connection the selected protocol constructed. Requests use it in the
/// calling task; supervised work handles construction and retirement.
#[derive(Clone)]
pub struct Connection<'scope> {
pub(crate) struct Connection<'scope> {
inner: Arc<Inner<'scope>>,
}
impl<'scope> Connection<'scope> {
fn new() -> Self {
Self {
inner: Arc::new(Inner {
direct: Mutex::new(None),
selected: Mutex::new(None),
changed: Event::new(),
stop: Cancellation::new(),
result: Mutex::new(None),
Expand All @@ -53,21 +54,21 @@ impl<'scope> Connection<'scope> {
pub(crate) fn clone_handle(&self) -> Self {
self.clone()
}
pub(crate) fn open(&self, opening: Open<'scope>) -> Opening<'scope> {
// Admission is published only after the session installs its direct state, which it never removes.
let direct = lock(&self.inner.direct)
/// The selected connection. Admission is published only after the session
/// installs it, which it never removes.
fn selected(&self) -> ClientConnection<'scope> {
lock(&self.inner.selected)
.clone()
.expect("an admitted connection has direct state");
direct.open(opening)
.expect("an admitted connection has a selected protocol connection")
}
pub(crate) fn open(&self, opening: Open<'scope>) -> Opening<'scope> {
self.selected().open(opening)
}
/// Check an admitted idle connection before its exchange begins. A failed
/// probe retires the registration; the caller completes its use and
/// acquires again, since no request bytes have been sent.
pub(crate) fn probe(&self) -> bool {
let direct = lock(&self.inner.direct)
.clone()
.expect("an admitted connection has direct state");
direct.probe()
self.selected().probe()
}
/// Wait until the connection is stopped or its lifetime ends.
async fn stopped(&self, lifetime: &Cancellation) {
Expand Down Expand Up @@ -165,23 +166,28 @@ pub(crate) async fn run<'scope, S>(
return transport
.with_duplex(scheduler, &lifetime, |reader, writer| async {
let protocol = options.protocols.negotiated(selected.as_deref())?;
let (input, output) = protocol
.client(reader, writer, options.http1.clone())
.expect("Client::new validated the HTTP/1 options");
session(
input,
output,
&mut owner,
&mut build,
&mut ready,
&cancellation,
&lifetime,
queue.clone(),
)
.await
match protocol {
HttpProtocol::Http1 => {
let input = ResponseReader::new(reader, options.http1.clone())
.expect("Client::new validated the HTTP/1 options");
session(
input,
RequestWriter::new(writer),
&mut owner,
&mut build,
&mut ready,
&cancellation,
&lifetime,
queue.clone(),
)
.await
}
}
})
.await;
}
// A plain TCP connection negotiates nothing, so select its engine before connecting.
let protocol = options.protocols.plaintext()?;
let socket = endpoint_transport
.connect(scheduler, &cancellation)
.await
Expand All @@ -195,13 +201,13 @@ pub(crate) async fn run<'scope, S>(
return Err(Error::from(error));
}
};
Ok::<_, Error>(
options
.protocols
.plaintext()
.client(reader, writer, options.http1.clone())
.expect("Client::new validated the HTTP/1 options"),
)
Ok::<_, Error>(match protocol {
HttpProtocol::Http1 => (
ResponseReader::new(reader, options.http1.clone())
.expect("Client::new validated the HTTP/1 options"),
RequestWriter::new(writer),
),
})
}
.await;
let result = match initialized {
Expand Down Expand Up @@ -266,9 +272,34 @@ where
}
}

// A connection retains its typed HTTP buffers and transport directions. Only
// an admitted exchange may take them; short locks protect transfer, never I/O.
trait DirectConnection<'scope>: Send + Sync {
/// One outbound connection speaking the selected protocol, as Async::HTTP's
/// `Protocol::HTTP1::Client` is: it opens each exchange on the connection and
/// checks an idle connection before reuse. HTTP/1's session publishes its fixed
/// admission of one exchange on the pool registration; an engine whose
/// admission changes, such as HTTP/2's stream limits, will publish it here. There is one variant for each engine compiled in, on which
/// the client dispatches. Each variant erases its transport's types, which
/// depend on the scheduler and on whether the connection is encrypted.
#[derive(Clone)]
enum ClientConnection<'scope> {
Http1(Arc<dyn Http1Exchanges<'scope> + 'scope>),
}
impl<'scope> ClientConnection<'scope> {
fn open(self, opening: Open<'scope>) -> Opening<'scope> {
match self {
Self::Http1(connection) => connection.open(opening),
}
}
fn probe(&self) -> bool {
match self {
Self::Http1(connection) => connection.probe(),
}
}
}

// An HTTP/1 connection retains its typed buffers and transport directions.
// Only an admitted exchange may take them; short locks protect transfer, never
// I/O.
trait Http1Exchanges<'scope>: Send + Sync {
fn open(self: Arc<Self>, opening: Open<'scope>) -> Opening<'scope>;
fn probe(&self) -> bool;
}
Expand Down Expand Up @@ -324,7 +355,7 @@ impl<R: ReadableStream, W: WritableStream> Http1Connection<'_, R, W> {
Ok(())
}
}
impl<'scope, R: ReadableStream + 'scope, W: WritableStream + 'scope> DirectConnection<'scope>
impl<'scope, R: ReadableStream + 'scope, W: WritableStream + 'scope> Http1Exchanges<'scope>
for Http1Connection<'scope, R, W>
{
fn open(self: Arc<Self>, opening: Open<'scope>) -> Opening<'scope> {
Expand Down Expand Up @@ -459,8 +490,8 @@ where
let _ = output.close().await;
return Err(Error::Cancelled);
}
// Set the direct interface before publication; no admitted caller can see
// a connection without its codec storage.
// Install the selected connection before publication; no admitted caller
// can see a connection without its codec storage.
// The pool closes only once the driver's cancellation, which construction
// inherits from its waiting request, has been cancelled, and that was
// checked above with no wait since, so the pool is still open.
Expand All @@ -481,7 +512,7 @@ where
queue,
open: crate::writable::factory(),
});
*lock(&owner.connection.inner.direct) = Some(state.clone());
*lock(&owner.connection.inner.selected) = Some(ClientConnection::Http1(state.clone()));
// A registration that is already draining publishes no admission; its retirement stops the session below.
state.registration.update(Admission::concurrent(1));
// Construction runs one session, and reports readiness itself only if the session never does.
Expand Down
14 changes: 10 additions & 4 deletions crates/client/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ pub enum Error {
InvalidOptions,
Unsupported(&'static str),
Pool(base_pool::Error),
Protocol(Arc<base_http1::Error>),
/// The connection's engine failed, such as on a malformed response.
Protocol(Arc<base_http_protocol::ProtocolError>),
Io(Arc<io::Error>),
Body(base_http::body::BodyError),
}
Expand Down Expand Up @@ -91,6 +92,11 @@ impl From<base_pool::Error> for Error {
}
}
}
impl Error {
fn protocol(error: base_http1::Error) -> Self {
Self::Protocol(Arc::new(error.into()))
}
}
impl From<base_http1::Error> for Error {
fn from(error: base_http1::Error) -> Self {
match error {
Expand All @@ -101,12 +107,12 @@ impl From<base_http1::Error> for Error {
Err(error) => match error.downcast::<base_http::InterimError<Self>>() {
Ok(error) => match *error {
base_http::InterimError::Handler(error) => error,
error => Self::Protocol(Arc::new(base_http1::Error::Body(Box::new(error)))),
error => Self::protocol(base_http1::Error::Body(Box::new(error))),
},
Err(error) => Self::Protocol(Arc::new(base_http1::Error::Body(error))),
Err(error) => Self::protocol(base_http1::Error::Body(error)),
},
},
error => Self::Protocol(Arc::new(error)),
error => Self::protocol(error),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ mod sink;
mod writable;
pub use writable::{PendingResponse, RequestBodyWriter, StreamingResponseBody, WritableRequest};

pub use connection::Connection;
use connection::Connection;
pub use driver::Driver;
pub use error::Error;

Expand Down
30 changes: 30 additions & 0 deletions crates/client/tests/client/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,33 @@ fn clients_report_their_endpoint() {
assert_eq!(endpoint.scheme(), "http");
});
}

#[test]
fn a_disabled_plaintext_engine_fails_calls_before_connecting() {
let scheduler = NativeScheduler::new().unwrap();
let options = Options {
protocols: base_http_protocol::HttpProtocols {
enabled: Vec::new(),
..Default::default()
},
..Default::default()
};
// Nothing listens on port 1, so connecting would fail; selection fails first.
let endpoint = Endpoint::new("127.0.0.1:1".parse().unwrap());
let (client, driver) = Client::new(&scheduler, endpoint, options).unwrap();
let never = base_scheduler::Cancellation::never();
let (driven, ()) =
futures_lite::future::block_on(futures_lite::future::zip(driver.run(&never), async {
let request =
base_http::Request::new(base_http::Method::GET, "/", base_http::body::EmptyBody);
let error = client.call(request, &never).await.err().unwrap();
assert!(matches!(error, Error::Negotiation(_)), "{error:?}");
assert_eq!(
chain(&error),
["HTTP application protocol \"http/1.1\" is not enabled"]
);
client.begin_close();
}));
driven.unwrap();
futures_lite::future::block_on(scheduler.shutdown());
}
6 changes: 5 additions & 1 deletion crates/client/tests/https.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ fn https_echo_reuses_connections_and_accepts_during_another_handshake() {
let endpoint = Endpoint::new(address).with_tls(client_config, "localhost");
assert_eq!(endpoint.scheme(), "https");
let options = Options {
protocols: base_http_protocol::HttpProtocols { require_alpn: true },
protocols: base_http_protocol::HttpProtocols {
require_alpn: true,
..Default::default()
},
..Options::default()
};
let (client, driver) = Client::new(&scheduler, endpoint, options).unwrap();
Expand Down Expand Up @@ -198,6 +201,7 @@ fn https_client_applies_missing_alpn_policy_before_pool_publication() {
let options = Options {
protocols: base_http_protocol::HttpProtocols {
require_alpn: required,
..Default::default()
},
..Options::default()
};
Expand Down
1 change: 0 additions & 1 deletion crates/protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@ readme = "readme.md"

[dependencies]
base-http1 = { version = "0.4.0", path = "../http1" }
base-endpoint = "0.3.0"
4 changes: 2 additions & 2 deletions crates/protocol/readme.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Base HTTP Protocol

Experimental protocol selection shared by the application client and server, following Async::HTTP's protocol factories. `HttpProtocols` supplies application-protocol offers and selects an enabled engine from explicit plaintext policy or an opaque negotiated identifier. `HttpProtocol` constructs the corresponding client/server codec pair.
Experimental protocol selection shared by the application client and server, following Async::HTTP's protocol factories. `HttpProtocols` lists the enabled engines in preference order, from which it supplies application-protocol offers, and selects an enabled engine from its `Plaintext` policy or an opaque negotiated identifier, so offers and selection always agree. `HttpProtocol` names the selected engine; the client and server each construct their connection for it, as Async::HTTP's `Protocol::HTTP1::Client` and `Server`, and dispatch on a closed enum with one variant for each engine compiled in. `ProtocolError` reports an engine's failure and names the engine.

The initial engine is HTTP/1, advertising `http/1.1`. Missing ALPN is accepted for older HTTPS peers unless `require_alpn` is enabled. An unknown negotiated identifier is always rejected. TLS configuration, handshakes, encryption and transport ownership remain outside this crate. `base-http1` only consumes plaintext stream capabilities.
The initial engine is HTTP/1, advertising `http/1.1`. Missing ALPN is accepted for older HTTPS peers unless `require_alpn` is enabled, and only when HTTP/1 is enabled. An unknown or disabled negotiated identifier is always rejected, and a plaintext policy whose engine is disabled refuses the connection. TLS configuration, handshakes, encryption and transport ownership remain outside this crate. `base-http1` only consumes plaintext stream capabilities.

HTTP/2 and QUIC/HTTP/3 are future engines. TCP and QUIC require distinct establishment paths; advertising `h3` over a TLS/TCP connection cannot select QUIC. The existing semantic `base_http::Protocol` describes application upgrades and is unrelated to this configuration.
Loading