Skip to main content

SharedWebSocketServer

Struct SharedWebSocketServer 

Source
pub struct SharedWebSocketServer { /* private fields */ }
Expand description

Cheap, cloneable handle to a WebSocketServer’s per-connection configuration, produced by WebSocketServer::into_shared.

into_shared builds the connection configuration (router, hooks, capacities) exactly once; cloning a SharedWebSocketServer is an Arc clone. The handle is Send + Sync + 'static, so it drops straight into a per-connection tokio::spawn(async move { shared.serve_connection(ws).await }) — the shape an embedder needs to share one TCP port between REPE WebSocket upgrades and its own HTTP routes.

Implementations§

Source§

impl SharedWebSocketServer

Source

pub async fn accept( &self, stream: TcpStream, path: &str, ) -> Result<WebSocketStream<TcpStream>, RepeError>

Perform the REPE WebSocket handshake using this server’s configured WebSocketLimits.

Prefer this over the associated WebSocketServer::accept in an embedder-owned accept loop. That one takes no self, so it cannot see a builder-set with_limits and accepts with the defaults instead: the limits would appear to be configured and silently not be.

Source

pub async fn accept_with_handshake( &self, stream: TcpStream, path: &str, ) -> Result<(WebSocketStream<TcpStream>, HandshakeContext), RepeError>

accept, also returning the upgrade’s HandshakeContext.

Source

pub fn limits(&self) -> WebSocketLimits

This server’s size limits, for an embedder that upgrades the stream through some path of its own and needs to configure it to match.

Source

pub async fn adopt_upgraded<S>(&self, io: S) -> WebSocketStream<S>
where S: AsyncRead + AsyncWrite + Unpin,

Wrap the raw IO of a connection another HTTP stack already upgraded into a server-role WebSocketStream carrying this server’s configured WebSocketLimits, ready for serve_connection.

This is the seam for an embedder whose HTTP routes live in a framework (axum, hyper, tower) rather than in a hand-written accept loop. Such an embedder already owns a Router with its own paths on it and wants the REPE endpoint to be one more route, answering the 101 through the framework’s own upgrade machinery. The peek-then-fork recipe (is_websocket_upgrade + accept) cannot serve that shape, because it requires repe to own the TcpStream before any HTTP is parsed. Here the framework keeps the socket, performs the handshake, and hands back the upgraded byte stream — which is what io is.

The caller is responsible for the handshake itself: validating Upgrade/Connection/Sec-WebSocket-Version and answering 101 with the derive_accept_key of the client’s Sec-WebSocket-Key. Frameworks that expose the upgrade as an extractor do that part; derive_accept_key is provided for those that hand back the raw request. Path validation is the caller’s too — the framework already routed the request here, which is the counterpart to the path argument WebSocketServer::accept takes.

Nothing is read from io before the first REPE frame, so a stream whose handshake produced garbage surfaces as a protocol error on that connection alone. The other failure shape is quieter: if the client is still waiting for a 101 that never came, neither side speaks, and repe applies no read timeout or idle deadline — the framework’s own upgrade timeout is what bounds that.

To name the returned type in your own signatures, the transport crate is re-exported as repe::tokio_tungstenite; call sites that pass the value straight to serve_connection never need to.

This call is where the connection’s inbound thresholds are fixed — they cannot be changed afterwards — which is precisely why it exists rather than leaving embedders to call the transport’s from_raw_socket themselves and silently substitute its defaults for the limits the server was built with. The outbound guard travels with the server config and applies on every path.

Source

pub async fn adopt_upgraded_partially_read<S>( &self, io: S, buffered: Vec<u8>, ) -> WebSocketStream<S>
where S: AsyncRead + AsyncWrite + Unpin,

adopt_upgraded for a framework that hands back the bytes it read past the upgrade request separately from the stream, as (io, buffered).

A client may legally pipeline its first frame with the upgrade request, so those bytes can be real REPE traffic. hyper hides this — its Upgraded replays what it buffered — but a framework that returns the two halves separately needs somewhere to put them, and dropping them loses a frame. Pass them here and they are decoded ahead of anything read from io.

Prefer adopt_upgraded when the stream already replays its own leftovers; passing buffered bytes that io will also yield would double-decode them.

Source

pub async fn serve_connection<S>( &self, ws: WebSocketStream<S>, ) -> Result<(), RepeError>
where S: AsyncRead + AsyncWrite + Unpin + Send + 'static,

Run one connection’s reader/writer loop using this server’s router, hooks, and capacities. Pair with WebSocketServer::accept to serve a stream the embedder accepted and upgraded itself.

Generic over the underlying byte stream, so the connection need not have come from a TcpStream this crate accepted. A stream some other HTTP stack upgraded — an axum/hyper route that answered the 101 itself — is served by wrapping its upgraded IO with adopt_upgraded and passing the result here.

Connect/disconnect hooks (and any PeerRegistry attached via WebSocketServer::with_peer_registry) fire for connections served this way, exactly as under WebSocketServer::serve.

The connection’s off-reader handlers see their cancellation signal (CallContext::is_cancelled / CallContext::cancelled) fire on disconnect. To also fire it on an embedder-driven shutdown, use serve_connection_with_cancel.

Source

pub async fn serve_connection_with_handshake<S>( &self, ws: WebSocketStream<S>, handshake: HandshakeContext, ) -> Result<(), RepeError>
where S: AsyncRead + AsyncWrite + Unpin + Send + 'static,

Like serve_connection, but threads the HandshakeContext from WebSocketServer::accept_with_handshake through so on_peer_connect_with_handshake hooks fire for this connection. For a one-port co-hosting embedder that keys peers off the upgrade request.

Source

pub async fn serve_connection_with_cancel<S>( &self, ws: WebSocketStream<S>, shutdown: &ShutdownToken, ) -> Result<(), RepeError>
where S: AsyncRead + AsyncWrite + Unpin + Send + 'static,

Like serve_connection, but ties this connection’s cancellation signal to a shared ShutdownToken as well as to disconnect.

For a one-port co-hosting embedder that owns its accept loop: create one ShutdownToken, serve each connection through this method, and call ShutdownToken::cancel on shutdown to wake every connection’s in-flight off-reader handlers at once while you drain your own task set. The connection’s token is a child of the shared one, so cancelling the shared token cancels every connection, and a single connection’s disconnect cancels only its own child.

Source

pub async fn serve_connection_with_cancel_and_handshake<S>( &self, ws: WebSocketStream<S>, handshake: HandshakeContext, shutdown: &ShutdownToken, ) -> Result<(), RepeError>
where S: AsyncRead + AsyncWrite + Unpin + Send + 'static,

serve_connection_with_cancel plus the captured HandshakeContext — the union of co-hosting, embedder-driven drain, and handshake-keyed peers. Cancelling the shared ShutdownToken winds the connection’s in-flight off-reader handlers down, and on_peer_connect_with_handshake hooks fire from the captured handshake.

Trait Implementations§

Source§

impl Clone for SharedWebSocketServer

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<R> IntoTypedResponse<R> for R

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more