pub struct WebSocketDispatcher { /* private fields */ }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
impl WebSocketDispatcher
Sourcepub fn with_serve_config(self, config: ServeConfig) -> WebSocketDispatcher
Available on crate feature websocket only.
pub fn with_serve_config(self, config: ServeConfig) -> WebSocketDispatcher
websocket only.Takes the listener settings Server takes
(ADR 0052), for serve_with_shutdown,
replacing the ones set so far.
Applied, as on Server:
max_connections: the permit is taken beforeaccept()and held for the whole connection; on the HTTP port (WebSocketUpgrades) it caps the upgrades.0is refused when the listener starts.idle_timeout: the dispatcher’s idle bound, which sends a Ping at half the budget, so it closes a peer that stops answering and not a quiet subscription (seewith_idle_timeout, which sets the same field; the later call wins).ServeConfig’s default, 75 s, isDEFAULT_WS_IDLE_TIMEOUT.completion_grace,task_grace,drain_timeoutanddrain_delay: the shutdown, in the orderserve_with_shutdowndescribes.production, withtls_terminated_in_front: the listener refuses to start on plaintextws://beyond loopback (unlesswith_tlsis set) and on a card that declares no WebSocket interface, and says so inServeReport::refused.
Not applied:
header_read_timeout:with_handshake_timeout(10 s by default) bounds the whole upgrade, TLS included.allowed_hostsandhost_check: theOrigincheck (with_allowed_origins) is what refuses a browser page, which is what DNS rebinding needs.
Source§impl WebSocketDispatcher
impl WebSocketDispatcher
Sourcepub async fn serve_with_shutdown(
self: Arc<WebSocketDispatcher>,
listener: TcpListener,
shutdown: impl Future<Output = ()> + Send,
) -> ServeReport
Available on crate feature websocket only.
pub async fn serve_with_shutdown( self: Arc<WebSocketDispatcher>, listener: TcpListener, shutdown: impl Future<Output = ()> + Send, ) -> ServeReport
websocket only.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:
- 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.
- End in-flight tasks with
RequestHandler::finish_in_flight: up toServeConfig::completion_gracefor them to finish on their own, then their cancellation tokens fire and executors getServeConfig::task_graceto act on it. A subscription whose task ends gets its terminal event. - Close the connections. Each stops reading, lets the requests it
already read finish, and sends a Close frame — for up to
ServeConfig::drain_timeoutin 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
impl WebSocketDispatcher
Sourcepub const fn new(handler: Arc<RequestHandler>) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn new(handler: Arc<RequestHandler>) -> WebSocketDispatcher
websocket only.Creates a new WebSocket dispatcher.
Sourcepub const fn with_agent_card_max_age(self, seconds: u32) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn with_agent_card_max_age(self, seconds: u32) -> WebSocketDispatcher
websocket only.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.
Sourcepub fn with_tls(self, config: ServerConfig) -> WebSocketDispatcher
Available on crate features tls-rustls and websocket only.
pub fn with_tls(self, config: ServerConfig) -> WebSocketDispatcher
tls-rustls and websocket 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.
Sourcepub fn with_tls_pem(
self,
cert_chain: &[u8],
key: &[u8],
) -> Result<WebSocketDispatcher, Error>
Available on crate features tls-rustls and websocket only.
pub fn with_tls_pem( self, cert_chain: &[u8], key: &[u8], ) -> Result<WebSocketDispatcher, Error>
tls-rustls and websocket 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.
Sourcepub fn with_allowed_origins<I, S>(self, origins: I) -> WebSocketDispatcher
Available on crate feature websocket only.
pub fn with_allowed_origins<I, S>(self, origins: I) -> WebSocketDispatcher
websocket only.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.
Sourcepub fn allow_any_origin(self) -> WebSocketDispatcher
Available on crate feature websocket only.
pub fn allow_any_origin(self) -> WebSocketDispatcher
websocket only.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.
Sourcepub fn require_origin(self) -> WebSocketDispatcher
Available on crate feature websocket only.
pub fn require_origin(self) -> WebSocketDispatcher
websocket only.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.
Sourcepub const fn accept_missing_version_header(self) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn accept_missing_version_header(self) -> WebSocketDispatcher
websocket only.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.
Sourcepub const fn with_handshake_timeout(
self,
timeout: Duration,
) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn with_handshake_timeout( self, timeout: Duration, ) -> WebSocketDispatcher
websocket only.Overrides the handshake timeout (default: 10 seconds).
A peer that does not complete the WebSocket handshake within this bound is disconnected.
Sourcepub 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
Available on crate feature websocket only.
pub const fn with_max_connections(self, max: usize) -> WebSocketDispatcher
use with_serve_config(ServeConfig::new().with_max_connections(max)); removed no earlier than 0.17.0
websocket only.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.
Sourcepub const fn with_idle_timeout(self, timeout: Duration) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn with_idle_timeout(self, timeout: Duration) -> WebSocketDispatcher
websocket only.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.
Sourcepub const fn without_idle_timeout(self) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn without_idle_timeout(self) -> WebSocketDispatcher
websocket only.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.
Sourcepub const fn with_write_timeout(self, timeout: Duration) -> WebSocketDispatcher
Available on crate feature websocket only.
pub const fn with_write_timeout(self, timeout: Duration) -> WebSocketDispatcher
websocket only.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.
Sourcepub 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
Available on crate feature websocket only.
pub const fn with_completion_grace(self, grace: Duration) -> WebSocketDispatcher
use with_serve_config(ServeConfig::new().with_completion_grace(grace)); removed no earlier than 0.17.0
websocket only.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.
Sourcepub 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
Available on crate feature websocket only.
pub const fn with_task_grace(self, grace: Duration) -> WebSocketDispatcher
use with_serve_config(ServeConfig::new().with_task_grace(grace)); removed no earlier than 0.17.0
websocket only.How long cancelled tasks get to act on their cancellation before the
connections are closed. Default
DEFAULT_TASK_GRACE.
Sourcepub 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
Available on crate feature websocket only.
pub const fn with_drain_timeout(self, timeout: Duration) -> WebSocketDispatcher
use with_serve_config(ServeConfig::new().with_drain_timeout(timeout)); removed no earlier than 0.17.0
websocket only.How long serve_with_shutdown waits for
connections to close once they have been told to. Default
DEFAULT_DRAIN_TIMEOUT.
Sourcepub 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
Available on crate feature websocket only.
pub async fn serve( self: Arc<WebSocketDispatcher>, addr: impl ToSocketAddrs, ) -> Result<(), Error>
it cannot be stopped: bind a TcpListener and use serve_with_shutdown; removed no earlier than 0.17.0
websocket only.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.
Sourcepub 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
Available on crate feature websocket only.
pub async fn serve_with_addr( self: Arc<WebSocketDispatcher>, addr: impl ToSocketAddrs, ) -> Result<SocketAddr, Error>
it cannot be stopped: bind a TcpListener and use serve_with_shutdown; removed no earlier than 0.17.0
websocket only.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§
Auto Trait Implementations§
impl !RefUnwindSafe for WebSocketDispatcher
impl !UnwindSafe for WebSocketDispatcher
impl Forget for WebSocketDispatcher
impl Freeze for WebSocketDispatcher
impl Move for WebSocketDispatcher
impl Send for WebSocketDispatcher
impl Sync for WebSocketDispatcher
impl Unpin for WebSocketDispatcher
impl UnsafeUnpin for WebSocketDispatcher
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].