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: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Notable changes are recorded from 0.5.0 onward.

### Breaking Changes

- The accept functions of the transports with a request path return that path before the connection's halves, for example `/prices`: `WebSocketTransport::accept` and `accept_tls`, `SyncWebSocketTransport::accept`, `HttpTransport::accept` and `accept_tls`, and `WebTransport::accept`. The `Transport` trait implementations still return the halves only, because the trait covers transports without a request path.
- Renamed `TableStreamDecoder` to `TableDecoder`. Decoding is now synchronous, with readers responsible for I/O. `TableDecoder::new` no longer accepts a source. Readers fill `spare_uninit`, commit bytes with `advance` and call `decode_next`, which returns `TableDecodeResult`.
- Moved the `Stream` implementation and `read_keyed` from the decoder to `TableReader`, which owns the `AsyncRead` source.
- Renamed `TableStreamEncoder` to `TableEncoder`.
Expand Down
2 changes: 1 addition & 1 deletion rust/src/models/readers/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl HttpTableReader {
listener: &TcpListener,
limits: Option<DecodeLimits>,
) -> io::Result<Self> {
let (recv_read, send_write) = HttpTransport::accept(listener).await?;
let (_path, recv_read, send_write) = HttpTransport::accept(listener).await?;
Self::from_exchange(recv_read, send_write, limits).await
}

Expand Down
2 changes: 1 addition & 1 deletion rust/src/models/readers/sync_websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl SyncWebSocketTableReader {
/// e.g. via `SyncWebSocketTransport::bind`, and holds it across
/// connections. Uses `IPCMessageProtocol::Stream`.
pub fn accept(listener: &TcpListener, limits: Option<DecodeLimits>) -> io::Result<Self> {
let (read_half, write_half) = SyncWebSocketTransport::accept(listener)?;
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(listener)?;
Ok(Self::from_halves(
read_half,
write_half,
Expand Down
2 changes: 1 addition & 1 deletion rust/src/models/readers/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl WebSocketTableReader {
listener: &TcpListener,
limits: Option<DecodeLimits>,
) -> io::Result<Self> {
let (read_half, write_half) = WebSocketTransport::accept(listener).await?;
let (_path, read_half, write_half) = WebSocketTransport::accept(listener).await?;
Ok(Self::from_halves(
read_half,
write_half,
Expand Down
30 changes: 19 additions & 11 deletions rust/src/models/transports/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,22 +93,25 @@ impl HttpTransport {
}

/// Accept the next inbound connection, take its first request,
/// answer with response headers, and return the exchange's byte
/// halves.
pub async fn accept(listener: &TcpListener) -> io::Result<(H2RecvRead, H2SendWrite)> {
/// answer with response headers, and return the request path with the
/// exchange's byte halves.
///
/// The path is returned as written in the request, for example `/feed`.
pub async fn accept(listener: &TcpListener) -> io::Result<(String, H2RecvRead, H2SendWrite)> {
let (tcp, _) = listener.accept().await?;
accept_exchange(tcp).await
}

/// Accept the next inbound connection, terminate TLS with the
/// supplied `rustls::ServerConfig`, take the exchange's first
/// request, answer with response headers, and return its byte
/// halves. The config advertises the `h2` application protocol.
/// request, answer with response headers, and return the request path
/// with its byte halves. The config advertises the `h2` application
/// protocol.
#[cfg(feature = "tls")]
pub async fn accept_tls(
listener: &TcpListener,
config: std::sync::Arc<tokio_rustls::rustls::ServerConfig>,
) -> io::Result<(H2RecvRead, H2SendWrite)> {
) -> io::Result<(String, H2RecvRead, H2SendWrite)> {
let (tcp, _) = listener.accept().await?;
let acceptor = tokio_rustls::TlsAcceptor::from(config);
let tls = acceptor.accept(tcp).await?;
Expand Down Expand Up @@ -147,9 +150,9 @@ where
}

/// Run the h2 server handshake on an established stream, take its
/// first request, answer with response headers, and return the byte
/// halves.
async fn accept_exchange<T>(io_stream: T) -> io::Result<(H2RecvRead, H2SendWrite)>
/// first request, answer with response headers, and return the request
/// path with the byte halves.
async fn accept_exchange<T>(io_stream: T) -> io::Result<(String, H2RecvRead, H2SendWrite)>
where
T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
Expand All @@ -170,6 +173,7 @@ where
)
})?
.map_err(io::Error::other)?;
let path = req.uri().path().to_string();
let recv = req.into_body();

let response = Response::builder()
Expand All @@ -185,7 +189,7 @@ where
// until the peer closes.
tokio::spawn(async move { while conn.accept().await.is_some() {} });

Ok((H2RecvRead::new(recv), H2SendWrite::new(send_stream)))
Ok((path, H2RecvRead::new(recv), H2SendWrite::new(send_stream)))
}

impl Transport for HttpTransport {
Expand All @@ -202,7 +206,11 @@ impl Transport for HttpTransport {
HttpTransport::bind(endpoint).await
}

/// The `Transport` contract returns the halves only, because most
/// transports don't have a request path. Callers that route by path use
/// [`HttpTransport::accept`].
async fn accept(listener: &TcpListener) -> io::Result<(H2RecvRead, H2SendWrite)> {
HttpTransport::accept(listener).await
let (_path, recv_read, send_write) = HttpTransport::accept(listener).await?;
Ok((recv_read, send_write))
}
}
19 changes: 14 additions & 5 deletions rust/src/models/transports/sync_websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};

use tokio_tungstenite::tungstenite::accept;
use tokio_tungstenite::tungstenite::accept_hdr;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};

use crate::models::transports::websocket::{
check_handshake_response, handshake_closed, handshake_request, handshake_response_complete,
Expand Down Expand Up @@ -64,13 +65,21 @@ impl SyncWebSocketTransport {
}

/// Accept the next inbound connection, run the server upgrade
/// handshake, and return the post-handshake read and write halves.
pub fn accept(listener: &TcpListener) -> io::Result<(TcpStream, TcpStream)> {
/// handshake, and return the request path with the post-handshake read
/// and write halves.
///
/// The path is returned as written in the request, for example `/prices`.
pub fn accept(listener: &TcpListener) -> io::Result<(String, TcpStream, TcpStream)> {
let (tcp, _) = listener.accept()?;
let ws_stream = accept(tcp).map_err(|e| io::Error::other(e.to_string()))?;
let mut path = String::new();
let ws_stream = accept_hdr(tcp, |request: &Request, response: Response| {
path = request.uri().path().to_string();
Ok(response)
})
.map_err(|e| io::Error::other(e.to_string()))?;
let tcp = ws_stream.into_inner();
let write_half = tcp.try_clone()?;
Ok((tcp, write_half))
Ok((path, tcp, write_half))
}
}

Expand Down
41 changes: 32 additions & 9 deletions rust/src/models/transports/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ use std::str;

use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::handshake::client::generate_key;
use tokio_tungstenite::tungstenite::handshake::derive_accept_key;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};

use crate::traits::transport::Transport;

Expand Down Expand Up @@ -89,31 +90,49 @@ impl WebSocketTransport {
}

/// Accept the next inbound connection, run the server upgrade
/// handshake, and return the post-handshake halves.
/// handshake, and return the request path with the post-handshake halves.
///
/// The path is returned as written in the request, for example `/prices`.
pub async fn accept(
listener: &TcpListener,
) -> io::Result<(ReadHalf<TcpStream>, WriteHalf<TcpStream>)> {
) -> io::Result<(String, ReadHalf<TcpStream>, WriteHalf<TcpStream>)> {
let (tcp, _) = listener.accept().await?;
let ws_stream = accept_async(tcp).await.map_err(io::Error::other)?;
Ok(tokio::io::split(ws_stream.into_inner()))
let mut path = String::new();
let ws_stream = accept_hdr_async(tcp, |request: &Request, response: Response| {
path = request.uri().path().to_string();
Ok(response)
})
.await
.map_err(io::Error::other)?;
let (read_half, write_half) = tokio::io::split(ws_stream.into_inner());
Ok((path, read_half, write_half))
}

/// Accept the next inbound connection, terminate TLS with the
/// supplied `rustls::ServerConfig`, run the server upgrade
/// handshake over it, and return the post-handshake halves.
/// handshake over it, and return the request path with the
/// post-handshake halves.
#[cfg(feature = "tls")]
pub async fn accept_tls(
listener: &TcpListener,
config: std::sync::Arc<tokio_rustls::rustls::ServerConfig>,
) -> io::Result<(
String,
ReadHalf<tokio_rustls::server::TlsStream<TcpStream>>,
WriteHalf<tokio_rustls::server::TlsStream<TcpStream>>,
)> {
let (tcp, _) = listener.accept().await?;
let acceptor = tokio_rustls::TlsAcceptor::from(config);
let tls = acceptor.accept(tcp).await?;
let ws_stream = accept_async(tls).await.map_err(io::Error::other)?;
Ok(tokio::io::split(ws_stream.into_inner()))
let mut path = String::new();
let ws_stream = accept_hdr_async(tls, |request: &Request, response: Response| {
path = request.uri().path().to_string();
Ok(response)
})
.await
.map_err(io::Error::other)?;
let (read_half, write_half) = tokio::io::split(ws_stream.into_inner());
Ok((path, read_half, write_half))
}
}

Expand Down Expand Up @@ -252,7 +271,11 @@ impl Transport for WebSocketTransport {
WebSocketTransport::bind(endpoint).await
}

/// The `Transport` contract returns the halves only, because most
/// transports don't have a request path. Callers that route by path use
/// [`WebSocketTransport::accept`].
async fn accept(listener: &TcpListener) -> io::Result<(Self::Read, Self::Write)> {
WebSocketTransport::accept(listener).await
let (_path, read_half, write_half) = WebSocketTransport::accept(listener).await?;
Ok((read_half, write_half))
}
}
11 changes: 8 additions & 3 deletions rust/src/models/transports/webtransport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,21 @@ impl WebTransport {
}

/// Accept the next inbound session, take its first bidirectional
/// stream, and return the stream's halves.
pub async fn accept(listener: &Endpoint<Server>) -> io::Result<(RecvStream, SendStream)> {
/// stream, and return the session's request path with the stream's
/// halves.
///
/// The path is returned as written in the session's CONNECT request, for
/// example `/feed`.
pub async fn accept(listener: &Endpoint<Server>) -> io::Result<(String, RecvStream, SendStream)> {
let session_request = listener.accept().await.await.map_err(io::Error::other)?;
let path = session_request.path().to_string();
let conn = session_request.accept().await.map_err(io::Error::other)?;
let (send, recv) = conn.accept_bi().await.map_err(io::Error::other)?;
// The session dies when every handle drops, so a task holds
// one until the peers close it or it idles out.
tokio::spawn(async move {
conn.closed().await;
});
Ok((recv, send))
Ok((path, recv, send))
}
}
2 changes: 1 addition & 1 deletion rust/src/models/writers/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl HttpTableWriter {
schema: Vec<Field>,
compression: Option<Compression>,
) -> io::Result<Self> {
let (recv_read, send_write) = HttpTransport::accept(listener).await?;
let (_path, recv_read, send_write) = HttpTransport::accept(listener).await?;
Self::from_exchange(recv_read, send_write, schema, compression)
}

Expand Down
2 changes: 1 addition & 1 deletion rust/src/models/writers/sync_websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl SyncWebSocketTableWriter {
schema: Vec<Field>,
compression: Option<Compression>,
) -> io::Result<Self> {
let (read_half, write_half) = SyncWebSocketTransport::accept(listener)?;
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(listener)?;
Ok(Self::from_halves(read_half, write_half, schema, compression))
}

Expand Down
2 changes: 1 addition & 1 deletion rust/src/models/writers/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl WebSocketTableWriter {
schema: Vec<Field>,
compression: Option<Compression>,
) -> io::Result<Self> {
let (read_half, write_half) = WebSocketTransport::accept(listener).await?;
let (_path, read_half, write_half) = WebSocketTransport::accept(listener).await?;
Self::from_halves(read_half, write_half, schema, compression)
}

Expand Down
18 changes: 14 additions & 4 deletions rust/tests/sync_websocket_roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ fn capture_messages(

let mut ws_read = match reader_listener {
Some(listener) => {
let (read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (shared, _ws_write) = SyncWsWrite::new(write_half);
SyncWsRead::new(read_half, shared)
}
Expand Down Expand Up @@ -520,7 +520,7 @@ fn sync_transport_reads_text_and_binary_messages_from_a_connecting_peer() {
pongs
});

let (read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (shared, ws_write) = SyncWsWrite::new(write_half);
let mut ws_read = SyncWsRead::new(read_half, shared);
let mut buf = Vec::new();
Expand All @@ -539,6 +539,16 @@ fn sync_transport_reads_text_and_binary_messages_from_a_connecting_peer() {
assert_eq!(peer.join().unwrap(), vec![vec![7u8, 8, 9]]);
}

#[test]
fn sync_accept_returns_the_request_path() {
let (listener, url) = bind_local();
let peer = thread::spawn(move || SyncWebSocketTransport::connect(&format!("{url}/prices")).unwrap());

let (path, _read_half, _write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
assert_eq!(path, "/prices");
drop(peer.join().unwrap());
}

#[test]
fn sync_transport_reads_messages_from_an_accepting_peer() {
let (listener, url) = bind_local();
Expand Down Expand Up @@ -595,7 +605,7 @@ fn fragmented_messages_are_joined_across_interleaved_pings() {
_read_half
});

let (read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (shared, _ws_write) = SyncWsWrite::new(write_half);
let mut ws_read = SyncWsRead::new(read_half, shared);
let mut buf = Vec::new();
Expand Down Expand Up @@ -623,7 +633,7 @@ fn messages_beyond_max_len_are_rejected() {
_read_half
});

let (read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (_path, read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap();
let (shared, _ws_write) = SyncWsWrite::new(write_half);
let mut ws_read = SyncWsRead::new(read_half, shared);
let mut buf = Vec::new();
Expand Down
Loading
Loading