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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 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
Expand Down
2 changes: 2 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion python/examples/transport/wt/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand Down
121 changes: 82 additions & 39 deletions python/src/listeners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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 {
Expand All @@ -58,8 +70,10 @@ enum BoundListener {
Tcp(Arc<TcpListener>),
#[cfg(unix)]
Uds(Arc<UnixListener>),
Ws(Arc<WebSocketListener>),
Http(Arc<HttpListener>),
Quic(Arc<quinn::Endpoint>),
Wt(Arc<wtransport::Endpoint<Server>>),
Wt(Arc<WebTransportListener>),
}

static LISTENERS: OnceLock<Mutex<HashMap<ListenerKey, BoundListener>>> = OnceLock::new();
Expand All @@ -74,33 +88,28 @@ pub fn tcp(addr: &str) -> PyResult<Arc<TcpListener>> {
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<Arc<TcpListener>> {
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<Arc<WebSocketListener>> {
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<Arc<TcpListener>> {
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<Arc<WebSocketListener>> {
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<Arc<TcpListener>> {
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<Arc<HttpListener>> {
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<Arc<TcpListener>> {
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<Arc<HttpListener>> {
shared_http(ListenerKey::Https(endpoint(url, "https://")), url).await
}

/// Returns the process-held UDS listener for the socket path, binding
Expand Down Expand Up @@ -148,21 +157,18 @@ pub fn quic(authority: &str, cert: &Path, key: &Path) -> PyResult<Arc<quinn::End
Ok(listener)
}

/// Returns the process-held WebTransport endpoint for the authority,
/// binding it with the given TLS identity on the first call. Call
/// within the runtime context.
pub async fn wt(
authority: &str,
cert: &Path,
key: &Path,
) -> PyResult<Arc<wtransport::Endpoint<Server>>> {
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<Arc<WebTransportListener>> {
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()))?;
Expand All @@ -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<Arc<WebSocketListener>> {
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<Arc<HttpListener>> {
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<Arc<TcpListener>> {
Expand Down Expand Up @@ -205,9 +244,13 @@ pub fn socket_addr(authority: &str) -> PyResult<net::SocketAddr> {
})
}

/// 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}/")
}
}
Loading
Loading