From 9ecb360ac6c0b7ee9450b656bc203dc040fd791d Mon Sep 17 00:00:00 2001 From: Peter Bower <37089506+pbower@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:45:38 +0000 Subject: [PATCH 1/4] WebSocket, HTTP/2 and WebTransport listeners accept only connections to the path of their bound URL --- rust/README.md | 17 + rust/src/lib.rs | 4 + rust/src/models/readers/http.rs | 10 +- rust/src/models/readers/sync_websocket.rs | 12 +- rust/src/models/readers/websocket.rs | 9 +- rust/src/models/transports/http.rs | 225 ++++++- rust/src/models/transports/routing.rs | 353 ++++++++++ rust/src/models/transports/sync_websocket.rs | 168 ++++- rust/src/models/transports/websocket.rs | 264 +++++++- rust/src/models/transports/webtransport.rs | 150 ++++- rust/src/models/writers/http.rs | 10 +- rust/src/models/writers/sync_websocket.rs | 12 +- rust/src/models/writers/websocket.rs | 10 +- rust/tests/sync_websocket_roundtrip.rs | 202 +++++- rust/tests/transport_roundtrip.rs | 660 ++++++++++++++++++- 15 files changed, 1960 insertions(+), 146 deletions(-) create mode 100644 rust/src/models/transports/routing.rs diff --git a/rust/README.md b/rust/README.md index 8234e56..56eaea0 100644 --- a/rust/README.md +++ b/rust/README.md @@ -145,6 +145,23 @@ writer.write_table(batch_1)?; writer.finish()?; ``` +**URL endpoints** + +WebSocket, HTTP/2 and WebTransport endpoints are URLs, and the path is part of the endpoint. `bind` returns a listener for the URL's path, and listeners for several paths on one scheme, host and port share a single socket in the process. Each listener's `accept` returns only the connections made to its own path, and connections to an unbound path are refused with status `404 Not Found`. Binding a URL that is already bound returns `AddrInUse`, and dropping a listener unbinds its path. + +```rust +use lightstream::models::readers::websocket::WebSocketTableReader; +use lightstream::models::transports::websocket::WebSocketTransport; + +let prices = WebSocketTransport::bind("ws://0.0.0.0:9910/prices").await?; +let trades = WebSocketTransport::bind("ws://0.0.0.0:9910/trades").await?; + +// Receives only the connections made to `/prices`. +let reader = WebSocketTableReader::accept(&prices, None).await?; +``` + +TLS is established before the path is known, therefore endpoints on one host and port share a single TLS identity. + **Memory-mapped Arrow IPC** The mmap reader is very fast. Warm mmap rivals standalone RAM speed, as it gets out the way. diff --git a/rust/src/lib.rs b/rust/src/lib.rs index ee344dd..39fba6b 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -479,6 +479,10 @@ pub mod models { /// WebTransport Transport. #[cfg(feature = "webtransport")] pub mod webtransport; + + /// Path routing for the transports with URL endpoints. + #[cfg(any(feature = "websocket", feature = "http", feature = "webtransport"))] + pub(crate) mod routing; } /// Stream adapters and sources. diff --git a/rust/src/models/readers/http.rs b/rust/src/models/readers/http.rs index 16d4d3f..1695ee8 100644 --- a/rust/src/models/readers/http.rs +++ b/rust/src/models/readers/http.rs @@ -40,13 +40,13 @@ use futures_core::Stream; use http::{Request, Uri}; use minarrow::{Field, SuperTable, Table, Vec64}; use tokio::io::AsyncWriteExt; -use tokio::net::{TcpListener, TcpStream}; +use tokio::net::TcpStream; use crate::enums::{BufferChunkSize, IPCMessageProtocol}; use crate::models::readers::ipc::table::TableReader; use crate::models::decoders::limits::DecodeLimits; use crate::models::streams::http::{H2RecvRead, H2SendWrite, HttpByteStream}; -use crate::models::transports::http::HttpTransport; +use crate::models::transports::http::{HttpListener, HttpTransport}; use crate::traits::transport_reader::IPCTransportReader; /// Async Arrow IPC reader over an HTTP/2 GET response body. @@ -132,8 +132,8 @@ impl HttpTableReader { Self { inner } } - /// Accept the next inbound exchange and return a table reader over - /// its request body. + /// Accept the next inbound exchange for the listener's path and return + /// a table reader over its request body. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `HttpTransport::bind`, and holds it across connections. @@ -141,7 +141,7 @@ impl HttpTableReader { /// ended with a clean h2 half-close and the exchange continues on /// the request body alone. pub async fn accept( - listener: &TcpListener, + listener: &HttpListener, limits: Option, ) -> io::Result { let (recv_read, send_write) = HttpTransport::accept(listener).await?; diff --git a/rust/src/models/readers/sync_websocket.rs b/rust/src/models/readers/sync_websocket.rs index 61a596e..f8c4777 100644 --- a/rust/src/models/readers/sync_websocket.rs +++ b/rust/src/models/readers/sync_websocket.rs @@ -40,7 +40,6 @@ //! [`SyncWsRead`]: crate::models::streams::sync_websocket::SyncWsRead use std::io::{self, Read, Write}; -use std::net::TcpListener; use std::sync::{Arc, Mutex}; use minarrow::{Field, SuperTable, Table, Vec64}; @@ -49,7 +48,7 @@ use crate::enums::{BufferChunkSize, IPCMessageProtocol}; use crate::models::decoders::limits::DecodeLimits; use crate::models::readers::ipc::sync_table::SyncTableReader; use crate::models::streams::sync_websocket::{SyncWsRead, SyncWsWrite}; -use crate::models::transports::sync_websocket::SyncWebSocketTransport; +use crate::models::transports::sync_websocket::{SyncWebSocketListener, SyncWebSocketTransport}; /// Read-side type of [`SyncWebSocketTableReader`]. Boxing the /// [`SyncWsRead`] lets every constructor return the same struct type for @@ -81,13 +80,16 @@ impl SyncWebSocketTableReader { )) } - /// Accept the next inbound connection, run the server upgrade - /// handshake, and return a table reader over it. + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and return a table reader over it. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `SyncWebSocketTransport::bind`, and holds it across /// connections. Uses `IPCMessageProtocol::Stream`. - pub fn accept(listener: &TcpListener, limits: Option) -> io::Result { + pub fn accept( + listener: &SyncWebSocketListener, + limits: Option, + ) -> io::Result { let (read_half, write_half) = SyncWebSocketTransport::accept(listener)?; Ok(Self::from_halves( read_half, diff --git a/rust/src/models/readers/websocket.rs b/rust/src/models/readers/websocket.rs index 921af9a..729a7df 100644 --- a/rust/src/models/readers/websocket.rs +++ b/rust/src/models/readers/websocket.rs @@ -49,13 +49,12 @@ use std::task::{Context, Poll}; use futures_core::Stream; use minarrow::{Field, SuperTable, Table, Vec64}; -use tokio::net::TcpListener; use crate::enums::{BufferChunkSize, IPCMessageProtocol}; use crate::models::readers::ipc::table::TableReader; use crate::models::decoders::limits::DecodeLimits; use crate::models::streams::websocket::{WsRead, WsWrite}; -use crate::models::transports::websocket::WebSocketTransport; +use crate::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use crate::traits::transport_reader::IPCTransportReader; /// Async Arrow IPC reader over a WebSocket connection. @@ -90,14 +89,14 @@ impl WebSocketTableReader { Ok(Self { inner }) } - /// Accept the next inbound connection, run the server upgrade - /// handshake, and return a table reader over it. + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and return a table reader over it. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `WebSocketTransport::bind`, and holds it across /// connections. Uses `IPCMessageProtocol::Stream`. pub async fn accept( - listener: &TcpListener, + listener: &WebSocketListener, limits: Option, ) -> io::Result { let (read_half, write_half) = WebSocketTransport::accept(listener).await?; diff --git a/rust/src/models/transports/http.rs b/rust/src/models/transports/http.rs index e3a6064..0ac9a1d 100644 --- a/rust/src/models/transports/http.rs +++ b/rust/src/models/transports/http.rs @@ -17,16 +17,30 @@ //! //! GET semantics for cross-ecosystem endpoints stay on //! [`HttpTableReader::get`](crate::models::readers::http::HttpTableReader::get). +//! +//! ## Listeners +//! +//! Each [`HttpListener`] is the endpoint of one URL path. +//! [`HttpTransport::bind`] binds the URL's scheme and authority as a socket +//! held in the process, and listeners for other paths on the same scheme +//! and authority share that socket. `accept` returns only the exchanges +//! that open with a request for the listener's own path. Requests for a +//! path that no listener in the process has bound are answered with status +//! `404 Not Found`. URLs without a path refer to the path `/`. use std::io; +use std::net::SocketAddr; +use std::sync::Arc; use bytes::Bytes; -use http::{Request, Response, Uri}; +use h2::server::SendResponse; +use http::{Request, Response, StatusCode, Uri}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpListener, TcpStream}; use crate::models::readers::http::host_port; use crate::models::streams::http::{H2RecvRead, H2SendWrite}; +use crate::models::transports::routing::{AcceptRouter, SocketKey, SocketRegistry}; use crate::traits::transport::Transport; /// Initial flow-control window each peer advertises during the h2 @@ -35,6 +49,82 @@ use crate::traits::transport::Transport; /// while 8 MiB lets a typical record batch land in one round-trip. const INITIAL_WINDOW: u32 = 8 * 1024 * 1024; +/// First request of an accepted connection, with its response handle. +type PendingRequest = (Request, SendResponse); + +/// Sockets bound by [`HttpTransport::bind`] in this process. +static SOCKETS: SocketRegistry = SocketRegistry::new(); + +/// Socket shared by the HTTP/2 listeners of one scheme and authority. +struct SharedSocket { + listener: TcpListener, + router: AcceptRouter, +} + +/// # HttpListener +/// +/// ## Description +/// - Accepting endpoint for one `http://` or `https://` URL, returned by +/// [`HttpTransport::bind`]. +/// - Accepts only the exchanges that open with a request for the URL's +/// path. URLs without a path refer to the path `/`. +/// - Listeners for different paths on the same scheme and authority share +/// one socket in the process. +/// +/// ## Structure +/// - `socket`: the socket shared by the listeners of the URL's scheme and +/// authority, with the paths bound on it. +/// - `path`: the URL path this listener accepts. +/// +/// ## Usage +/// - Pass to [`HttpTransport::accept`] or [`HttpTransport::accept_tls`], +/// or to the `accept` constructors of [`HttpTableReader`] and +/// [`HttpTableWriter`]. +/// - Hold the listener across connections to keep its path bound. +/// +/// ## Notes +/// - Binding a URL that is already bound in the process returns +/// `io::ErrorKind::AddrInUse`. +/// - Dropping the listener unbinds its path. Dropping the last listener on +/// an authority closes the socket. +/// - Requests for a path that no listener has bound are answered with +/// status `404 Not Found`. +/// +/// ## Example +/// ```rust,no_run +/// # async fn run() -> std::io::Result<()> { +/// use lightstream::models::readers::http::HttpTableReader; +/// use lightstream::models::transports::http::HttpTransport; +/// +/// let prices = HttpTransport::bind("http://127.0.0.1:9910/prices").await?; +/// let trades = HttpTransport::bind("http://127.0.0.1:9910/trades").await?; +/// +/// // Receives only the exchanges made to `/prices`. +/// let reader = HttpTableReader::accept(&prices, None).await?; +/// # drop((reader, trades)); +/// # Ok(()) } +/// ``` +/// +/// [`HttpTableReader`]: crate::models::readers::http::HttpTableReader +/// [`HttpTableWriter`]: crate::models::writers::http::HttpTableWriter +pub struct HttpListener { + socket: Arc, + path: String, +} + +impl HttpListener { + /// Returns the local address of the bound socket. + pub fn local_addr(&self) -> io::Result { + self.socket.listener.local_addr() + } +} + +impl Drop for HttpListener { + fn drop(&mut self) { + self.socket.router.unbind(&self.path); + } +} + /// HTTP/2 implementation of [`Transport`]. /// /// Establishes plaintext h2c exchanges. TLS entry points stay on the @@ -81,38 +171,91 @@ impl HttpTransport { connect_exchange(tls, uri).await } - /// Bind the URL's authority and return the listener. - pub async fn bind(url: &str) -> io::Result { + /// Bind the URL as an endpoint and return its listener. + /// + /// The first bind of a scheme and authority in the process binds its + /// socket, and later binds of other paths on it share that socket. + /// URLs with port 0 bind a new socket on a free port, reported by + /// [`HttpListener::local_addr`]. Returns `io::ErrorKind::AddrInUse` + /// for a URL that is already bound in the process. + pub async fn bind(url: &str) -> io::Result { let uri: Uri = url .parse() .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; let scheme = uri.scheme_str().unwrap_or("http"); let default_port = if scheme == "https" { 443 } else { 80 }; let (host, port) = host_port(&uri, scheme, default_port)?; - TcpListener::bind((host.as_str(), port)).await + let path = match uri.path() { + "" => "/", + path => path, + }; + let key = SocketKey::new(scheme, &host, port); + let socket = SOCKETS.open(key, || { + let std_listener = std::net::TcpListener::bind((host.as_str(), port))?; + std_listener.set_nonblocking(true)?; + let port = std_listener.local_addr()?.port(); + let listener = TcpListener::from_std(std_listener)?; + Ok(( + SharedSocket { + listener, + router: AcceptRouter::new(), + }, + port, + )) + })?; + socket.router.bind(path)?; + Ok(HttpListener { + socket, + path: path.to_string(), + }) } - /// 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)> { - let (tcp, _) = listener.accept().await?; - accept_exchange(tcp).await + /// Accept the next inbound connection that opens with a request for the + /// listener's path, answer with response headers, and return the + /// exchange's byte halves. + /// + /// Requests that arrive for other bound paths on the socket are held, + /// unanswered, for those paths' next `accept`. + pub async fn accept(listener: &HttpListener) -> io::Result<(H2RecvRead, H2SendWrite)> { + let socket = &*listener.socket; + let pending = socket + .router + .accept(&listener.path, || async move { + let (tcp, _) = socket.listener.accept().await?; + accept_request(tcp, &socket.router).await + }) + .await?; + answer_request(pending) } /// 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 for the listener's path, answer with response headers, + /// and return its byte halves. The config advertises the `h2` + /// application protocol. + /// + /// TLS is terminated before the request path is known. Endpoints that + /// share an authority therefore share its TLS identity, and requests + /// held for other bound paths have completed TLS with `config`. #[cfg(feature = "tls")] pub async fn accept_tls( - listener: &TcpListener, + listener: &HttpListener, config: std::sync::Arc, ) -> io::Result<(H2RecvRead, H2SendWrite)> { - let (tcp, _) = listener.accept().await?; + let socket = &*listener.socket; let acceptor = tokio_rustls::TlsAcceptor::from(config); - let tls = acceptor.accept(tcp).await?; - accept_exchange(tls).await + let pending = socket + .router + .accept(&listener.path, || { + let acceptor = acceptor.clone(); + async move { + let (tcp, _) = socket.listener.accept().await?; + let tls = acceptor.accept(tcp).await?; + accept_request(tls, &socket.router).await + } + }) + .await?; + answer_request(pending) } } @@ -147,9 +290,15 @@ 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(io_stream: T) -> io::Result<(H2RecvRead, H2SendWrite)> +/// first request, and return the request path with the request and its +/// response handle. +/// +/// Returns `None` for a request to a path that no listener has bound, +/// after answering it with status `404 Not Found`. +async fn accept_request( + io_stream: T, + router: &AcceptRouter, +) -> io::Result> where T: AsyncRead + AsyncWrite + Send + Unpin + 'static, { @@ -170,8 +319,32 @@ where ) })? .map_err(io::Error::other)?; - let recv = req.into_body(); + // The h2 Connection is the I/O driver for all in-flight + // streams. Polling accept() in a loop drives the connection + // until the peer closes. + tokio::spawn(async move { while conn.accept().await.is_some() {} }); + + let path = req.uri().path().to_string(); + if !router.is_bound(&path) { + let refusal = Response::builder() + .status(StatusCode::NOT_FOUND) + .body(()) + .map_err(io::Error::other)?; + respond + .send_response(refusal, true) + .map_err(io::Error::other)?; + return Ok(None); + } + Ok(Some((path, (req, respond)))) +} + +/// Answer an accepted request with response headers and return the +/// exchange's byte halves. +fn answer_request( + (req, mut respond): PendingRequest, +) -> io::Result<(H2RecvRead, H2SendWrite)> { + let recv = req.into_body(); let response = Response::builder() .status(200) .body(()) @@ -179,18 +352,12 @@ where let send_stream = respond .send_response(response, false) .map_err(io::Error::other)?; - - // The h2 Connection is the I/O driver for all in-flight - // streams. Polling accept() in a loop drives the connection - // until the peer closes. - tokio::spawn(async move { while conn.accept().await.is_some() {} }); - Ok((H2RecvRead::new(recv), H2SendWrite::new(send_stream))) } impl Transport for HttpTransport { type Endpoint = str; - type Listener = TcpListener; + type Listener = HttpListener; type Read = H2RecvRead; type Write = H2SendWrite; @@ -198,11 +365,11 @@ impl Transport for HttpTransport { HttpTransport::connect(endpoint).await } - async fn bind(endpoint: &str) -> io::Result { + async fn bind(endpoint: &str) -> io::Result { HttpTransport::bind(endpoint).await } - async fn accept(listener: &TcpListener) -> io::Result<(H2RecvRead, H2SendWrite)> { + async fn accept(listener: &HttpListener) -> io::Result<(H2RecvRead, H2SendWrite)> { HttpTransport::accept(listener).await } } diff --git a/rust/src/models/transports/routing.rs b/rust/src/models/transports/routing.rs new file mode 100644 index 0000000..295f407 --- /dev/null +++ b/rust/src/models/transports/routing.rs @@ -0,0 +1,353 @@ +// Copyright Peter G. Bower 2025-2026. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! # Path routing +//! +//! Shared listener state for the transports with URL endpoints, i.e. +//! WebSocket, HTTP/2 and WebTransport. +//! +//! ## Context +//! +//! An endpoint such as `ws://host:9910/prices` is one path on the socket +//! bound to the URL's scheme and authority. Listeners for different paths +//! on one authority share that socket. Each transport holds a +//! [`SocketRegistry`] of its bound sockets for the life of the process, +//! keyed by [`SocketKey`], and each socket records its bound paths in an +//! [`AcceptRouter`] or, for the blocking WebSocket transport, a +//! [`SyncAcceptRouter`]. +//! +//! ## Details +//! +//! - Accepting calls drive the shared socket themselves, without a +//! background task or thread. One call at a time accepts from the socket +//! and reads the request path of each connection. Connections for the +//! calling listener's path are returned, connections for another bound +//! path are queued until that path's next accept, and connections for an +//! unbound path are refused. +//! - Registry entries are weak references. Sockets stay open while at least +//! one listener holds them, and close with the last one. +//! - The async router waits through `tokio::sync::Notify` and the blocking +//! router through `std::sync::Condvar`. Both keep their paths and queued +//! connections in the same `PathQueues` state. + +use std::collections::{HashMap, VecDeque}; +use std::future::Future; +use std::io; +use std::pin::pin; +#[cfg(feature = "websocket")] +use std::sync::Condvar; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak}; + +use tokio::sync::Notify; + +/// Identifies a bound socket by URL scheme, host and port. +/// +/// The scheme separates sockets for different schemes on one port, for +/// example `ws` and `wss`, into distinct bindings. +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct SocketKey { + scheme: String, + host: String, + port: u16, +} + +impl SocketKey { + /// Builds the key for a scheme, host and port. + pub(crate) fn new(scheme: &str, host: &str, port: u16) -> Self { + Self { + scheme: scheme.to_string(), + host: host.to_string(), + port, + } + } + + /// Builds the key for a scheme and an authority in `host:port` form. + /// + /// Returns `io::ErrorKind::InvalidInput` for an authority without a + /// numeric port. + #[cfg(any(feature = "websocket", feature = "webtransport"))] + pub(crate) fn from_authority(scheme: &str, authority: &str) -> io::Result { + let (host, port) = authority + .rsplit_once(':') + .and_then(|(host, port)| Some((host, port.parse::().ok()?))) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("endpoint authority '{authority}' requires a port"), + ) + })?; + Ok(Self::new(scheme, host, port)) + } +} + +/// Process-held record of the sockets one transport has bound. +/// +/// Entries are weak references. A socket stays open while a listener +/// holds it and closes when the last listener is dropped. +pub(crate) struct SocketRegistry { + sockets: OnceLock>>>, +} + +impl SocketRegistry { + /// Constructs an empty registry for use in a `static`. + pub(crate) const fn new() -> Self { + Self { + sockets: OnceLock::new(), + } + } + + /// Returns the open socket for `key`, opening it with `open` when the + /// process holds none. + /// + /// `open` returns the socket with the port it bound. That port replaces + /// port 0 in the recorded key, ensuring that later binds of the bound + /// port share the socket. + pub(crate) fn open( + &self, + key: SocketKey, + open: impl FnOnce() -> io::Result<(S, u16)>, + ) -> io::Result> { + let mut sockets = self + .sockets + .get_or_init(|| Mutex::new(HashMap::new())) + .lock() + .unwrap_or_else(|e| e.into_inner()); + sockets.retain(|_, socket| socket.strong_count() > 0); + if key.port != 0 { + if let Some(socket) = sockets.get(&key).and_then(Weak::upgrade) { + return Ok(socket); + } + } + let (socket, port) = open()?; + let socket = Arc::new(socket); + sockets.insert(SocketKey { port, ..key }, Arc::downgrade(&socket)); + Ok(socket) + } +} + +/// Bound paths of one socket, with the connections accepted for each path +/// and not yet returned. +struct PathQueues { + queues: HashMap>, + /// Set while an accepting call is accepting from the socket. + accepting: bool, +} + +impl PathQueues { + fn new() -> Self { + Self { + queues: HashMap::new(), + accepting: false, + } + } + + /// Binds `path`, returning `io::ErrorKind::AddrInUse` when it is + /// already bound. + fn bind(&mut self, path: &str) -> io::Result<()> { + if self.queues.contains_key(path) { + return Err(io::Error::new( + io::ErrorKind::AddrInUse, + format!("endpoint path '{path}' is already bound"), + )); + } + self.queues.insert(path.to_string(), VecDeque::new()); + Ok(()) + } + + /// Queues a connection for `path`, or drops it when `path` is no longer + /// bound. + fn deliver(&mut self, path: &str, conn: C) { + if let Some(queue) = self.queues.get_mut(path) { + queue.push_back(conn); + } + } + + fn take(&mut self, path: &str) -> Option { + self.queues.get_mut(path)?.pop_front() + } +} + +/// Path router for a socket shared by async listeners. +pub(crate) struct AcceptRouter { + state: Mutex>, + /// Notified when a connection is queued or the accepting call returns. + changed: Notify, +} + +impl AcceptRouter { + pub(crate) fn new() -> Self { + Self { + state: Mutex::new(PathQueues::new()), + changed: Notify::new(), + } + } + + /// Binds `path`, returning `io::ErrorKind::AddrInUse` when it is + /// already bound. + pub(crate) fn bind(&self, path: &str) -> io::Result<()> { + self.state().bind(path) + } + + /// Unbinds `path` and drops its queued connections. + pub(crate) fn unbind(&self, path: &str) { + self.state().queues.remove(path); + } + + /// Reports whether a listener has bound `path`. + pub(crate) fn is_bound(&self, path: &str) -> bool { + self.state().queues.contains_key(path) + } + + /// Returns the next connection for `path`. + /// + /// Queued connections are returned first. Otherwise the call accepts + /// from the socket when no other call is accepting, and waits for a + /// queued connection or a free socket when another call is. `next` + /// accepts one connection from the socket and returns it with its + /// request path, or `None` for a refused connection. Connections for + /// other paths are queued for those paths, and accepting continues + /// until a connection for `path` arrives. Errors from `next` are + /// returned to the caller. + pub(crate) async fn accept(&self, path: &str, mut next: F) -> io::Result + where + F: FnMut() -> Fut, + Fut: Future>>, + { + loop { + // Registering for the notification before checking the queue + // ensures that a connection queued in between wakes this call. + let mut changed = pin!(self.changed.notified()); + changed.as_mut().enable(); + let accepting = { + let mut state = self.state(); + if let Some(conn) = state.take(path) { + return Ok(conn); + } + !std::mem::replace(&mut state.accepting, true) + }; + if !accepting { + changed.await; + continue; + } + let _role = AcceptingRole { router: self }; + loop { + let Some((conn_path, conn)) = next().await? else { + continue; + }; + if conn_path == path { + return Ok(conn); + } + self.state().deliver(&conn_path, conn); + self.changed.notify_waiters(); + } + } + } + + fn state(&self) -> MutexGuard<'_, PathQueues> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// Accepting role of one call to [`AcceptRouter::accept`]. Dropping the +/// role on return, error or cancellation releases the socket to the +/// waiting calls. +struct AcceptingRole<'a, C> { + router: &'a AcceptRouter, +} + +impl Drop for AcceptingRole<'_, C> { + fn drop(&mut self) { + self.router.state().accepting = false; + self.router.changed.notify_waiters(); + } +} + +/// Path router for a socket shared by blocking listeners. +#[cfg(feature = "websocket")] +pub(crate) struct SyncAcceptRouter { + state: Mutex>, + /// Signalled when a connection is queued or the accepting call returns. + changed: Condvar, +} + +#[cfg(feature = "websocket")] +impl SyncAcceptRouter { + pub(crate) fn new() -> Self { + Self { + state: Mutex::new(PathQueues::new()), + changed: Condvar::new(), + } + } + + /// Binds `path`, returning `io::ErrorKind::AddrInUse` when it is + /// already bound. + pub(crate) fn bind(&self, path: &str) -> io::Result<()> { + self.state().bind(path) + } + + /// Unbinds `path` and drops its queued connections. + pub(crate) fn unbind(&self, path: &str) { + self.state().queues.remove(path); + } + + /// Reports whether a listener has bound `path`. + pub(crate) fn is_bound(&self, path: &str) -> bool { + self.state().queues.contains_key(path) + } + + /// Returns the next connection for `path`, blocking the calling thread. + /// + /// Follows [`AcceptRouter::accept`], with `next` blocking until it has + /// accepted one connection. + pub(crate) fn accept(&self, path: &str, mut next: F) -> io::Result + where + F: FnMut() -> io::Result>, + { + { + let mut state = self.state(); + loop { + if let Some(conn) = state.take(path) { + return Ok(conn); + } + if !state.accepting { + state.accepting = true; + break; + } + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + let _role = SyncAcceptingRole { router: self }; + loop { + let Some((conn_path, conn)) = next()? else { + continue; + }; + if conn_path == path { + return Ok(conn); + } + self.state().deliver(&conn_path, conn); + self.changed.notify_all(); + } + } + + fn state(&self) -> MutexGuard<'_, PathQueues> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// Accepting role of one call to [`SyncAcceptRouter::accept`]. Dropping +/// the role on return or error releases the socket to the waiting calls. +#[cfg(feature = "websocket")] +struct SyncAcceptingRole<'a, C> { + router: &'a SyncAcceptRouter, +} + +#[cfg(feature = "websocket")] +impl Drop for SyncAcceptingRole<'_, C> { + fn drop(&mut self) { + self.router.state().accepting = false; + self.router.changed.notify_all(); + } +} diff --git a/rust/src/models/transports/sync_websocket.rs b/rust/src/models/transports/sync_websocket.rs index 440b2eb..f3cd379 100644 --- a/rust/src/models/transports/sync_websocket.rs +++ b/rust/src/models/transports/sync_websocket.rs @@ -21,20 +21,107 @@ //! `101 Switching Protocols` response in the socket for the frame parser. //! The accepting peer runs the sync server handshake of `tungstenite`. //! +//! ## Listeners +//! +//! Each [`SyncWebSocketListener`] is the endpoint of one URL path. +//! [`SyncWebSocketTransport::bind`] binds the URL's scheme and authority as a +//! socket held in the process, and listeners for other paths on the same +//! scheme and authority share that socket. `accept` returns only the +//! upgrades requested for the listener's own path. Upgrade requests for a +//! path that no listener in the process has bound are refused with status +//! `404 Not Found`. URLs without a path refer to the path `/`. +//! //! [`WebSocketTransport`]: crate::models::transports::websocket::WebSocketTransport //! [`SyncWsRead`]: crate::models::streams::sync_websocket::SyncWsRead //! [`SyncWsWrite`]: crate::models::streams::sync_websocket::SyncWsWrite use std::io::{self, Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::Arc; -use tokio_tungstenite::tungstenite::accept; +use tokio_tungstenite::tungstenite::Error as WsError; +use tokio_tungstenite::tungstenite::{HandshakeError, WebSocket, accept_hdr}; +use crate::models::transports::routing::{SocketKey, SocketRegistry, SyncAcceptRouter}; use crate::models::transports::websocket::{ - check_handshake_response, handshake_closed, handshake_request, handshake_response_complete, - split_url, + PathCallback, check_handshake_response, handshake_closed, handshake_request, + handshake_response_complete, split_url, }; +/// Sockets bound by [`SyncWebSocketTransport::bind`] in this process. +static SOCKETS: SocketRegistry = SocketRegistry::new(); + +/// Socket shared by the sync WebSocket listeners of one scheme and +/// authority. +struct SharedSocket { + listener: TcpListener, + router: SyncAcceptRouter, +} + +/// # SyncWebSocketListener +/// +/// ## Description +/// - Blocking accepting endpoint for one `ws://` URL, returned by +/// [`SyncWebSocketTransport::bind`]. +/// - Accepts only the upgrades requested for the URL's path. URLs without +/// a path refer to the path `/`. +/// - Listeners for different paths on the same scheme and authority share +/// one socket in the process. +/// +/// ## Structure +/// - `socket`: the socket shared by the listeners of the URL's scheme and +/// authority, with the paths bound on it. +/// - `path`: the URL path this listener accepts. +/// +/// ## Usage +/// - Pass to [`SyncWebSocketTransport::accept`], or to the `accept` +/// constructors of [`SyncWebSocketTableReader`] and +/// [`SyncWebSocketTableWriter`]. +/// - Hold the listener across connections to keep its path bound. +/// +/// ## Notes +/// - Binding a URL that is already bound in the process returns +/// `io::ErrorKind::AddrInUse`. +/// - Dropping the listener unbinds its path. Dropping the last listener on +/// an authority closes the socket. +/// - Upgrades for a path that no listener has bound are refused with +/// status `404 Not Found`. +/// +/// ## Example +/// ```rust,no_run +/// # fn run() -> std::io::Result<()> { +/// use lightstream::models::readers::sync_websocket::SyncWebSocketTableReader; +/// use lightstream::models::transports::sync_websocket::SyncWebSocketTransport; +/// +/// let prices = SyncWebSocketTransport::bind("ws://127.0.0.1:9910/prices")?; +/// let trades = SyncWebSocketTransport::bind("ws://127.0.0.1:9910/trades")?; +/// +/// // Receives only the connections made to `/prices`. +/// let reader = SyncWebSocketTableReader::accept(&prices, None)?; +/// # drop((reader, trades)); +/// # Ok(()) } +/// ``` +/// +/// [`SyncWebSocketTableReader`]: crate::models::readers::sync_websocket::SyncWebSocketTableReader +/// [`SyncWebSocketTableWriter`]: crate::models::writers::sync_websocket::SyncWebSocketTableWriter +pub struct SyncWebSocketListener { + socket: Arc, + path: String, +} + +impl SyncWebSocketListener { + /// Returns the local address of the bound socket. + pub fn local_addr(&self) -> io::Result { + self.socket.listener.local_addr() + } +} + +impl Drop for SyncWebSocketListener { + fn drop(&mut self) { + self.socket.router.unbind(&self.path); + } +} + /// Blocking WebSocket transport over `std::net`. pub struct SyncWebSocketTransport; @@ -57,23 +144,76 @@ impl SyncWebSocketTransport { Ok((tcp, write_half)) } - /// Bind the URL's authority and return the listener. - pub fn bind(url: &str) -> io::Result { - let (authority, _path) = split_url(url); - TcpListener::bind(authority) + /// Bind the URL as an endpoint and return its listener. + /// + /// The first bind of a scheme and authority in the process binds its + /// socket, and later binds of other paths on it share that socket. + /// URLs with port 0 bind a new socket on a free port, reported by + /// [`SyncWebSocketListener::local_addr`]. Returns `io::ErrorKind::AddrInUse` + /// for a URL that is already bound in the process. + pub fn bind(url: &str) -> io::Result { + let scheme = if url.starts_with("wss://") { "wss" } else { "ws" }; + let (authority, path) = split_url(url); + let key = SocketKey::from_authority(scheme, authority)?; + let socket = SOCKETS.open(key, || { + let listener = TcpListener::bind(authority)?; + let port = listener.local_addr()?.port(); + Ok(( + SharedSocket { + listener, + router: SyncAcceptRouter::new(), + }, + port, + )) + })?; + socket.router.bind(path)?; + Ok(SyncWebSocketListener { + socket, + path: path.to_string(), + }) } - /// 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)> { - let (tcp, _) = listener.accept()?; - let ws_stream = accept(tcp).map_err(|e| io::Error::other(e.to_string()))?; - let tcp = ws_stream.into_inner(); + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and return the post-handshake read and + /// write halves. + /// + /// Connections that arrive for other bound paths on the socket are + /// upgraded and held for those paths' next `accept`. + pub fn accept(listener: &SyncWebSocketListener) -> io::Result<(TcpStream, TcpStream)> { + let socket = &*listener.socket; + let tcp = socket.router.accept(&listener.path, || { + let (tcp, _) = socket.listener.accept()?; + upgrade(tcp, &socket.router) + })?; let write_half = tcp.try_clone()?; Ok((tcp, write_half)) } } +/// Run the server upgrade handshake on an accepted connection, and return +/// the request path with the upgraded connection. +/// +/// Returns `None` for a request to a path that no listener has bound, +/// after answering it with status `404 Not Found`. +fn upgrade( + tcp: TcpStream, + router: &SyncAcceptRouter, +) -> io::Result> { + let mut requested = None; + let callback = PathCallback::new(|path| router.is_bound(path), &mut requested); + let result = accept_hdr(tcp, callback) + .map(WebSocket::into_inner) + .map_err(|e| match e { + HandshakeError::Failure(WsError::Http(_)) => None, + e => Some(io::Error::other(e.to_string())), + }); + match result { + Ok(tcp) => Ok(requested.map(|path| (path, tcp))), + Err(None) => Ok(None), + Err(Some(e)) => Err(e), + } +} + /// Run the client upgrade handshake on an established stream, reading /// the response byte-precisely so early frames stay in the stream for /// the frame parser. diff --git a/rust/src/models/transports/websocket.rs b/rust/src/models/transports/websocket.rs index 1d082c1..a61d848 100644 --- a/rust/src/models/transports/websocket.rs +++ b/rust/src/models/transports/websocket.rs @@ -22,22 +22,120 @@ //! //! TLS-wrapped channels keep their `connect_tls` entry points on the //! table reader and writer types. +//! +//! ## Listeners +//! +//! Each [`WebSocketListener`] is the endpoint of one URL path. +//! [`WebSocketTransport::bind`] binds the URL's scheme and authority as a +//! socket held in the process, and listeners for other paths on the same +//! scheme and authority share that socket. `accept` returns only the +//! upgrades requested for the listener's own path. Upgrade requests for a +//! path that no listener in the process has bound are refused with status +//! `404 Not Found`. URLs without a path refer to the path `/`. use std::io; +use std::net::SocketAddr; use std::str; +use std::sync::Arc; -use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf}; use tokio::net::{TcpListener, TcpStream}; -use tokio_tungstenite::accept_async; +use tokio_tungstenite::accept_hdr_async; +use tokio_tungstenite::tungstenite::Error as WsError; use tokio_tungstenite::tungstenite::handshake::client::generate_key; use tokio_tungstenite::tungstenite::handshake::derive_accept_key; +use tokio_tungstenite::tungstenite::handshake::server::{ + Callback, ErrorResponse, Request, Response, +}; +use tokio_tungstenite::tungstenite::http::StatusCode; +use crate::models::transports::routing::{AcceptRouter, SocketKey, SocketRegistry}; use crate::traits::transport::Transport; /// Cap on upgrade response header size before the handshake is /// rejected as malformed. const MAX_HANDSHAKE_RESPONSE: usize = 16 * 1024; +/// Sockets bound by [`WebSocketTransport::bind`] in this process. +static SOCKETS: SocketRegistry = SocketRegistry::new(); + +/// Socket shared by the WebSocket listeners of one scheme and authority. +struct SharedSocket { + listener: TcpListener, + router: AcceptRouter, +} + +/// Upgraded connection queued for the listener of its path. +enum Upgraded { + Plain(TcpStream), + #[cfg(feature = "tls")] + Tls(Box>), +} + +/// # WebSocketListener +/// +/// ## Description +/// - Accepting endpoint for one `ws://` or `wss://` URL, returned by +/// [`WebSocketTransport::bind`]. +/// - Accepts only the upgrades requested for the URL's path. URLs without +/// a path refer to the path `/`. +/// - Listeners for different paths on the same scheme and authority share +/// one socket in the process. +/// +/// ## Structure +/// - `socket`: the socket shared by the listeners of the URL's scheme and +/// authority, with the paths bound on it. +/// - `path`: the URL path this listener accepts. +/// +/// ## Usage +/// - Pass to [`WebSocketTransport::accept`] or +/// [`WebSocketTransport::accept_tls`], or to the `accept` constructors of +/// [`WebSocketTableReader`] and [`WebSocketTableWriter`]. +/// - Hold the listener across connections to keep its path bound. +/// +/// ## Notes +/// - Binding a URL that is already bound in the process returns +/// `io::ErrorKind::AddrInUse`. +/// - Dropping the listener unbinds its path. Dropping the last listener on +/// an authority closes the socket. +/// - Upgrades for a path that no listener has bound are refused with +/// status `404 Not Found`. +/// +/// ## Example +/// ```rust,no_run +/// # async fn run() -> std::io::Result<()> { +/// use lightstream::models::readers::websocket::WebSocketTableReader; +/// use lightstream::models::transports::websocket::WebSocketTransport; +/// +/// let prices = WebSocketTransport::bind("ws://127.0.0.1:9910/prices").await?; +/// let trades = WebSocketTransport::bind("ws://127.0.0.1:9910/trades").await?; +/// +/// // Receives only the connections made to `/prices`. +/// let reader = WebSocketTableReader::accept(&prices, None).await?; +/// # drop((reader, trades)); +/// # Ok(()) } +/// ``` +/// +/// [`WebSocketTableReader`]: crate::models::readers::websocket::WebSocketTableReader +/// [`WebSocketTableWriter`]: crate::models::writers::websocket::WebSocketTableWriter +pub struct WebSocketListener { + socket: Arc, + path: String, +} + +impl WebSocketListener { + /// Returns the local address of the bound socket. + pub fn local_addr(&self) -> io::Result { + self.socket.listener.local_addr() + } +} + +impl Drop for WebSocketListener { + fn drop(&mut self) { + self.socket.router.unbind(&self.path); + } +} + /// WebSocket implementation of [`Transport`]. pub struct WebSocketTransport; @@ -82,38 +180,160 @@ impl WebSocketTransport { Ok(tokio::io::split(tls)) } - /// Bind the URL's authority and return the listener. - pub async fn bind(url: &str) -> io::Result { - let (authority, _path) = split_url(url); - TcpListener::bind(authority).await + /// Bind the URL as an endpoint and return its listener. + /// + /// The first bind of a scheme and authority in the process binds its + /// socket, and later binds of other paths on it share that socket. + /// URLs with port 0 bind a new socket on a free port, reported by + /// [`WebSocketListener::local_addr`]. Returns `io::ErrorKind::AddrInUse` + /// for a URL that is already bound in the process. + pub async fn bind(url: &str) -> io::Result { + let scheme = if url.starts_with("wss://") { "wss" } else { "ws" }; + let (authority, path) = split_url(url); + let key = SocketKey::from_authority(scheme, authority)?; + let socket = SOCKETS.open(key, || { + let std_listener = std::net::TcpListener::bind(authority)?; + std_listener.set_nonblocking(true)?; + let port = std_listener.local_addr()?.port(); + let listener = TcpListener::from_std(std_listener)?; + Ok(( + SharedSocket { + listener, + router: AcceptRouter::new(), + }, + port, + )) + })?; + socket.router.bind(path)?; + Ok(WebSocketListener { + socket, + path: path.to_string(), + }) } - /// Accept the next inbound connection, run the server upgrade - /// handshake, and return the post-handshake halves. + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and return the post-handshake halves. + /// + /// Connections that arrive for other bound paths on the socket are + /// upgraded and held for those paths' next `accept`. pub async fn accept( - listener: &TcpListener, + listener: &WebSocketListener, ) -> io::Result<(ReadHalf, WriteHalf)> { - 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 socket = &*listener.socket; + let conn = socket + .router + .accept(&listener.path, || async move { + let (tcp, _) = socket.listener.accept().await?; + let upgraded = upgrade(tcp, &socket.router).await?; + Ok(upgraded.map(|(path, tcp)| (path, Upgraded::Plain(tcp)))) + }) + .await?; + match conn { + Upgraded::Plain(tcp) => Ok(tokio::io::split(tcp)), + #[cfg(feature = "tls")] + Upgraded::Tls(_) => Err(io::Error::new( + io::ErrorKind::InvalidData, + "the connection for this path was accepted with TLS", + )), + } } - /// Accept the next inbound connection, terminate TLS with the - /// supplied `rustls::ServerConfig`, run the server upgrade + /// Accept the next inbound connection to the listener's path, terminate + /// TLS with the supplied `rustls::ServerConfig`, run the server upgrade /// handshake over it, and return the post-handshake halves. + /// + /// TLS is terminated before the request path is known. Endpoints that + /// share an authority therefore share its TLS identity, and connections + /// held for other bound paths have completed TLS with `config`. #[cfg(feature = "tls")] pub async fn accept_tls( - listener: &TcpListener, + listener: &WebSocketListener, config: std::sync::Arc, ) -> io::Result<( ReadHalf>, WriteHalf>, )> { - let (tcp, _) = listener.accept().await?; + let socket = &*listener.socket; 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 conn = socket + .router + .accept(&listener.path, || { + let acceptor = acceptor.clone(); + async move { + let (tcp, _) = socket.listener.accept().await?; + let tls = acceptor.accept(tcp).await?; + let upgraded = upgrade(tls, &socket.router).await?; + Ok(upgraded.map(|(path, tls)| (path, Upgraded::Tls(Box::new(tls))))) + } + }) + .await?; + match conn { + Upgraded::Tls(tls) => Ok(tokio::io::split(*tls)), + Upgraded::Plain(_) => Err(io::Error::new( + io::ErrorKind::InvalidData, + "the connection for this path was accepted without TLS", + )), + } + } +} + +/// Run the server upgrade handshake on an accepted stream, and return the +/// request path with the upgraded stream. +/// +/// Returns `None` for a request to a path that no listener has bound, +/// after answering it with status `404 Not Found`. +async fn upgrade( + stream: S, + router: &AcceptRouter, +) -> io::Result> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + let mut requested = None; + let callback = PathCallback::new(|path| router.is_bound(path), &mut requested); + let result = accept_hdr_async(stream, callback).await; + match result { + Ok(ws_stream) => Ok(requested.map(|path| (path, ws_stream.into_inner()))), + Err(WsError::Http(_)) => Ok(None), + Err(e) => Err(io::Error::other(e)), + } +} + +/// Server upgrade callback that accepts a request for a bound path and +/// refuses any other path with status `404 Not Found`. +/// +/// Records the path of an accepted request. Shared by the async and +/// blocking server handshakes. +pub(crate) struct PathCallback<'a, F> { + is_bound: F, + requested: &'a mut Option, +} + +impl<'a, F> PathCallback<'a, F> +where + F: FnOnce(&str) -> bool, +{ + pub(crate) fn new(is_bound: F, requested: &'a mut Option) -> Self { + Self { + is_bound, + requested, + } + } +} + +impl Callback for PathCallback<'_, F> +where + F: FnOnce(&str) -> bool, +{ + fn on_request(self, request: &Request, response: Response) -> Result { + let path = request.uri().path(); + if !(self.is_bound)(path) { + let mut refusal = ErrorResponse::new(None); + *refusal.status_mut() = StatusCode::NOT_FOUND; + return Err(refusal); + } + *self.requested = Some(path.to_string()); + Ok(response) } } @@ -240,7 +460,7 @@ fn host_of(authority: &str) -> &str { impl Transport for WebSocketTransport { type Endpoint = str; - type Listener = TcpListener; + type Listener = WebSocketListener; type Read = ReadHalf; type Write = WriteHalf; @@ -248,11 +468,11 @@ impl Transport for WebSocketTransport { WebSocketTransport::connect(endpoint).await } - async fn bind(endpoint: &str) -> io::Result { + async fn bind(endpoint: &str) -> io::Result { WebSocketTransport::bind(endpoint).await } - async fn accept(listener: &TcpListener) -> io::Result<(Self::Read, Self::Write)> { + async fn accept(listener: &WebSocketListener) -> io::Result<(Self::Read, Self::Write)> { WebSocketTransport::accept(listener).await } } diff --git a/rust/src/models/transports/webtransport.rs b/rust/src/models/transports/webtransport.rs index 14152f3..5461413 100644 --- a/rust/src/models/transports/webtransport.rs +++ b/rust/src/models/transports/webtransport.rs @@ -21,12 +21,97 @@ //! WebTransport streams reach the peer on first use, so a connecting //! peer that only reads should shut down its write half to open the //! stream. +//! +//! ## Listeners +//! +//! Each [`WebTransportListener`] is the endpoint of one URL path. +//! [`WebTransport::bind`] binds the URL's scheme and authority as a +//! wtransport endpoint held in the process, and listeners for other paths +//! on the same scheme and authority share that endpoint. `accept` returns +//! only the sessions requested for the listener's own path. Session +//! requests for a path that no listener in the process has bound are +//! rejected with status `404 Not Found`. URLs without a path refer to the +//! path `/`. use std::io; +use std::net::SocketAddr; +use std::sync::Arc; +use wtransport::endpoint::SessionRequest; use wtransport::endpoint::endpoint_side::Server; use wtransport::{ClientConfig, Endpoint, RecvStream, SendStream, ServerConfig}; +use crate::models::transports::routing::{AcceptRouter, SocketKey, SocketRegistry}; + +/// Endpoints bound by [`WebTransport::bind`] in this process. +static SOCKETS: SocketRegistry = SocketRegistry::new(); + +/// Endpoint shared by the WebTransport listeners of one scheme and +/// authority. +struct SharedSocket { + endpoint: Endpoint, + router: AcceptRouter, +} + +/// # WebTransportListener +/// +/// ## Description +/// - Accepting endpoint for one `https://` URL, returned by +/// [`WebTransport::bind`]. +/// - Accepts only the sessions requested for the URL's path. URLs without +/// a path refer to the path `/`. +/// - Listeners for different paths on the same scheme and authority share +/// one wtransport endpoint in the process. +/// +/// ## Structure +/// - `socket`: the endpoint shared by the listeners of the URL's scheme and +/// authority, with the paths bound on it. +/// - `path`: the URL path this listener accepts. +/// +/// ## Usage +/// - Pass to [`WebTransport::accept`]. +/// - Hold the listener across sessions to keep its path bound. +/// +/// ## Notes +/// - Binding a URL that is already bound in the process returns +/// `io::ErrorKind::AddrInUse`. +/// - Dropping the listener unbinds its path. Dropping the last listener on +/// an authority closes the endpoint. +/// - Session requests for a path that no listener has bound are rejected +/// with status `404 Not Found`. +/// +/// ## Example +/// ```rust,no_run +/// # async fn run(prices_config: wtransport::ServerConfig, +/// # trades_config: wtransport::ServerConfig) -> std::io::Result<()> { +/// use lightstream::models::transports::webtransport::WebTransport; +/// +/// let prices = WebTransport::bind("https://127.0.0.1:4433/prices", prices_config)?; +/// let trades = WebTransport::bind("https://127.0.0.1:4433/trades", trades_config)?; +/// +/// // Receives only the sessions requested for `/prices`. +/// let (recv, send) = WebTransport::accept(&prices).await?; +/// # drop((recv, send, trades)); +/// # Ok(()) } +/// ``` +pub struct WebTransportListener { + socket: Arc, + path: String, +} + +impl WebTransportListener { + /// Returns the local address of the bound endpoint. + pub fn local_addr(&self) -> io::Result { + self.socket.endpoint.local_addr() + } +} + +impl Drop for WebTransportListener { + fn drop(&mut self) { + self.socket.router.unbind(&self.path); + } +} + /// WebTransport wire in the connect, bind, accept shape. pub struct WebTransport; @@ -54,15 +139,66 @@ impl WebTransport { Ok((recv, send)) } - /// Bind a WebTransport endpoint and return its listener. - pub fn bind(config: ServerConfig) -> io::Result> { - Endpoint::server(config) + /// Bind an `https://` URL as an endpoint and return its listener. + /// + /// The first bind of a scheme and authority in the process builds the + /// wtransport endpoint from `config`. Later binds of other paths on the + /// same scheme and authority share that endpoint and its TLS identity, + /// and their `config` is unused. The bind address of `config` is + /// expected to match the URL's authority. For URLs with port 0, the + /// endpoint binds the port `config` selects, reported by + /// [`WebTransportListener::local_addr`]. Returns + /// `io::ErrorKind::AddrInUse` for a URL that is already bound in the + /// process. + pub fn bind(url: &str, config: ServerConfig) -> io::Result { + let (scheme, rest) = url.split_once("://").unwrap_or(("https", url)); + let (authority, path) = match rest.find('/') { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, "/"), + }; + let key = SocketKey::from_authority(scheme, authority)?; + let socket = SOCKETS.open(key, || { + let endpoint = Endpoint::server(config)?; + let port = endpoint.local_addr()?.port(); + Ok(( + SharedSocket { + endpoint, + router: AcceptRouter::new(), + }, + port, + )) + })?; + socket.router.bind(path)?; + Ok(WebTransportListener { + socket, + path: path.to_string(), + }) } - /// Accept the next inbound session, take its first bidirectional - /// stream, and return the stream's halves. - pub async fn accept(listener: &Endpoint) -> io::Result<(RecvStream, SendStream)> { - let session_request = listener.accept().await.await.map_err(io::Error::other)?; + /// Accept the next inbound session for the listener's path, take its + /// first bidirectional stream, and return the stream's halves. + /// + /// Session requests that arrive for other bound paths on the endpoint + /// are held for those paths' next `accept`. + pub async fn accept(listener: &WebTransportListener) -> io::Result<(RecvStream, SendStream)> { + let socket = &*listener.socket; + let session_request = socket + .router + .accept(&listener.path, || async move { + let request = socket + .endpoint + .accept() + .await + .await + .map_err(io::Error::other)?; + let path = request.path().to_string(); + if !socket.router.is_bound(&path) { + request.not_found().await; + return Ok(None); + } + Ok(Some((path, request))) + }) + .await?; 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 diff --git a/rust/src/models/writers/http.rs b/rust/src/models/writers/http.rs index 58f27fb..271f3fa 100644 --- a/rust/src/models/writers/http.rs +++ b/rust/src/models/writers/http.rs @@ -28,13 +28,13 @@ use bytes::Bytes; use futures_util::sink::SinkExt; use http::{Method, Request, Uri}; use minarrow::{Field, TableV}; -use tokio::net::{TcpListener, TcpStream}; +use tokio::net::TcpStream; use crate::compression::Compression; use crate::enums::IPCMessageProtocol; use crate::models::sinks::table_sink::TableSink64; use crate::models::streams::http::{H2RecvRead, H2SendWrite}; -use crate::models::transports::http::HttpTransport; +use crate::models::transports::http::{HttpListener, HttpTransport}; use crate::traits::transport_writer::IPCTransportWriter; /// Async Arrow IPC writer over an HTTP/2 POST request body. @@ -109,8 +109,8 @@ impl HttpTableWriter { Self::from_send_stream(send_stream, response_fut, schema, compression) } - /// Accept the next inbound exchange and prepare to write Arrow IPC - /// tables into its response body. + /// Accept the next inbound exchange for the listener's path and prepare + /// to write Arrow IPC tables into its response body. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `HttpTransport::bind`, and holds it across connections. @@ -118,7 +118,7 @@ impl HttpTableWriter { /// drains it to its clean end while the response streams out. Pass /// `None` for `compression` to write uncompressed batches. pub async fn accept( - listener: &TcpListener, + listener: &HttpListener, schema: Vec, compression: Option, ) -> io::Result { diff --git a/rust/src/models/writers/sync_websocket.rs b/rust/src/models/writers/sync_websocket.rs index 896405e..0defabd 100644 --- a/rust/src/models/writers/sync_websocket.rs +++ b/rust/src/models/writers/sync_websocket.rs @@ -22,7 +22,7 @@ //! //! Both peer roles are supported. [`SyncWebSocketTableWriter::connect`] //! reaches a listening `ws://` URL, and [`SyncWebSocketTableWriter::accept`] -//! serves the next inbound connection on a bound `TcpListener`. +//! serves the next inbound connection on a bound `SyncWebSocketListener`. //! //! ## Security //! @@ -35,14 +35,13 @@ //! [`SyncWsWrite`]: crate::models::streams::sync_websocket::SyncWsWrite use std::io::{self, Read, Write}; -use std::net::TcpListener; use minarrow::{Field, Table, TableV, Vec64}; use crate::compression::Compression; use crate::models::sinks::sync_table_sink::SyncTableSink; use crate::models::streams::sync_websocket::SyncWsWrite; -use crate::models::transports::sync_websocket::SyncWebSocketTransport; +use crate::models::transports::sync_websocket::{SyncWebSocketListener, SyncWebSocketTransport}; /// Write half of [`SyncWebSocketTableWriter`]. Boxing the underlying /// `std::io::Write` lets every constructor return the same struct type for @@ -78,15 +77,16 @@ impl SyncWebSocketTableWriter { Ok(Self { sink }) } - /// Accept the next inbound connection, run the server upgrade - /// handshake, and prepare to write Arrow IPC tables to it. + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and prepare to write Arrow IPC tables to + /// it. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `SyncWebSocketTransport::bind`, and holds it across /// connections. Pass `None` for `compression` to write /// uncompressed batches. pub fn accept( - listener: &TcpListener, + listener: &SyncWebSocketListener, schema: Vec, compression: Option, ) -> io::Result { diff --git a/rust/src/models/writers/websocket.rs b/rust/src/models/writers/websocket.rs index 1d51ae6..f9fb728 100644 --- a/rust/src/models/writers/websocket.rs +++ b/rust/src/models/writers/websocket.rs @@ -33,13 +33,12 @@ use std::pin::Pin; use futures_util::sink::SinkExt; use minarrow::{Field, TableV}; use tokio_tungstenite::connect_async; -use tokio::net::TcpListener; use crate::compression::Compression; use crate::enums::IPCMessageProtocol; use crate::models::sinks::table_sink::TableSink64; use crate::models::streams::websocket::WsWrite; -use crate::models::transports::websocket::WebSocketTransport; +use crate::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use crate::traits::transport_writer::IPCTransportWriter; /// Concrete write-half type carried by [`WebSocketTableWriter`]. Boxing @@ -86,15 +85,16 @@ impl WebSocketTableWriter { Ok(ws_write) } - /// Accept the next inbound connection, run the server upgrade - /// handshake, and prepare to write Arrow IPC tables to it. + /// Accept the next inbound connection to the listener's path, run the + /// server upgrade handshake, and prepare to write Arrow IPC tables to + /// it. /// /// Serves the accepting peer role. The caller binds the listener, /// e.g. via `WebSocketTransport::bind`, and holds it across /// connections. Pass `None` for `compression` to write /// uncompressed batches. pub async fn accept( - listener: &TcpListener, + listener: &WebSocketListener, schema: Vec, compression: Option, ) -> io::Result { diff --git a/rust/tests/sync_websocket_roundtrip.rs b/rust/tests/sync_websocket_roundtrip.rs index 95b1355..15d3c8f 100644 --- a/rust/tests/sync_websocket_roundtrip.rs +++ b/rust/tests/sync_websocket_roundtrip.rs @@ -21,7 +21,7 @@ use std::io::{self, Write}; use std::net::TcpListener; -use std::sync::Arc; +use std::sync::{Arc, mpsc}; use std::thread; use futures_util::StreamExt; @@ -34,7 +34,10 @@ use lightstream::models::frames::websocket::{ use lightstream::models::readers::sync_websocket::SyncWebSocketTableReader; use lightstream::models::readers::websocket::WebSocketTableReader; use lightstream::models::streams::sync_websocket::{SyncWsRead, SyncWsWrite}; -use lightstream::models::transports::sync_websocket::SyncWebSocketTransport; +use lightstream::models::transports::sync_websocket::{ + SyncWebSocketListener, SyncWebSocketTransport, +}; +use lightstream::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use lightstream::models::writers::sync_websocket::SyncWebSocketTableWriter; use lightstream::models::writers::websocket::WebSocketTableWriter; use lightstream::traits::transport_reader::IPCTransportReader; @@ -159,8 +162,10 @@ enum Listening { /// Connection role of one peer. enum Endpoint { - Connect(String), - Accept(TcpListener), + /// Connects to the URL the accepting peer sends once it has bound. + Connect(mpsc::Receiver), + /// Binds a loopback URL, sends it to the connecting peer, and accepts. + Accept(mpsc::Sender), } fn current_thread_runtime() -> tokio::runtime::Runtime { @@ -171,15 +176,18 @@ fn current_thread_runtime() -> tokio::runtime::Runtime { } /// Bind a loopback listener and return it with its `ws://` URL. -fn bind_local() -> (TcpListener, String) { +fn bind_local() -> (SyncWebSocketListener, String) { let listener = SyncWebSocketTransport::bind("ws://127.0.0.1:0").unwrap(); let url = format!("ws://{}", listener.local_addr().unwrap()); (listener, url) } -fn to_tokio_listener(listener: TcpListener) -> io::Result { - listener.set_nonblocking(true)?; - tokio::net::TcpListener::from_std(listener) +/// Bind a loopback listener for the async transport and return it with its +/// `ws://` URL. Call within the runtime that accepts on it. +async fn bind_local_async() -> (WebSocketListener, String) { + let listener = WebSocketTransport::bind("ws://127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + (listener, url) } fn write_tables( @@ -194,9 +202,12 @@ fn write_tables( // The sync writer registers dictionaries from categorical columns. let mut writer = match endpoint { Endpoint::Connect(url) => { - SyncWebSocketTableWriter::connect(&url, schema, compression).unwrap() + SyncWebSocketTableWriter::connect(&url.recv().unwrap(), schema, compression) + .unwrap() } - Endpoint::Accept(listener) => { + Endpoint::Accept(url) => { + let (listener, local_url) = bind_local(); + url.send(local_url).unwrap(); SyncWebSocketTableWriter::accept(&listener, schema, compression).unwrap() } }; @@ -204,11 +215,14 @@ fn write_tables( } Side::Async => current_thread_runtime().block_on(async move { let mut writer = match endpoint { - Endpoint::Connect(url) => WebSocketTableWriter::connect(&url, schema, compression) - .await - .unwrap(), - Endpoint::Accept(listener) => { - let listener = to_tokio_listener(listener).unwrap(); + Endpoint::Connect(url) => { + WebSocketTableWriter::connect(&url.recv().unwrap(), schema, compression) + .await + .unwrap() + } + Endpoint::Accept(url) => { + let (listener, local_url) = bind_local_async().await; + url.send(local_url).unwrap(); WebSocketTableWriter::accept(&listener, schema, compression) .await .unwrap() @@ -231,16 +245,25 @@ fn read_tables( match side { Side::Sync => { let reader = match endpoint { - Endpoint::Connect(url) => SyncWebSocketTableReader::connect(&url, limits)?, - Endpoint::Accept(listener) => SyncWebSocketTableReader::accept(&listener, limits)?, + Endpoint::Connect(url) => { + SyncWebSocketTableReader::connect(&url.recv().unwrap(), limits)? + } + Endpoint::Accept(url) => { + let (listener, local_url) = bind_local(); + url.send(local_url).unwrap(); + SyncWebSocketTableReader::accept(&listener, limits)? + } }; reader.read_all_tables() } Side::Async => current_thread_runtime().block_on(async move { let reader = match endpoint { - Endpoint::Connect(url) => WebSocketTableReader::connect(&url, limits).await?, - Endpoint::Accept(listener) => { - let listener = to_tokio_listener(listener)?; + Endpoint::Connect(url) => { + WebSocketTableReader::connect(&url.recv().unwrap(), limits).await? + } + Endpoint::Accept(url) => { + let (listener, local_url) = bind_local_async().await; + url.send(local_url).unwrap(); WebSocketTableReader::accept(&listener, limits).await? } }; @@ -259,12 +282,12 @@ fn transfer( compression: Option, limits: Option, ) -> io::Result> { - let (listener, url) = bind_local(); + let (url_tx, url_rx) = mpsc::channel(); let schema = schema_of(&tables[0]); let (writer_end, reader_end) = match listening { - Listening::Writer => (Endpoint::Accept(listener), Endpoint::Connect(url)), - Listening::Reader => (Endpoint::Connect(url), Endpoint::Accept(listener)), + Listening::Writer => (Endpoint::Accept(url_tx), Endpoint::Connect(url_rx)), + Listening::Reader => (Endpoint::Connect(url_rx), Endpoint::Accept(url_tx)), }; let writer_thread = @@ -444,22 +467,25 @@ fn capture_messages( tables: Vec, compression: Option, ) -> Vec<(u8, Vec)> { - let (listener, url) = bind_local(); + let (url_tx, url_rx) = mpsc::channel(); let schema = schema_of(&tables[0]); - let (writer_end, reader_listener) = match listening { - Listening::Writer => (Endpoint::Accept(listener), None), - Listening::Reader => (Endpoint::Connect(url.clone()), Some(listener)), + let (writer_end, reader_end) = match listening { + Listening::Writer => (Endpoint::Accept(url_tx), Endpoint::Connect(url_rx)), + Listening::Reader => (Endpoint::Connect(url_rx), Endpoint::Accept(url_tx)), }; let writer_thread = thread::spawn(move || write_tables(writer, writer_end, schema, tables, compression)); - let mut ws_read = match reader_listener { - Some(listener) => { + let mut ws_read = match reader_end { + Endpoint::Accept(url) => { + let (listener, local_url) = bind_local(); + url.send(local_url).unwrap(); let (read_half, write_half) = SyncWebSocketTransport::accept(&listener).unwrap(); let (shared, _ws_write) = SyncWsWrite::new(write_half); SyncWsRead::new(read_half, shared) } - None => { + Endpoint::Connect(url) => { + let url = url.recv().unwrap(); let (read_half, write_half) = SyncWebSocketTransport::connect(&url).unwrap(); let (shared, _ws_write) = SyncWsWrite::new_client(write_half); SyncWsRead::new_client(read_half, shared) @@ -541,7 +567,8 @@ fn sync_transport_reads_text_and_binary_messages_from_a_connecting_peer() { #[test] fn sync_transport_reads_messages_from_an_accepting_peer() { - let (listener, url) = bind_local(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); let peer = thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); let mut socket = tungstenite::accept(stream).unwrap(); @@ -697,3 +724,116 @@ fn sync_ws_write_closes_once_and_rejects_later_writes() { assert_eq!(ws_write.write(b"late").unwrap_err().kind(), io::ErrorKind::Other); assert_eq!(*shared.lock().unwrap(), [0x82, 2, b'o', b'k', 0x88, 2, 0x03, 0xE8]); } + +/// Bind `/prices` on a free port, then `/trades` on the same authority. +fn bind_two_paths() -> (SyncWebSocketListener, SyncWebSocketListener, String) { + let prices = SyncWebSocketTransport::bind("ws://127.0.0.1:0/prices").unwrap(); + let base = format!("ws://{}", prices.local_addr().unwrap()); + let trades = SyncWebSocketTransport::bind(&format!("{base}/trades")).unwrap(); + assert_eq!(trades.local_addr().unwrap(), prices.local_addr().unwrap()); + (prices, trades, base) +} + +/// Connect to `url`, write one table of `n_rows` rows and finish. +fn send_table(url: &str, n_rows: usize) { + let table = make_large_table(n_rows); + let mut writer = SyncWebSocketTableWriter::connect(url, schema_of(&table), None).unwrap(); + writer.write_table(table).unwrap(); + writer.finish().unwrap(); +} + +/// Accept one connection on `listener` and return the row counts it sends. +fn receive_rows(listener: &SyncWebSocketListener) -> Vec { + let reader = SyncWebSocketTableReader::accept(listener, None).unwrap(); + reader + .read_all_tables() + .unwrap() + .iter() + .map(|table| table.n_rows) + .collect() +} + +#[test] +fn listeners_on_one_authority_receive_their_own_paths() { + let (prices, trades, base) = bind_two_paths(); + + // Only the `/prices` listener accepts at first, therefore it upgrades + // the `/trades` connection and holds it for `/trades`. + let prices_server = thread::spawn(move || receive_rows(&prices)); + send_table(&format!("{base}/trades"), 5); + send_table(&format!("{base}/prices"), 3); + assert_eq!(prices_server.join().unwrap(), [3]); + assert_eq!(receive_rows(&trades), [5]); +} + +#[test] +fn listeners_on_one_authority_accept_concurrently() { + let (prices, trades, base) = bind_two_paths(); + let prices_server = thread::spawn(move || receive_rows(&prices)); + let trades_server = thread::spawn(move || receive_rows(&trades)); + send_table(&format!("{base}/prices"), 3); + send_table(&format!("{base}/trades"), 5); + assert_eq!(prices_server.join().unwrap(), [3]); + assert_eq!(trades_server.join().unwrap(), [5]); +} + +#[test] +fn upgrades_to_unbound_paths_are_refused() { + let listener = SyncWebSocketTransport::bind("ws://127.0.0.1:0/prices").unwrap(); + let base = format!("ws://{}", listener.local_addr().unwrap()); + let server = thread::spawn(move || receive_rows(&listener)); + + let error = SyncWebSocketTransport::connect(&format!("{base}/missing")).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::ConnectionRefused); + + send_table(&format!("{base}/prices"), 4); + assert_eq!(server.join().unwrap(), [4]); +} + +#[test] +fn url_without_a_path_is_the_root_path() { + let (listener, url) = bind_local(); + let error = SyncWebSocketTransport::bind(&format!("{url}/")) + .err() + .expect("the root path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + + let server = thread::spawn(move || receive_rows(&listener)); + send_table(&format!("{url}/"), 2); + assert_eq!(server.join().unwrap(), [2]); +} + +#[test] +fn binding_bound_urls_returns_addr_in_use() { + let (_prices, _trades, base) = bind_two_paths(); + for path in ["/prices", "/trades"] { + let error = SyncWebSocketTransport::bind(&format!("{base}{path}")) + .err() + .expect("the path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse, "{path}"); + } +} + +#[test] +fn dropped_listeners_unbind_their_paths_and_the_last_frees_the_port() { + let (prices, trades, base) = bind_two_paths(); + let addr = prices.local_addr().unwrap(); + drop(trades); + let trades = SyncWebSocketTransport::bind(&format!("{base}/trades")).unwrap(); + drop(trades); + drop(prices); + TcpListener::bind(addr).unwrap(); +} + +#[test] +fn upgrades_to_dropped_paths_are_refused() { + let (prices, trades, base) = bind_two_paths(); + drop(trades); + let server = thread::spawn(move || receive_rows(&prices)); + + let error = SyncWebSocketTransport::connect(&format!("{base}/trades")).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::ConnectionRefused); + + send_table(&format!("{base}/prices"), 6); + assert_eq!(server.join().unwrap(), [6]); +} diff --git a/rust/tests/transport_roundtrip.rs b/rust/tests/transport_roundtrip.rs index 24c5c56..7eda7f1 100644 --- a/rust/tests/transport_roundtrip.rs +++ b/rust/tests/transport_roundtrip.rs @@ -178,14 +178,156 @@ mod uds { #[cfg(feature = "websocket")] mod ws { + use std::io; + use std::net::SocketAddr; + use lightstream::models::readers::websocket::WebSocketTableReader; - use lightstream::models::transports::websocket::WebSocketTransport; + use lightstream::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use lightstream::models::writers::websocket::WebSocketTableWriter; use lightstream::traits::transport_reader::IPCTransportReader; use lightstream::traits::transport_writer::IPCTransportWriter; use super::{assert_tables, make_table, table_schema}; + /// Bind `/prices` on a free port, then `/trades` on the same authority. + async fn bind_two_paths(scheme: &str) -> (WebSocketListener, WebSocketListener, SocketAddr) { + let prices = WebSocketTransport::bind(&format!("{scheme}://127.0.0.1:0/prices")) + .await + .unwrap(); + let addr = prices.local_addr().unwrap(); + let trades = WebSocketTransport::bind(&format!("{scheme}://{addr}/trades")) + .await + .unwrap(); + assert_eq!(trades.local_addr().unwrap(), addr); + (prices, trades, addr) + } + + /// Connect to `url`, write one table of `n_rows` rows and finish. + async fn send_table(url: &str, n_rows: usize) { + let mut writer = WebSocketTableWriter::connect(url, table_schema(), None) + .await + .unwrap(); + writer.write_table(make_table("t", n_rows)).await.unwrap(); + writer.finish().await.unwrap(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_listeners_on_one_authority_receive_their_own_paths() { + let (prices, trades, addr) = bind_two_paths("ws").await; + + // Only the `/prices` listener accepts at first, therefore it + // upgrades the `/trades` connection and holds it for `/trades`. + let prices_server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("ws://{addr}/trades"), 5).await; + send_table(&format!("ws://{addr}/prices"), 3).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + + let reader = WebSocketTableReader::accept(&trades, None).await.unwrap(); + assert_tables(&reader.read_all_tables().await.unwrap(), &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_listeners_on_one_authority_accept_concurrently() { + let (prices, trades, addr) = bind_two_paths("ws").await; + let prices_server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + let trades_server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&trades, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("ws://{addr}/prices"), 3).await; + send_table(&format!("ws://{addr}/trades"), 5).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + assert_tables(&trades_server.await.unwrap(), &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_upgrades_to_unbound_paths_are_refused() { + let listener = WebSocketTransport::bind("ws://127.0.0.1:0/prices").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&listener, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + + let error = WebSocketTransport::connect(&format!("ws://{addr}/missing")) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::ConnectionRefused); + + send_table(&format!("ws://{addr}/prices"), 4).await; + assert_tables(&server.await.unwrap(), &[4]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_url_without_a_path_is_the_root_path() { + let listener = WebSocketTransport::bind("ws://127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let error = WebSocketTransport::bind(&format!("ws://{addr}/")) + .await + .err() + .expect("the root path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + + let server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&listener, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("ws://{addr}/"), 2).await; + assert_tables(&server.await.unwrap(), &[2]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_binding_bound_urls_returns_addr_in_use() { + for scheme in ["ws", "wss"] { + let (_prices, _trades, addr) = bind_two_paths(scheme).await; + for path in ["/prices", "/trades"] { + let error = WebSocketTransport::bind(&format!("{scheme}://{addr}{path}")) + .await + .err() + .expect("the path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse, "{scheme} {path}"); + } + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_dropped_listeners_unbind_their_paths_and_the_last_frees_the_port() { + for scheme in ["ws", "wss"] { + let (prices, trades, addr) = bind_two_paths(scheme).await; + drop(trades); + let trades = WebSocketTransport::bind(&format!("{scheme}://{addr}/trades")) + .await + .unwrap(); + drop(trades); + drop(prices); + std::net::TcpListener::bind(addr).unwrap(); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_websocket_upgrades_to_dropped_paths_are_refused() { + let (prices, trades, addr) = bind_two_paths("ws").await; + drop(trades); + let server = tokio::spawn(async move { + let reader = WebSocketTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + + let error = WebSocketTransport::connect(&format!("ws://{addr}/trades")) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::ConnectionRefused); + + send_table(&format!("ws://{addr}/prices"), 6).await; + assert_tables(&server.await.unwrap(), &[6]); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_websocket_accepting_writer_to_connecting_reader() { let listener = WebSocketTransport::bind("ws://127.0.0.1:0").await.unwrap(); @@ -231,18 +373,173 @@ mod ws { #[cfg(feature = "http")] mod http { + use std::io; + use std::net::SocketAddr; + + use ::http::{Request, StatusCode}; use lightstream::models::readers::http::HttpTableReader; - use lightstream::models::transports::http::HttpTransport; + use lightstream::models::transports::http::{HttpListener, HttpTransport}; use lightstream::models::writers::http::HttpTableWriter; use lightstream::traits::transport_reader::IPCTransportReader; use lightstream::traits::transport_writer::IPCTransportWriter; + use tokio::net::TcpStream; use super::{assert_tables, make_table, table_schema}; + /// Bind `/prices` on a free port, then `/trades` on the same authority. + async fn bind_two_paths(scheme: &str) -> (HttpListener, HttpListener, SocketAddr) { + let prices = HttpTransport::bind(&format!("{scheme}://127.0.0.1:0/prices")) + .await + .unwrap(); + let addr = prices.local_addr().unwrap(); + let trades = HttpTransport::bind(&format!("{scheme}://{addr}/trades")) + .await + .unwrap(); + assert_eq!(trades.local_addr().unwrap(), addr); + (prices, trades, addr) + } + + /// POST one table of `n_rows` rows to `url` and finish. + async fn send_table(url: &str, n_rows: usize) { + let mut writer = HttpTableWriter::post(url, table_schema(), None).await.unwrap(); + writer.write_table(make_table("t", n_rows)).await.unwrap(); + writer.finish().await.unwrap(); + } + + /// POST an empty body to `url` over h2c and return the response status. + async fn post_status(url: &str) -> StatusCode { + let request = Request::post(url).body(()).unwrap(); + let authority = request.uri().authority().unwrap().to_string(); + let tcp = TcpStream::connect(authority).await.unwrap(); + let (mut send_request, connection) = h2::client::handshake(tcp).await.unwrap(); + tokio::spawn(async move { + let _ = connection.await; + }); + let (response, _body) = send_request.send_request(request, true).unwrap(); + response.await.unwrap().status() + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_http_accepting_writer_to_connecting_reader() { + async fn test_http_listeners_on_one_authority_receive_their_own_paths() { + let (prices, trades, addr) = bind_two_paths("http").await; + + // Only the `/prices` listener accepts at first, therefore it + // holds the `/trades` request for `/trades`. + let prices_server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("http://{addr}/trades"), 5).await; + send_table(&format!("http://{addr}/prices"), 3).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + + let reader = HttpTableReader::accept(&trades, None).await.unwrap(); + assert_tables(&reader.read_all_tables().await.unwrap(), &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_listeners_on_one_authority_accept_concurrently() { + let (prices, trades, addr) = bind_two_paths("http").await; + let prices_server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + let trades_server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&trades, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("http://{addr}/prices"), 3).await; + send_table(&format!("http://{addr}/trades"), 5).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + assert_tables(&trades_server.await.unwrap(), &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_requests_to_unbound_paths_are_refused() { + let listener = HttpTransport::bind("http://127.0.0.1:0/prices").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&listener, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + + assert_eq!( + post_status(&format!("http://{addr}/missing")).await, + StatusCode::NOT_FOUND + ); + + send_table(&format!("http://{addr}/prices"), 4).await; + assert_tables(&server.await.unwrap(), &[4]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_url_without_a_path_is_the_root_path() { let listener = HttpTransport::bind("http://127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); + let error = HttpTransport::bind(&format!("http://{addr}/")) + .await + .err() + .expect("the root path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + + let server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&listener, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + send_table(&format!("http://{addr}/"), 2).await; + assert_tables(&server.await.unwrap(), &[2]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_binding_bound_urls_returns_addr_in_use() { + for scheme in ["http", "https"] { + let (_prices, _trades, addr) = bind_two_paths(scheme).await; + for path in ["/prices", "/trades"] { + let error = HttpTransport::bind(&format!("{scheme}://{addr}{path}")) + .await + .err() + .expect("the path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse, "{scheme} {path}"); + } + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_dropped_listeners_unbind_their_paths_and_the_last_frees_the_port() { + for scheme in ["http", "https"] { + let (prices, trades, addr) = bind_two_paths(scheme).await; + drop(trades); + let trades = HttpTransport::bind(&format!("{scheme}://{addr}/trades")) + .await + .unwrap(); + drop(trades); + drop(prices); + std::net::TcpListener::bind(addr).unwrap(); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_requests_to_dropped_paths_are_refused() { + let (prices, trades, addr) = bind_two_paths("http").await; + drop(trades); + let server = tokio::spawn(async move { + let reader = HttpTableReader::accept(&prices, None).await.unwrap(); + reader.read_all_tables().await.unwrap() + }); + + assert_eq!( + post_status(&format!("http://{addr}/trades")).await, + StatusCode::NOT_FOUND + ); + + send_table(&format!("http://{addr}/prices"), 6).await; + assert_tables(&server.await.unwrap(), &[6]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_http_accepting_writer_to_connecting_reader() { + let listener = HttpTransport::bind("http://127.0.0.1:0/feed").await.unwrap(); + let addr = listener.local_addr().unwrap(); let server = tokio::spawn(async move { let mut writer = HttpTableWriter::accept(&listener, table_schema(), None) @@ -263,7 +560,7 @@ mod http { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_http_connecting_writer_to_accepting_reader() { - let listener = HttpTransport::bind("http://127.0.0.1:0").await.unwrap(); + let listener = HttpTransport::bind("http://127.0.0.1:0/ingest").await.unwrap(); let addr = listener.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -425,13 +722,18 @@ mod quic { #[cfg(feature = "webtransport")] mod wt { + use std::io; + use std::net::{SocketAddr, UdpSocket}; + use std::time::{Duration, Instant}; + use lightstream::models::readers::webtransport::WebTransportTableReader; - use lightstream::models::transports::webtransport::WebTransport; + use lightstream::models::transports::webtransport::{WebTransport, WebTransportListener}; use lightstream::models::writers::webtransport::WebTransportTableWriter; use lightstream::traits::transport_reader::IPCTransportReader; use lightstream::traits::transport_writer::IPCTransportWriter; use tokio::io::AsyncWriteExt; use wtransport::tls::Sha256Digest; + use minarrow::Table; use wtransport::{ClientConfig, Identity, ServerConfig}; use super::{assert_tables, make_table, table_schema}; @@ -458,10 +760,174 @@ mod wt { .build() } + /// Server config bound to a free loopback port, matching the + /// `https://127.0.0.1:0` URLs of the path tests. + fn make_loopback_server_config(identity: Identity) -> ServerConfig { + ServerConfig::builder() + .with_bind_address(SocketAddr::from(([127, 0, 0, 1], 0))) + .with_identity(identity) + .build() + } + + /// Bind `/prices` on a free port, then `/trades` on the same authority, + /// and return the certificate hash clients pin. + fn bind_two_paths() -> (WebTransportListener, WebTransportListener, SocketAddr, Sha256Digest) { + let (identity, cert_hash) = make_test_identity(); + let prices = WebTransport::bind( + "https://127.0.0.1:0/prices", + make_loopback_server_config(identity), + ) + .unwrap(); + let addr = prices.local_addr().unwrap(); + // The second bind shares the endpoint, and its config is unused. + let (identity, _) = make_test_identity(); + let trades = WebTransport::bind( + &format!("https://{addr}/trades"), + make_loopback_server_config(identity), + ) + .unwrap(); + assert_eq!(trades.local_addr().unwrap(), addr); + (prices, trades, addr, cert_hash) + } + + /// Open a session on `url`, write one table of `n_rows` rows and finish. + async fn send_table(url: String, cert_hash: Sha256Digest, n_rows: usize) { + let (_recv, send) = WebTransport::connect(&url, make_client_config(cert_hash)) + .await + .unwrap(); + let mut writer = WebTransportTableWriter::new(send, table_schema(), None).unwrap(); + writer.write_table(make_table("t", n_rows)).await.unwrap(); + writer.finish().await.unwrap(); + } + + /// Accept one session on `listener` and read its tables. + async fn receive_tables(listener: &WebTransportListener) -> Vec
{ + let (recv, _send) = WebTransport::accept(listener).await.unwrap(); + WebTransportTableReader::from_recv(recv, None) + .read_all_tables() + .await + .unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_listeners_on_one_authority_receive_their_own_paths() { + let (prices, trades, addr, cert_hash) = bind_two_paths(); + + // Only the `/prices` listener accepts at first, therefore it holds + // the `/trades` session request for `/trades`. That session opens + // once `/trades` accepts, so its client runs on a task. + let prices_server = tokio::spawn(async move { receive_tables(&prices).await }); + let trades_client = tokio::spawn(send_table(format!("https://{addr}/trades"), cert_hash.clone(), 5)); + send_table(format!("https://{addr}/prices"), cert_hash, 3).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + + assert_tables(&receive_tables(&trades).await, &[5]); + trades_client.await.unwrap(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_sessions_for_unbound_paths_are_rejected() { + let (identity, cert_hash) = make_test_identity(); + let listener = WebTransport::bind( + "https://127.0.0.1:0/prices", + make_loopback_server_config(identity), + ) + .unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { receive_tables(&listener).await }); + + let rejected = WebTransport::connect( + &format!("https://{addr}/missing"), + make_client_config(cert_hash.clone()), + ) + .await; + let error = rejected.err().expect("the session is rejected"); + assert_eq!(error.to_string(), "server rejected WebTransport session request"); + + send_table(format!("https://{addr}/prices"), cert_hash, 4).await; + assert_tables(&server.await.unwrap(), &[4]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_url_without_a_path_is_the_root_path() { + let (identity, cert_hash) = make_test_identity(); + let listener = + WebTransport::bind("https://127.0.0.1:0", make_loopback_server_config(identity)) + .unwrap(); + let addr = listener.local_addr().unwrap(); + let (identity, _) = make_test_identity(); + let error = WebTransport::bind( + &format!("https://{addr}/"), + make_loopback_server_config(identity), + ) + .err() + .expect("the root path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + + let server = tokio::spawn(async move { receive_tables(&listener).await }); + send_table(format!("https://{addr}/"), cert_hash, 2).await; + assert_tables(&server.await.unwrap(), &[2]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_binding_bound_urls_returns_addr_in_use() { + let (_prices, _trades, addr, _) = bind_two_paths(); + for path in ["/prices", "/trades"] { + let (identity, _) = make_test_identity(); + let error = WebTransport::bind( + &format!("https://{addr}{path}"), + make_loopback_server_config(identity), + ) + .err() + .expect("the path is bound"); + assert_eq!(error.kind(), io::ErrorKind::AddrInUse, "{path}"); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_dropped_listeners_unbind_their_paths_and_the_last_frees_the_port() { + let (prices, trades, addr, _) = bind_two_paths(); + drop(trades); + let (identity, _) = make_test_identity(); + let trades = WebTransport::bind( + &format!("https://{addr}/trades"), + make_loopback_server_config(identity), + ) + .unwrap(); + drop(trades); + drop(prices); + + // The endpoint's driver closes the socket once it observes the drop. + let deadline = Instant::now() + Duration::from_secs(5); + while UdpSocket::bind(addr).is_err() { + assert!(Instant::now() < deadline, "the port stays bound"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_webtransport_sessions_for_dropped_paths_are_rejected() { + let (prices, trades, addr, cert_hash) = bind_two_paths(); + drop(trades); + let server = tokio::spawn(async move { receive_tables(&prices).await }); + + let rejected = WebTransport::connect( + &format!("https://{addr}/trades"), + make_client_config(cert_hash.clone()), + ) + .await; + let error = rejected.err().expect("the session is rejected"); + assert_eq!(error.to_string(), "server rejected WebTransport session request"); + + send_table(format!("https://{addr}/prices"), cert_hash, 6).await; + assert_tables(&server.await.unwrap(), &[6]); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_webtransport_connecting_writer_to_accepting_reader() { let (identity, cert_hash) = make_test_identity(); - let listener = WebTransport::bind(make_server_config(identity)).unwrap(); + let listener = + WebTransport::bind("https://127.0.0.1:0", make_server_config(identity)).unwrap(); let port = listener.local_addr().unwrap().port(); let server = tokio::spawn(async move { @@ -486,7 +952,8 @@ mod wt { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_webtransport_accepting_writer_to_connecting_reader() { let (identity, cert_hash) = make_test_identity(); - let listener = WebTransport::bind(make_server_config(identity)).unwrap(); + let listener = + WebTransport::bind("https://127.0.0.1:0", make_server_config(identity)).unwrap(); let port = listener.local_addr().unwrap().port(); let server = tokio::spawn(async move { @@ -515,18 +982,21 @@ mod wt { #[cfg(all(feature = "websocket", feature = "http", feature = "tls"))] mod tls_wires { + use std::io; use std::sync::Arc; + use ::http::{Request, StatusCode}; use lightstream::models::readers::http::HttpTableReader; use lightstream::models::readers::websocket::WebSocketTableReader; - use lightstream::models::transports::http::HttpTransport; - use lightstream::models::transports::websocket::WebSocketTransport; + use lightstream::models::transports::http::{HttpListener, HttpTransport}; + use lightstream::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use lightstream::models::writers::http::HttpTableWriter; use lightstream::models::writers::websocket::WebSocketTableWriter; use lightstream::enums::IPCMessageProtocol; use lightstream::traits::transport_reader::IPCTransportReader; use lightstream::traits::transport_writer::IPCTransportWriter; - use tokio::net::TcpListener; + use minarrow::Table; + use tokio::net::TcpStream; use super::{assert_tables, make_table, table_schema}; @@ -557,10 +1027,176 @@ mod tls_wires { (Arc::new(server), Arc::new(client)) } + /// Accept one wss connection on `listener` and read its tables. + async fn receive_wss_tables( + listener: &WebSocketListener, + config: Arc, + ) -> Vec
{ + let (read_half, write_half) = WebSocketTransport::accept_tls(listener, config) + .await + .unwrap(); + WebSocketTableReader::from_halves(read_half, write_half, IPCMessageProtocol::Stream, None) + .read_all_tables() + .await + .unwrap() + } + + /// Connect to a `wss://` URL, write one table of `n_rows` rows and finish. + async fn send_wss_table(url: &str, config: Arc, n_rows: usize) { + let mut writer = WebSocketTableWriter::connect_tls(url, config, table_schema(), None) + .await + .unwrap(); + writer.write_table(make_table("t", n_rows)).await.unwrap(); + writer.finish().await.unwrap(); + } + + /// Accept one https exchange on `listener` and read its tables. + async fn receive_https_tables( + listener: &HttpListener, + config: Arc, + ) -> Vec
{ + let (recv_read, send_write) = HttpTransport::accept_tls(listener, config).await.unwrap(); + HttpTableReader::from_exchange(recv_read, send_write, None) + .await + .unwrap() + .read_all_tables() + .await + .unwrap() + } + + /// POST one table of `n_rows` rows to an `https://` URL and finish. + async fn send_https_table(url: &str, config: Arc, n_rows: usize) { + let mut writer = HttpTableWriter::post_tls(url, config, table_schema(), None) + .await + .unwrap(); + writer.write_table(make_table("t", n_rows)).await.unwrap(); + writer.finish().await.unwrap(); + } + + /// POST an empty body to an `https://localhost` URL and return the + /// response status. + async fn post_tls_status(url: &str, config: Arc) -> StatusCode { + let request = Request::post(url).body(()).unwrap(); + let port = request.uri().port_u16().unwrap(); + let tcp = TcpStream::connect(("localhost", port)).await.unwrap(); + let server_name = rustls::pki_types::ServerName::try_from("localhost").unwrap(); + let tls = tokio_rustls::TlsConnector::from(config) + .connect(server_name, tcp) + .await + .unwrap(); + let (mut send_request, connection) = h2::client::handshake(tls).await.unwrap(); + tokio::spawn(async move { + let _ = connection.await; + }); + let (response, _body) = send_request.send_request(request, true).unwrap(); + response.await.unwrap().status() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wss_listeners_on_one_authority_receive_their_own_paths() { + let (server_config, client_config) = make_tls_pair(&[]); + let prices = WebSocketTransport::bind("wss://127.0.0.1:0/prices").await.unwrap(); + let port = prices.local_addr().unwrap().port(); + let trades = WebSocketTransport::bind(&format!("wss://127.0.0.1:{port}/trades")) + .await + .unwrap(); + + // The `/prices` accept terminates TLS for the `/trades` connection + // too, because both paths share the authority's TLS identity. + let prices_config = server_config.clone(); + let prices_server = + tokio::spawn(async move { receive_wss_tables(&prices, prices_config).await }); + let base = format!("wss://localhost:{port}"); + send_wss_table(&format!("{base}/trades"), client_config.clone(), 5).await; + send_wss_table(&format!("{base}/prices"), client_config, 3).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + assert_tables(&receive_wss_tables(&trades, server_config).await, &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wss_upgrades_to_unbound_paths_are_refused() { + let (server_config, client_config) = make_tls_pair(&[]); + let listener = WebSocketTransport::bind("wss://127.0.0.1:0/prices").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = + tokio::spawn(async move { receive_wss_tables(&listener, server_config).await }); + + let base = format!("wss://localhost:{port}"); + let error = WebSocketTransport::connect_tls(&format!("{base}/missing"), client_config.clone()) + .await + .err() + .expect("the upgrade is refused"); + assert_eq!(error.kind(), io::ErrorKind::ConnectionRefused); + + send_wss_table(&format!("{base}/prices"), client_config, 4).await; + assert_tables(&server.await.unwrap(), &[4]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wss_url_without_a_path_is_the_root_path() { + let (server_config, client_config) = make_tls_pair(&[]); + let listener = WebSocketTransport::bind("wss://127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = + tokio::spawn(async move { receive_wss_tables(&listener, server_config).await }); + send_wss_table(&format!("wss://localhost:{port}/"), client_config, 2).await; + assert_tables(&server.await.unwrap(), &[2]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_https_listeners_on_one_authority_receive_their_own_paths() { + let (server_config, client_config) = make_tls_pair(&[b"h2"]); + let prices = HttpTransport::bind("https://127.0.0.1:0/prices").await.unwrap(); + let port = prices.local_addr().unwrap().port(); + let trades = HttpTransport::bind(&format!("https://127.0.0.1:{port}/trades")) + .await + .unwrap(); + + // The `/prices` accept terminates TLS for the `/trades` request + // too, because both paths share the authority's TLS identity. + let prices_config = server_config.clone(); + let prices_server = + tokio::spawn(async move { receive_https_tables(&prices, prices_config).await }); + let base = format!("https://localhost:{port}"); + send_https_table(&format!("{base}/trades"), client_config.clone(), 5).await; + send_https_table(&format!("{base}/prices"), client_config, 3).await; + assert_tables(&prices_server.await.unwrap(), &[3]); + assert_tables(&receive_https_tables(&trades, server_config).await, &[5]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_https_requests_to_unbound_paths_are_refused() { + let (server_config, client_config) = make_tls_pair(&[b"h2"]); + let listener = HttpTransport::bind("https://127.0.0.1:0/prices").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = + tokio::spawn(async move { receive_https_tables(&listener, server_config).await }); + + let base = format!("https://localhost:{port}"); + assert_eq!( + post_tls_status(&format!("{base}/missing"), client_config.clone()).await, + StatusCode::NOT_FOUND + ); + + send_https_table(&format!("{base}/prices"), client_config, 4).await; + assert_tables(&server.await.unwrap(), &[4]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_https_url_without_a_path_is_the_root_path() { + let (server_config, client_config) = make_tls_pair(&[b"h2"]); + let listener = HttpTransport::bind("https://127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = + tokio::spawn(async move { receive_https_tables(&listener, server_config).await }); + send_https_table(&format!("https://localhost:{port}/"), client_config, 2).await; + assert_tables(&server.await.unwrap(), &[2]); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_wss_accepting_writer_to_connecting_reader() { let (server_config, client_config) = make_tls_pair(&[]); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let listener = WebSocketTransport::bind("wss://127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -593,7 +1229,7 @@ mod tls_wires { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_https_connecting_writer_to_accepting_reader() { let (server_config, client_config) = make_tls_pair(&[b"h2"]); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let listener = HttpTransport::bind("https://127.0.0.1:0/ingest").await.unwrap(); let addr = listener.local_addr().unwrap(); let server = tokio::spawn(async move { From 9377f2921ddfb586556f7c5647a7567f99dd8b11 Mon Sep 17 00:00:00 2001 From: Peter Bower <37089506+pbower@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:45:38 +0000 Subject: [PATCH 2/4] Python accepting reads and writes on URL endpoints use the path-bound lightstream listeners --- python/README.md | 2 + python/examples/transport/wt/server.rs | 5 +- python/src/listeners.rs | 121 +++++++++++++++++-------- python/src/uri.rs | 80 ++++------------ python/tests/test_accept.py | 88 ++++++++++++++++++ python/tests/test_tls_wires.py | 59 ++++++++++++ 6 files changed, 251 insertions(+), 104 deletions(-) diff --git a/python/README.md b/python/README.md index 8502d0f..7c455bd 100644 --- a/python/README.md +++ b/python/README.md @@ -110,6 +110,8 @@ writer.close() The listener remains available for the lifetime of the process. Connections arriving while a serving loop is active wait in the listener backlog, allowing the accepting endpoint to operate as a persistent server. +For the `ws`, `wss`, `http`, `https` and `wt` schemes, the URL path is part of the endpoint. Accepting calls on `ws://0.0.0.0:9910/prices` and `ws://0.0.0.0:9910/trades` share the port, and each receives only the connections made to its own path. Connections to a path that no accepting call has bound are refused. A URL without a path is the path `/`. Endpoints on one host and port share a single TLS certificate, because TLS is established before the path is known. + ### TLS QUIC and WebTransport include TLS at the protocol level. The accepting endpoint presents a PEM certificate and private key, while the connecting endpoint verifies the certificate using PEM roots. diff --git a/python/examples/transport/wt/server.rs b/python/examples/transport/wt/server.rs index 4dced96..4650244 100644 --- a/python/examples/transport/wt/server.rs +++ b/python/examples/transport/wt/server.rs @@ -34,7 +34,10 @@ async fn serve() -> io::Result<()> { .parse() .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; let config = tls::wt_server(addr, &args::tls_cert(), &args::tls_key()).await?; - let listener = WebTransport::bind(config)?; + // WebTransport sessions are requested over HTTPS. The endpoint URL + // therefore uses the `https` scheme with the URI's authority and path. + let rest = uri.split_once("://").map_or(uri.as_str(), |(_, rest)| rest); + let listener = WebTransport::bind(&format!("https://{rest}"), config)?; let table = datagen::get_table(); let schema = datagen::schema(&table); println!("Serving get_table on {uri}"); diff --git a/python/src/listeners.rs b/python/src/listeners.rs index 6e76a0b..a90035e 100644 --- a/python/src/listeners.rs +++ b/python/src/listeners.rs @@ -12,10 +12,18 @@ //! loop keeps its endpoint continuously bound and clients queue in //! the listener's backlog while another connection is being served. //! +//! The ws, wss, http, https and wt endpoints are URLs, and each path is +//! its own endpoint. Their listeners are the lightstream listeners for +//! those transports, which share one socket between the paths of a +//! scheme and authority and return to each listener only the +//! connections made to its path. +//! //! Binds run under the registry lock, so threads opening the same //! endpoint at once resolve to one bound listener. The QUIC and //! WebTransport listeners carry the TLS identity given at first bind, //! and later accepting calls on the endpoint reuse that identity. +//! WebTransport paths on one authority share the identity of the +//! first path bound there. use std::collections::HashMap; #[cfg(unix)] @@ -28,18 +36,22 @@ use std::path::Path; use std::path::PathBuf; use std::sync::{Arc, Mutex, OnceLock}; +use lightstream::models::transports::http::{HttpListener, HttpTransport}; +use lightstream::models::transports::webtransport::{WebTransport, WebTransportListener}; +use lightstream::models::transports::websocket::{WebSocketListener, WebSocketTransport}; use pyo3::PyResult; use tokio::net::TcpListener; #[cfg(unix)] use tokio::net::UnixListener; -use wtransport::endpoint::endpoint_side::Server; use crate::errors::{TransportError, to_py_err}; use crate::tls; use lightstream::error::IoError; -/// One bound endpoint per scheme and authority. The scheme stays in -/// the key so listeners for different wires on the same port remain +/// One bound endpoint per scheme and address. The address is the +/// authority for TCP and QUIC, the socket path for UDS, and the +/// authority with the URL path for the URL endpoints. The scheme stays +/// in the key so listeners for different wires on the same port remain /// distinct bindings rather than sharing one accept queue. #[derive(Hash, PartialEq, Eq)] enum ListenerKey { @@ -58,8 +70,10 @@ enum BoundListener { Tcp(Arc), #[cfg(unix)] Uds(Arc), + Ws(Arc), + Http(Arc), Quic(Arc), - Wt(Arc>), + Wt(Arc), } static LISTENERS: OnceLock>> = OnceLock::new(); @@ -74,33 +88,28 @@ pub fn tcp(addr: &str) -> PyResult> { shared_tcp(ListenerKey::Tcp(addr.to_string()), addr) } -/// Returns the process-held listener for a `ws://` URL's authority, -/// binding it on the first call. Call within the runtime context. -pub fn ws(url: &str) -> PyResult> { - let authority = authority(url, "ws://"); - shared_tcp(ListenerKey::Ws(authority.to_string()), authority) +/// Returns the process-held listener for a `ws://` URL, binding it on +/// the first call. +pub async fn ws(url: &str) -> PyResult> { + shared_ws(ListenerKey::Ws(endpoint(url, "ws://")), url).await } -/// Returns the process-held listener for a `wss://` URL's authority, -/// binding it on the first call. Call within the runtime context. -pub fn wss(url: &str) -> PyResult> { - let authority = authority(url, "wss://"); - shared_tcp(ListenerKey::Wss(authority.to_string()), authority) +/// Returns the process-held listener for a `wss://` URL, binding it on +/// the first call. +pub async fn wss(url: &str) -> PyResult> { + shared_ws(ListenerKey::Wss(endpoint(url, "wss://")), url).await } -/// Returns the process-held listener for an `http://` URL's authority, -/// binding it on the first call. Call within the runtime context. -pub fn http(url: &str) -> PyResult> { - let authority = authority(url, "http://"); - shared_tcp(ListenerKey::Http(authority.to_string()), authority) +/// Returns the process-held listener for an `http://` URL, binding it +/// on the first call. +pub async fn http(url: &str) -> PyResult> { + shared_http(ListenerKey::Http(endpoint(url, "http://")), url).await } -/// Returns the process-held listener for an `https://` URL's -/// authority, binding it on the first call. Call within the runtime -/// context. -pub fn https(url: &str) -> PyResult> { - let authority = authority(url, "https://"); - shared_tcp(ListenerKey::Https(authority.to_string()), authority) +/// Returns the process-held listener for an `https://` URL, binding it +/// on the first call. +pub async fn https(url: &str) -> PyResult> { + shared_http(ListenerKey::Https(endpoint(url, "https://")), url).await } /// Returns the process-held UDS listener for the socket path, binding @@ -148,21 +157,18 @@ pub fn quic(authority: &str, cert: &Path, key: &Path) -> PyResult PyResult>> { - let key_entry = ListenerKey::Wt(authority.to_string()); +/// Returns the process-held WebTransport listener for a `wt://` URL +/// without its scheme, binding it with the given TLS identity on the +/// first call. Call within the runtime context. +pub async fn wt(address: &str, cert: &Path, key: &Path) -> PyResult> { + let key_entry = ListenerKey::Wt(endpoint(address, "")); { let map = registry().lock().expect("listener registry lock"); if let Some(BoundListener::Wt(listener)) = map.get(&key_entry) { return Ok(listener.clone()); } } + let authority = address.split('/').next().unwrap_or(address); let config = tls::wt_server(socket_addr(authority)?, cert, key) .await .map_err(|e| TransportError::new_err(e.to_string()))?; @@ -171,12 +177,45 @@ pub async fn wt( return Ok(listener.clone()); } let listener = Arc::new( - wtransport::Endpoint::server(config).map_err(|e| to_py_err(IoError::Io(e)))?, + WebTransport::bind(&format!("https://{address}"), config) + .map_err(|e| to_py_err(IoError::Io(e)))?, ); map.insert(key_entry, BoundListener::Wt(listener.clone())); Ok(listener) } +/// Looks the key up or binds the WebSocket URL, storing the listener +/// for the life of the process. +async fn shared_ws(key: ListenerKey, url: &str) -> PyResult> { + let mut map = registry().lock().expect("listener registry lock"); + if let Some(BoundListener::Ws(listener)) = map.get(&key) { + return Ok(listener.clone()); + } + let listener = Arc::new( + WebSocketTransport::bind(url) + .await + .map_err(|e| to_py_err(IoError::Io(e)))?, + ); + map.insert(key, BoundListener::Ws(listener.clone())); + Ok(listener) +} + +/// Looks the key up or binds the HTTP URL, storing the listener for the +/// life of the process. +async fn shared_http(key: ListenerKey, url: &str) -> PyResult> { + let mut map = registry().lock().expect("listener registry lock"); + if let Some(BoundListener::Http(listener)) = map.get(&key) { + return Ok(listener.clone()); + } + let listener = Arc::new( + HttpTransport::bind(url) + .await + .map_err(|e| to_py_err(IoError::Io(e)))?, + ); + map.insert(key, BoundListener::Http(listener.clone())); + Ok(listener) +} + /// Looks the key up or binds the authority, storing the listener for /// the life of the process. fn shared_tcp(key: ListenerKey, authority: &str) -> PyResult> { @@ -205,9 +244,13 @@ pub fn socket_addr(authority: &str) -> PyResult { }) } -/// Strips the scheme and any path from a URL, leaving the authority -/// the listener binds. -fn authority<'a>(url: &'a str, scheme: &str) -> &'a str { +/// Strips the scheme from a URL, leaving the authority and path that +/// identify the endpoint. A URL without a path has the path `/`. +fn endpoint(url: &str, scheme: &str) -> String { let rest = url.strip_prefix(scheme).unwrap_or(url); - rest.split('/').next().unwrap_or(rest) + if rest.contains('/') { + rest.to_string() + } else { + format!("{rest}/") + } } diff --git a/python/src/uri.rs b/python/src/uri.rs index 7fa3b7d..80a773d 100644 --- a/python/src/uri.rs +++ b/python/src/uri.rs @@ -606,10 +606,7 @@ pub fn resolve_source( // Lightstream TLV bytes ride inside WebSocket // binary frames, parsed by the WsRead adapter. if accept { - let listener = { - let _guard = runtime().enter(); - listeners::ws(url.as_str())? - }; + let listener = runtime().block_on(listeners::ws(url.as_str()))?; runtime() .block_on(async { let (read_half, write_half) = @@ -639,10 +636,7 @@ pub fn resolve_source( } Endpoint::Http(url) => { if accept { - let listener = { - let _guard = runtime().enter(); - listeners::http(url.as_str())? - }; + let listener = runtime().block_on(listeners::http(url.as_str()))?; runtime() .block_on(async { let (recv_read, mut send_write) = @@ -741,10 +735,7 @@ pub fn resolve_source( let key = tls_key.expect("validated above"); let config = tls::wss_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::wss(url.as_str())? - }; + let listener = runtime().block_on(listeners::wss(url.as_str()))?; runtime() .block_on(async { let (read_half, write_half) = @@ -783,10 +774,7 @@ pub fn resolve_source( let key = tls_key.expect("validated above"); let config = tls::https_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::https(url.as_str())? - }; + let listener = runtime().block_on(listeners::https(url.as_str()))?; runtime() .block_on(async { let (recv_read, mut send_write) = @@ -851,10 +839,7 @@ pub fn resolve_source( } Endpoint::Ws(url) => { if accept { - let listener = { - let _guard = runtime().enter(); - listeners::ws(url.as_str())? - }; + let listener = runtime().block_on(listeners::ws(url.as_str()))?; runtime() .block_on(WebSocketTableReader::accept(&listener, None)) } else { @@ -870,10 +855,7 @@ pub fn resolve_source( let key = tls_key.expect("validated above"); let config = tls::wss_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::wss(url.as_str())? - }; + let listener = runtime().block_on(listeners::wss(url.as_str()))?; runtime().block_on(async { let (read_half, write_half) = WebSocketTransport::accept_tls(&listener, config).await?; @@ -899,10 +881,7 @@ pub fn resolve_source( } Endpoint::Http(url) => { if accept { - let listener = { - let _guard = runtime().enter(); - listeners::http(url.as_str())? - }; + let listener = runtime().block_on(listeners::http(url.as_str()))?; runtime().block_on(HttpTableReader::accept(&listener, None)) } else { runtime().block_on(HttpTableReader::get(url.as_str(), None)) @@ -916,10 +895,7 @@ pub fn resolve_source( let key = tls_key.expect("validated above"); let config = tls::https_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::https(url.as_str())? - }; + let listener = runtime().block_on(listeners::https(url.as_str()))?; runtime().block_on(async { let (recv_read, send_write) = HttpTransport::accept_tls(&listener, config).await?; @@ -1343,10 +1319,7 @@ pub fn resolve_target( // Lightstream TLV bytes ride inside WebSocket // binary frames, built by the WsWrite adapter. if accept { - let listener = { - let _guard = runtime().enter(); - listeners::ws(url.as_str())? - }; + let listener = runtime().block_on(listeners::ws(url.as_str()))?; runtime() .block_on(async { let (_read_half, write_half) = @@ -1377,10 +1350,7 @@ pub fn resolve_target( // task, reaching its clean end without resetting // the h2 stream. if accept { - let listener = { - let _guard = runtime().enter(); - listeners::http(url.as_str())? - }; + let listener = runtime().block_on(listeners::http(url.as_str()))?; runtime() .block_on(async { let (mut recv_read, send_write) = @@ -1483,10 +1453,7 @@ pub fn resolve_target( let key = tls_key.expect("validated above"); let config = tls::wss_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::wss(url.as_str())? - }; + let listener = runtime().block_on(listeners::wss(url.as_str()))?; runtime() .block_on(async { let (_read_half, write_half) = @@ -1526,10 +1493,7 @@ pub fn resolve_target( let key = tls_key.expect("validated above"); let config = tls::https_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::https(url.as_str())? - }; + let listener = runtime().block_on(listeners::https(url.as_str()))?; runtime() .block_on(async { let (mut recv_read, send_write) = @@ -1609,10 +1573,7 @@ pub fn resolve_target( } Endpoint::Ws(url) => { let link = if accept { - let listener = { - let _guard = runtime().enter(); - listeners::ws(url.as_str())? - }; + let listener = runtime().block_on(listeners::ws(url.as_str()))?; let halves = runtime() .block_on(WebSocketTransport::accept(&listener)) .map_err(|e| to_py_err(IoError::Io(e)))?; @@ -1632,10 +1593,7 @@ pub fn resolve_target( let key = tls_key.expect("validated above"); let config = tls::wss_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::wss(url.as_str())? - }; + let listener = runtime().block_on(listeners::wss(url.as_str()))?; let halves = runtime() .block_on(WebSocketTransport::accept_tls(&listener, config)) .map_err(|e| to_py_err(IoError::Io(e)))?; @@ -1654,10 +1612,7 @@ pub fn resolve_target( } Endpoint::Http(url) => { let link = if accept { - let listener = { - let _guard = runtime().enter(); - listeners::http(url.as_str())? - }; + let listener = runtime().block_on(listeners::http(url.as_str()))?; let halves = runtime() .block_on(HttpTransport::accept(&listener)) .map_err(|e| to_py_err(IoError::Io(e)))?; @@ -1677,10 +1632,7 @@ pub fn resolve_target( let key = tls_key.expect("validated above"); let config = tls::https_server(Path::new(cert), Path::new(key)) .map_err(|e| TransportError::new_err(e.to_string()))?; - let listener = { - let _guard = runtime().enter(); - listeners::https(url.as_str())? - }; + let listener = runtime().block_on(listeners::https(url.as_str()))?; let halves = runtime() .block_on(HttpTransport::accept_tls(&listener, config)) .map_err(|e| to_py_err(IoError::Io(e)))?; diff --git a/python/tests/test_accept.py b/python/tests/test_accept.py index 62f505b..9e67e16 100644 --- a/python/tests/test_accept.py +++ b/python/tests/test_accept.py @@ -130,6 +130,94 @@ def test_http_arrow_accepting_reader(): run_accepting_reader(f"http://127.0.0.1:{free_port()}/ingest") +def read_path(uri, deadline=30.0, **options): + """Reads every batch an accepting writer sends on a URL path. + + Retries until the writer has bound the path. A request for a path + that is not yet bound is refused without being served, therefore a + retry never consumes another path's connection. + """ + end = time.monotonic() + deadline + while True: + try: + batches = list(ls.read(uri, **options)) + if batches: + return batches + except ls.LightstreamError: + if time.monotonic() > end: + raise + assert time.monotonic() < end, f"no batches arrived from {uri}" + time.sleep(0.05) + + +def run_accepting_writers_on_two_paths(base, **server_options): + """Serves a different table on `/prices` and `/trades` of one authority.""" + + def serve(path, offset): + writer = ls.write(f"{base}{path}", accept=True, **server_options) + writer.write(sample_table(offset)) + writer.close() + + threads = [ + threading.Thread(target=serve, args=(path, offset), daemon=True) + for path, offset in [("/prices", 0), ("/trades", 100)] + ] + for thread in threads: + thread.start() + return threads + + +def assert_two_paths_served(base, threads, **client_options): + trades = read_path(f"{base}/trades", **client_options) + prices = read_path(f"{base}/prices", **client_options) + for thread in threads: + thread.join(timeout=30) + assert not thread.is_alive() + assert [pa.table(b).to_pydict() for b in prices] == [sample_table(0).to_pydict()] + assert [pa.table(b).to_pydict() for b in trades] == [sample_table(100).to_pydict()] + + +def test_ws_accepting_writers_on_two_paths_serve_their_own_tables(): + base = f"ws://127.0.0.1:{free_port()}" + threads = run_accepting_writers_on_two_paths(base) + assert_two_paths_served(base, threads) + + +def test_http_accepting_writers_on_two_paths_serve_their_own_tables(): + base = f"http://127.0.0.1:{free_port()}" + threads = run_accepting_writers_on_two_paths(base) + assert_two_paths_served(base, threads) + + +def test_ws_accepting_readers_on_two_paths_receive_their_own_tables(): + base = f"ws://127.0.0.1:{free_port()}" + result = {} + + def serve(path): + result[path] = list(ls.read(f"{base}{path}", accept=True)) + + threads = [ + threading.Thread(target=serve, args=(path,), daemon=True) + for path in ["/prices", "/trades"] + ] + for thread in threads: + thread.start() + + # A write to a path that is not yet bound is refused, and the retry + # opens a new connection. + for path, offset in [("/trades", 100), ("/prices", 0)]: + writer = ls.write(f"{base}{path}") + with_retries(lambda: writer.write(sample_table(offset))) + writer.close() + for thread in threads: + thread.join(timeout=30) + assert not thread.is_alive() + assert [pa.table(b).to_pydict() for b in result["/prices"]] == [sample_table(0).to_pydict()] + assert [pa.table(b).to_pydict() for b in result["/trades"]] == [ + sample_table(100).to_pydict() + ] + + def test_tcp_lightstream_accepting_reader(): uri = f"tcp://127.0.0.1:{free_port()}" result = {} diff --git a/python/tests/test_tls_wires.py b/python/tests/test_tls_wires.py index 9c9c311..cb146a9 100644 --- a/python/tests/test_tls_wires.py +++ b/python/tests/test_tls_wires.py @@ -174,6 +174,65 @@ def test_https_accepting_reader(tls_pair): run_accepting_reader(f"https://127.0.0.1:{free_port()}/ingest", cert, key, ca) +def serve_two_paths(base, cert, key): + """Serves a different table on `/prices` and `/trades` of one authority.""" + + def serve(path, offset): + writer = ls.write(f"{base}{path}", accept=True, tls_cert=cert, tls_key=key) + writer.write(sample_table(offset)) + writer.close() + + threads = [ + threading.Thread(target=serve, args=(path, offset), daemon=True) + for path, offset in [("/prices", 0), ("/trades", 100)] + ] + for thread in threads: + thread.start() + return threads + + +def read_path(uri, ca, deadline=30.0): + """Reads every batch an accepting writer sends on a URL path, retrying + until the writer has bound the path.""" + end = time.monotonic() + deadline + while True: + try: + batches = list(ls.read(uri, tls_ca=ca)) + if batches: + return batches + except ls.LightstreamError: + if time.monotonic() > end: + raise + assert time.monotonic() < end, f"no batches arrived from {uri}" + time.sleep(0.05) + + +def run_two_paths(base, cert, key, ca): + threads = serve_two_paths(base, cert, key) + trades = read_path(f"{base}/trades", ca) + prices = read_path(f"{base}/prices", ca) + for thread in threads: + thread.join(timeout=30) + assert not thread.is_alive() + assert [pa.table(b).to_pydict() for b in prices] == [sample_table(0).to_pydict()] + assert [pa.table(b).to_pydict() for b in trades] == [sample_table(100).to_pydict()] + + +def test_wss_accepting_writers_on_two_paths_serve_their_own_tables(tls_pair): + cert, key, ca = tls_pair + run_two_paths(f"wss://127.0.0.1:{free_port()}", cert, key, ca) + + +def test_https_accepting_writers_on_two_paths_serve_their_own_tables(tls_pair): + cert, key, ca = tls_pair + run_two_paths(f"https://127.0.0.1:{free_port()}", cert, key, ca) + + +def test_webtransport_accepting_writers_on_two_paths_serve_their_own_tables(tls_pair): + cert, key, ca = tls_pair + run_two_paths(f"wt://127.0.0.1:{free_port()}", cert, key, ca) + + def test_wss_lightstream_round_trip(tls_pair): cert, key, ca = tls_pair uri = f"wss://127.0.0.1:{free_port()}" From f69aef5cd455a4a31a3e8023a5f50b7c30c00644 Mon Sep 17 00:00:00 2001 From: Peter Bower <37089506+pbower@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:45:38 +0000 Subject: [PATCH 3/4] Record the path-bound listeners in the changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5ead2..ac9da79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,9 +20,11 @@ Notable changes are recorded from 0.5.0 onward. - Renamed `TableStreamEncoder` to `TableEncoder`. - Renamed `models::decoders::ipc::table_stream_decoder` to `models::decoders::ipc::table_decoder`. - Renamed `models::encoders::ipc::table_stream` to `models::encoders::ipc::table_encoder`. +- `bind` on `WebSocketTransport`, `SyncWebSocketTransport`, `HttpTransport` and `WebTransport` now returns `WebSocketListener`, `SyncWebSocketListener`, `HttpListener` and `WebTransportListener`, which the transports' `accept` and `accept_tls`, the matching table readers and writers, and `Transport::Listener` now receive. `WebTransport::bind` now receives the endpoint URL ahead of its `ServerConfig`. ### Fixed +- WebSocket, HTTP/2 and WebTransport listeners now accept only the connections made to the path of the URL they were bound to. Several paths on one scheme, host and port share a socket within the process, connections to an unbound path are refused with status `404 Not Found`, and the Python crate's accepting reads and writes follow the same rules. Previously, a listener accepted connections for any path on its port. - `TableStreamWriter::finish` now writes the Stream protocol end-of-stream marker when no tables have been written. Empty streams previously didn't produce any bytes, which `TableReader` rejected as truncated. ## v0.8.0 27 Oct 2026 From 47e805273931b4e821538a2056798c449a6fdf28 Mon Sep 17 00:00:00 2001 From: Peter Bower <37089506+pbower@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:50:35 +0000 Subject: [PATCH 4/4] Reword the changelog entries for the path-bound listeners --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac9da79..6671bf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,11 +20,11 @@ Notable changes are recorded from 0.5.0 onward. - Renamed `TableStreamEncoder` to `TableEncoder`. - Renamed `models::decoders::ipc::table_stream_decoder` to `models::decoders::ipc::table_decoder`. - Renamed `models::encoders::ipc::table_stream` to `models::encoders::ipc::table_encoder`. -- `bind` on `WebSocketTransport`, `SyncWebSocketTransport`, `HttpTransport` and `WebTransport` now returns `WebSocketListener`, `SyncWebSocketListener`, `HttpListener` and `WebTransportListener`, which the transports' `accept` and `accept_tls`, the matching table readers and writers, and `Transport::Listener` now receive. `WebTransport::bind` now receives the endpoint URL ahead of its `ServerConfig`. +- `bind` on `WebSocketTransport`, `SyncWebSocketTransport`, `HttpTransport` and `WebTransport` now returns a listener type for that transport: `WebSocketListener`, `SyncWebSocketListener`, `HttpListener` and `WebTransportListener`. `accept` and `accept_tls` on those transports, and `accept` on their table readers and writers, receive that type in place of `TcpListener`. `WebTransport::bind` now receives the endpoint URL before its `ServerConfig`. ### Fixed -- WebSocket, HTTP/2 and WebTransport listeners now accept only the connections made to the path of the URL they were bound to. Several paths on one scheme, host and port share a socket within the process, connections to an unbound path are refused with status `404 Not Found`, and the Python crate's accepting reads and writes follow the same rules. Previously, a listener accepted connections for any path on its port. +- WebSocket, HTTP/2 and WebTransport listeners now accept only connections to the path of the URL they were bound with. Several paths on one host and port share a socket within the process, and a connection to a path that is not bound is refused with status `404 Not Found`. Accepting reads and writes in the Python crate follow the same rules. Previously, a listener accepted connections to any path on its port. - `TableStreamWriter::finish` now writes the Stream protocol end-of-stream marker when no tables have been written. Empty streams previously didn't produce any bytes, which `TableReader` rejected as truncated. ## v0.8.0 27 Oct 2026