Skip to main content

WebSocketDispatcher

Struct WebSocketDispatcher 

Source
pub struct WebSocketDispatcher { /* private fields */ }
Available on crate feature websocket only.
Expand description

WebSocket-based A2A dispatcher.

Accepts WebSocket connections and processes JSON-RPC 2.0 messages over the WebSocket channel. Streaming responses are sent as individual text frames.

Incoming messages are capped at 4 MiB at the WebSocket protocol level; a connection sending a larger message or frame is terminated.

§Authentication, tenancy, and headers

The HTTP headers of the upgrade request that establishes the connection (lowercased, plus the request path under ":path") are captured during the handshake and passed to the handler for every request on the connection. Tenant resolvers and interceptors therefore see the same header context they would on the HTTP bindings — credentials are presented once, at connect time, and apply to the whole connection.

An upgrade request with no A2A-Version (header or ?A2A-Version= parameter), or one naming a version other than 1.0 (a patch number is ignored), is rejected during the handshake with HTTP 400; accept_missing_version_header admits the former.

§TLS and origins

The listener is plaintext (ws://) unless with_tls is set, which makes it wss:// only (spec §7.1 “Production deployments MUST use encrypted communication”). It refuses an upgrade from a browser (one that carries an Origin) unless with_allowed_origins names that origin, and accepts one without an Origin, as clients that are not browsers send; allow_any_origin accepts every origin.

Implementations§

Source§

impl WebSocketDispatcher

Source

pub fn with_serve_config(self, config: ServeConfig) -> WebSocketDispatcher

Takes the listener settings Server takes (ADR 0052), for serve_with_shutdown, replacing the ones set so far.

Applied, as on Server:

Not applied:

Source§

impl WebSocketDispatcher

Source

pub async fn serve_with_shutdown( self: Arc<WebSocketDispatcher>, listener: TcpListener, shutdown: impl Future<Output = ()> + Send, ) -> ServeReport

Serves until shutdown resolves, then ends the work in flight and closes the connections, in the order Server::serve_with_shutdown uses for the HTTP bindings:

  1. Stop accepting. The listener is closed. Open connections keep being read, and requests on them admitted, through step 2 — the same as the HTTP server.
  2. End in-flight tasks with RequestHandler::finish_in_flight: up to ServeConfig::completion_grace for them to finish on their own, then their cancellation tokens fire and executors get ServeConfig::task_grace to act on it. A subscription whose task ends gets its terminal event.
  3. Close the connections. Each stops reading, lets the requests it already read finish, and sends a Close frame — for up to ServeConfig::drain_timeout in all.

With a drain_delay, the handler’s readiness turns to “draining” when the signal fires and the listener goes on accepting for the delay before step 1. The settings are with_serve_config’s; a listener that refuses to start under them returns at once with ServeReport::refused saying why.

A WebSocket is one long-lived connection carrying many requests, so unlike HTTP it has no natural end between requests: without step 3 a client that stays connected would hold the drain open until its deadline.

It takes a bound listener so the caller knows the address — port 0 included — before serving starts. Call RequestHandler::shutdown after it returns.

Source§

impl WebSocketDispatcher

Source

pub const fn new(handler: Arc<RequestHandler>) -> WebSocketDispatcher

Creates a new WebSocket dispatcher.

Source

pub const fn with_agent_card_max_age(self, seconds: u32) -> WebSocketDispatcher

Sets the Cache-Control: max-age, in seconds, this listener serves the agent card with (spec §8.6.1: “appropriate for the agent’s expected update frequency”). Default 3600, as DispatchConfig::with_agent_card_max_age for the HTTP dispatchers. Until 2026-10-23 it was 3600 here, fixed.

Source

pub fn with_tls(self, config: ServerConfig) -> WebSocketDispatcher

Available on crate feature tls-rustls only.

Serves wss://: every connection is a TLS handshake first, with config’s certificate. Default: plaintext ws://.

The listener then speaks TLS only; a plaintext client fails the handshake and is closed. When config names no ALPN protocols, http/1.1 is offered, the only one a WebSocket upgrade runs on here. The handshake must finish within with_handshake_timeout, and the WebSocket upgrade then gets the same again. The agent card is served over the same TLS session (spec §8.1).

config is used as built, client authentication included. For a certificate and key in PEM files, with_tls_pem builds one. Requires the tls-rustls feature.

Source

pub fn with_tls_pem( self, cert_chain: &[u8], key: &[u8], ) -> Result<WebSocketDispatcher, Error>

Available on crate feature tls-rustls only.

with_tls with a server certificate chain (leaf first) and its private key (PKCS#8, PKCS#1 or SEC1), both PEM, under rustls’ safe defaults on the ring provider, as Server::with_tls_pem builds them.

§Errors

std::io::ErrorKind::InvalidInput when cert_chain holds no certificate, either PEM does not parse, or the key is not the certificate’s.

Source

pub fn with_allowed_origins<I, S>(self, origins: I) -> WebSocketDispatcher
where I: IntoIterator<Item = S>, S: Into<String>,

Accepts an upgrade whose Origin header is one of origins, and refuses any other with HTTP 403 during the handshake. Default: no origin is listed, so every browser is refused.

A browser sends Origin on every WebSocket upgrade and cannot forge it, and the handshake carries the browser’s cookies, and WebSocket is outside CORS: a listener that accepted any origin let every page a user visited open a connection carrying the user’s credentials and read the answers (cross-site WebSocket hijacking; audit SEC-03, the default until this release). It does nothing against a client that is not a browser, which can send any Origin or none; authenticate those with an interceptor.

Origins are compared whole and without regard to ASCII case, as serialised by the browser: scheme, host and a port only when it is not the scheme’s default, with no path or trailing slash (https://app.example.com, http://localhost:8080). An upgrade with no Origin is still accepted, as non-browser clients send none; require_origin refuses those too.

Source

pub fn allow_any_origin(self) -> WebSocketDispatcher

Accepts an upgrade from any origin, as this listener did before it refused browsers by default. Only for a listener no browser can reach with credentials worth taking, or one that authenticates every call with something a page cannot send (not a cookie); prefer with_allowed_origins.

Source

pub fn require_origin(self) -> WebSocketDispatcher

Refuses an upgrade that carries no Origin header, with HTTP 403. Default: accepted.

For a listener only browsers should reach. Every browser sends Origin on a WebSocket upgrade; most other clients, this SDK’s included, do not.

Source

pub const fn accept_missing_version_header(self) -> WebSocketDispatcher

Accepts upgrade requests without an A2A-Version header.

Spec §3.6.2 interprets a missing/empty header as protocol 0.3, which this server does not implement, so the strict default rejects such handshakes (parity with the HTTP dispatchers). This opt-out restores the tolerant pre-0.7 behavior.

Source

pub const fn with_handshake_timeout( self, timeout: Duration, ) -> WebSocketDispatcher

Overrides the handshake timeout (default: 10 seconds).

A peer that does not complete the WebSocket handshake within this bound is disconnected.

Source

pub const fn with_max_connections(self, max: usize) -> WebSocketDispatcher

👎Deprecated since 0.16.0:

use with_serve_config(ServeConfig::new().with_max_connections(max)); removed no earlier than 0.17.0

Caps the connections served at once. Default: unbounded.

Without this the accept loop spawns a task per accepted socket with no ceiling, exactly as serve did before ServeConfig existed. Measured on 2026-08-19: 400 idle handshaken connections were accepted and held, none refused, the ceiling being the process’s file-descriptor table.

The permit is taken before accept(), so load past the ceiling waits in the kernel’s listen backlog and is refused by the kernel when that fills — a far better failure than an unbounded task spawn that turns a traffic spike into an OOM.

Unbounded stays the default for the same reason it does on ServeConfig::max_connections: a deployment may genuinely want no ceiling, and picking one for it is picking its capacity.

Source

pub const fn with_idle_timeout(self, timeout: Duration) -> WebSocketDispatcher

Closes a connection that carries no traffic in either direction for timeout. Default: off.

with_handshake_timeout bounds a peer that connects and never upgrades. Nothing bounded the peer that completes the handshake and then goes silent, so one that did held a task, a socket and a file descriptor for the life of the process — measured, a connection idle for 12 seconds was still being served, and the read loop has no bound at all.

§Why this is off by default when the HTTP one is on

Default: DEFAULT_WS_IDLE_TIMEOUT (75 s) since 0.16.0; it was off until then (audit D-20, ADR 0042). without_idle_timeout turns it off.

On HTTP, silence means nothing is happening. On a WebSocket it may mean a subscription is waiting for its next event, which is a legitimate thing to do for hours, so a plain idle timeout would close healthy subscriptions.

What makes it safe on by default: at the halfway point of the budget the server sends a WebSocket Ping. Every conformant client library — this SDK’s included, via tungstenite — answers automatically, and that Pong is traffic. So the timeout closes peers that are unresponsive, not peers that are merely quiet. Only a client that has stopped reading its socket, or gone away without a close frame, fails to answer.

Outbound frames count too, so a stream pushing events to a silent consumer keeps its own connection alive.

Source

pub const fn without_idle_timeout(self) -> WebSocketDispatcher

Turns the idle bound off: a peer that goes away without a close frame keeps its connection, and its slot, until the TCP stack notices, which takes hours by default.

Source

pub const fn with_write_timeout(self, timeout: Duration) -> WebSocketDispatcher

How long one frame may take to be written before the connection is closed as having a peer that stopped reading (default DEFAULT_WS_WRITE_TIMEOUT, 30 s; audit D-07).

A write to a peer whose receive window is full waits for the peer, and until 2026-11-01 nothing bounded the wait: the connection’s sink stayed held, the read loop stalled behind it on its next reply, and neither the idle bound nor a shutdown was ever evaluated again. At the bound the connection is closed, its running requests are cancelled, and its slot is returned. Keep it above the slowest legitimate consumer of one frame.

Source

pub const fn with_completion_grace(self, grace: Duration) -> WebSocketDispatcher

👎Deprecated since 0.16.0:

use with_serve_config(ServeConfig::new().with_completion_grace(grace)); removed no earlier than 0.17.0

How long in-flight tasks get to finish on their own once serve_with_shutdown’s signal fires, before they are cancelled. Default DEFAULT_COMPLETION_GRACE; the HTTP server’s ServeConfig::with_completion_grace is the same setting.

Source

pub const fn with_task_grace(self, grace: Duration) -> WebSocketDispatcher

👎Deprecated since 0.16.0:

use with_serve_config(ServeConfig::new().with_task_grace(grace)); removed no earlier than 0.17.0

How long cancelled tasks get to act on their cancellation before the connections are closed. Default DEFAULT_TASK_GRACE.

Source

pub const fn with_drain_timeout(self, timeout: Duration) -> WebSocketDispatcher

👎Deprecated since 0.16.0:

use with_serve_config(ServeConfig::new().with_drain_timeout(timeout)); removed no earlier than 0.17.0

How long serve_with_shutdown waits for connections to close once they have been told to. Default DEFAULT_DRAIN_TIMEOUT.

Source

pub async fn serve( self: Arc<WebSocketDispatcher>, addr: impl ToSocketAddrs, ) -> Result<(), Error>

👎Deprecated since 0.16.0:

it cannot be stopped: bind a TcpListener and use serve_with_shutdown; removed no earlier than 0.17.0

Starts a WebSocket server on the given address.

The accept loop never terminates on transient accept() errors (per-connection aborts, fd-table exhaustion) — it logs, backs off when the fd table is full, and keeps accepting.

It takes no shutdown signal; use serve_with_shutdown for a graceful stop.

§Errors

Returns std::io::Error if the TCP listener fails to bind.

Source

pub async fn serve_with_addr( self: Arc<WebSocketDispatcher>, addr: impl ToSocketAddrs, ) -> Result<SocketAddr, Error>

👎Deprecated since 0.16.0:

it cannot be stopped: bind a TcpListener and use serve_with_shutdown; removed no earlier than 0.17.0

Starts a WebSocket server and returns the bound address.

Like serve, but useful for tests (bind to port 0).

§Errors

Returns std::io::Error if the TCP listener fails to bind.

Trait Implementations§

Source§

impl Debug for WebSocketDispatcher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. 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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

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

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

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<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

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

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