Skip to content

Implement Connect-over-WebSockets - #466

Open
anuraaga wants to merge 31 commits into
connectrpc:mainfrom
anuraaga:websockets-asgi
Open

anuraaga wants to merge 31 commits into
connectrpc:mainfrom
anuraaga:websockets-asgi

Conversation

@anuraaga

Copy link
Copy Markdown
Collaborator

This implements the pending spec for websockets support in the ASGI server. It takes an approach of wrapping the websockets stream into the normal connect one, while we can consider an abstraction to use a more websockets-native control flow, I feel the wrapping approach works pretty well already.

connectrpc/connectrpc.com#452

@anuraaga
anuraaga marked this pull request as draft November 12, 2026 14:29
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
@anuraaga
anuraaga marked this pull request as ready for review November 12, 2026 14:37
@anuraaga
anuraaga requested a review from a team November 12, 2026 14:37
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>

@stefanvanburen stefanvanburen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took a pass against the RFC in connectrpc/connectrpc.com#452 — the websocket conformance suites at 63de2c4 pass for me locally on uvicorn, pyvoy, and pyvoy-trio (442/442 each), but a few things slip past them, inline. None of them are blocking IMO (the origin ones all fail closed), so approving; fine to fix here or follow up, whichever's easier.

Couple of RFC SHOULDs that I don't think need to block this, but ought to at least get a docs note: without connect-timeout-ms the wait for the client's M is unbounded (§11.2 wants a server deadline), and no_context_takeover (§10) is entirely up to the ASGI server's config, so I think users need to be told to set it (like server.py does for pyvoy / uvicorn).

Comment thread src/connectrpc/_server_async.py Outdated
self._compressions = resolve_compressions(compressions)
codecs = codecs if codecs is not None else get_default_codecs()
self._codecs = {codec.name(): codec for codec in codecs}
for pattern in websockets_allowed_origins:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

websockets_allowed_origins is iterated twice here, so a generator validates fine and then ends up as ():

app = HaberdasherASGIApplication(svc, websockets_allowed_origins=(o for o in ["app.example.org"]))
assert app._websockets_allowed_origins == ()  # every cross-origin handshake then 403s

Probably just want to tuple(...) it once up front.

Comment thread src/connectrpc/_server_async.py Outdated
self._compressions = resolve_compressions(compressions)
codecs = codecs if codecs is not None else get_default_codecs()
self._codecs = {codec.name(): codec for codec in codecs}
for pattern in websockets_allowed_origins:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I imagine folks will copy their CORS origins over here — "https://app.example.org" passes validation, but _origin_allowed only compares the authority so it can never match, and every handshake from that origin gets a 403. Maybe reject patterns containing :// (or /) with the same ValueError?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When looking at starlette's docs, I didn't think people generally include scheme. A validation error for it seems to make sense anyways though

Comment thread src/connectrpc/_server_websocket.py Outdated
value = value_bytes.decode()
if name in ("content-type", CONNECT_STREAMING_HEADER_COMPRESSION):
continue
if name.startswith("trailer-"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This stashes trailer-* headers on every response, but they only get sent back out in _send_error_end, so on a 200 they're just dropped. e.g. a handler setting ctx.response_headers["trailer-id"] = "x" on MakeHat gives ['M{}', 'B{"size":10}', 'S{}']. Admittedly an edge case (and trailer- is already ambiguous for Connect unary), but I think it should only strip them when _error_status is set?

Comment thread src/connectrpc/_server_async.py Outdated
# RPCs also use the streaming message flow.
if (
isinstance(endpoint, EndpointUnary)
and not is_websocket

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On trio, routing unary through _call_stream means the disconnect watch only sets the flag (the asyncio watch always cancels), so a unary handler blocked on something slow runs to completion after the client goes away — in a quick test with a 2s sleep and a 1001 disconnect, the handler ran the full 2s on trio, cancelled immediately on asyncio. Same as gRPC unary on trio today I think, so not new, but §8 does say the server MUST treat it as cancelled. Maybe pass cancel=True to the watch when the endpoint is unary?

def _stream_error(
state: _StreamState, close_code: int, code: Code, message: str
) -> ConnectError:
state.close_code = close_code

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting close_code here, when the error is created rather than when it ends the RPC, means a client-stream / bidi handler that catches the request error and returns normally still gets a 1009 (or 1002 / 1003) close after a successful S{}. Repro: MakeFlexibleHat that does try: async for _ in request: ... except ConnectError: pass, read_max_bytes=8, and an oversized B → S{} then close 1009. §13 only has those codes after an S carrying the error, so I think the send adapter ought to only use the override close code when the S actually has an error.

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
@anuraaga

Copy link
Copy Markdown
Collaborator Author

Couple of RFC SHOULDs that I don't think need to block this, but ought to at least get a docs note:

Yup I think we'll want to add these to Deployment in the connectrpc.com docs

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
…nto websockets-asgi

# Conflicts:
#	conformance/test/gen/connectrpc/conformance/v1/service_connect.py
#	connectrpc-grpchealth/connectrpc_grpchealth/_gen/grpc/health/v1/health_connect.py
#	connectrpc-grpcreflect/connectrpc_grpcreflect/_gen/grpc/reflection/v1/reflection_connect.py
#	connectrpc-grpcreflect/connectrpc_grpcreflect/_gen/grpc/reflection/v1alpha/reflection_connect.py
#	connectrpc-grpcreflect/test/connectrpc/example/deprecated_connect.py
#	connectrpc-grpcreflect/test/connectrpc/example/empty_connect.py
#	connectrpc-grpcreflect/test/connectrpc/example/haberdasher_connect.py
#	example/example/gen/connectrpc/eliza/v1/eliza_connect.py
#	protoc-gen-connectrpc/protoc_gen_connectrpc/__init__.py
#	src/connectrpc/_protocol_connect.py
#	src/connectrpc/_protocol_grpc.py
#	src/connectrpc/_server_async.py
#	test/connectrpc/example/deprecated_connect.py
#	test/connectrpc/example/empty_connect.py
#	test/connectrpc/example/haberdasher_connect.py
#	test/google_compat/connectrpc/example/deprecated_connect.py
#	test/google_compat/connectrpc/example/empty_connect.py
#	test/google_compat/connectrpc/example/haberdasher_connect.py
#	test/test_server_protocols.py
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
@anuraaga

This comment was marked as resolved.

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
@anuraaga

anuraaga commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

@stefanvanburen There have been some larger changes to this. Can you take another quick look? Thanks!

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
http_scope["path"] = path
http_scope["scheme"] = "https" if scope.get("scheme") == "wss" else "http"
http_scope["headers"] = [
(name.encode(), value.encode())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a -bin value can still crash this after we've accepted: the field-value check in _parse_leading_metadata skips -bin keys, so M[["x-custom-bin","\ud800"]] (with x-custom-bin allowed) gets a lone surrogate through, and value.encode() here raises UnicodeEncodeError: surrogates not allowed. Under uvicorn that's a 1011 with no M/S, rather than S internal + 1002.

Probably simplest to .encode() the values during parsing; UnicodeEncodeError is a ValueError, so the existing except (TypeError, ValueError) would turn it into the protocol error. (The RFC says not to reject invalid base64 at parse time, but I'd think a value that isn't even encodable is fair game.)

timeout: The maximum time to handle a request in seconds. A request from the
client with a shorter timeout uses the client's timeout. If unset,
requests are only limited by the client's timeout.
websocket_allowed_origins: Origins permitted to open cross-origin

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we can't control permessage-deflate from the app, I think we ought to at least tell people how to configure their server for §10. With uvicorn's defaults (ws=auto → websockets-sansio, ws_per_message_deflate=True), it negotiates deflate without no_context_takeover, so uvicorn app:app with ProtocolType.WEBSOCKET breaks that MUST out of the box. The conformance runner turns it off (--ws-per-message-deflate=false, and websockets_compression_no_context_takeover=True for pyvoy), but users won't know to.

Same deal for §12: read_max_bytes is only checked after the server has buffered and decompressed the whole message (16 MiB by default in uvicorn), so the server's own limit (--ws-max-size etc.) ought to match it, like the runner does.

Fine with this living in the Deployment docs you mentioned rather than here, as long as it lands before a release. Even a line in this docstring pointing there would help.

protocols are served.
protocols: The protocols the server serves. If unset, the Connect,
gRPC, and gRPC-Web protocols are served.
timeout: The maximum time to handle a request in seconds. A request from the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RFC now says a server SHOULD have its own timeout and SHOULD default it generously (§11.2), mostly so a client that upgrades and never sends M can't hold the connection forever. With timeout=None that's what happens here. Maybe default a long timeout for WebSocket streams only? Or at least call it out in this docstring. No strong feelings on which.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we'll consider this in the deployment docs too, i.e. pyvoy's idle timeout may behave better than an overall request timeout.

compressions: Iterable[Compression] | None = None,
codecs: Iterable[Codec] | None = None,
protocols: Iterable[ProtocolType] | None = None,
protocols: Iterable[HTTPProtocolType] | None = None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: HaberdasherWSGIApplication(svc, protocols=[ProtocolType.WEBSOCKET]) constructs fine and then 415s every request with an empty Accept-Post. Might be nice to raise a ValueError here, like the clients now do.

Comment thread src/connectrpc/_server_async.py Outdated
codecs = codecs if codecs is not None else get_default_codecs()
self._codecs = {codec.name(): codec for codec in codecs}
self._protocols = resolve_protocols(protocols)
self._websocket_allowed_origins = frozenset(websocket_allowed_origins)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: websocket_allowed_origins="https://app.example.com" type-checks (a str is an Iterable[str]) and ends up as {'h', 't', 'p', ...}, and websocket_allowed_headers has the same problem. Probably worth a TypeError for a bare str, since it's an easy mistake to make and it fails quietly.


headers: dict[str, list[str]] = {}
for name_bytes, value_bytes in scope.get("headers", ()):
headers.setdefault(name_bytes.decode().lower(), []).append(value_bytes.decode())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not new here (_process_headers does the same thing on the HTTP path), but .decode() on handshake headers means a non-UTF-8 byte (e.g. cookie: a=\xe9) raises UnicodeDecodeError before we accept, and nothing gets sent. I think latin-1 is what ASGI servers expect here. Happy to file it separately rather than fix it in this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah left this unaddressed for now. I thought the existing behavior would be fine since connect protocol specifies header values as ascii, so we should actually reject those headers.

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>

@stefanvanburen stefanvanburen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM; CI is red though, since the pinned runner (f67cffa) still sends unary/server-stream over WebSocket and those now get unimplemented. Ought to either bump the pin once conformance#1200 has a commit that only sends client-stream/bidi, or add --known-failing patterns for **/Protocol:PROTOCOL_CONNECT_WEBSOCKET/**/unary/** and **/server-stream/** in the meantime. Few nits inline, none blocking.

# to the server as it is too late for us to be able to do anything.
async with (timeout := loop.timeout_at(None)):
try:
if not is_websocket and self._protocols == {ProtocolType.WEBSOCKET}:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: with protocols=[ProtocolType.WEBSOCKET] any unary/server-stream methods end up unreachable (426 over plain HTTP, unimplemented over the upgrade), and nothing tells you. Probably ought to at least call that out in the protocols docstring, or warn/raise if the service has those method kinds.


def resolve_allowed_origins(origins: Iterable[str]) -> frozenset[str]:
"""Validate the origins permitted to open cross-origin streams."""
if isinstance(origins, str):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: since this is an exact string match against Origin, something like https://app.example.com/ (trailing slash) or an upper-cased host never matches and the handshake just 403s with no hint why. Maybe validate entries are * or scheme://host[:port] (or lowercase them), a la resolve_allowed_headers?

):
msg = f"metadata key '{key}' is reserved"
raise ValueError(msg)
if key.endswith("-bin"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: -bin values skip _INVALID_FIELD_VALUE_RE entirely, so an allow-listed -bin key can carry CR/LF/NUL into the scope headers and ctx.request_headers. Fine to keep accepting invalid base64, but I think we still ought to reject control characters here.

@timostamm

Copy link
Copy Markdown
Member

@anuraaga, I opened anuraaga#21 against this branch. It updates the conformance tests to connectrpc/conformance#1212, the tests for WebSocket streaming as specified in connectrpc/connectrpc.com#470. The update pins the head of connectrpc/conformance#1212, so CI here should pass again.

On the API: ProtocolType.WEBSOCKET is still a fourth protocol, but connectrpc/connectrpc.com#470 defines WebSocket streaming as part of the Connect protocol. connect-go and connect-rust have a separate option to enable it. Can you do the same here?

Can you also rename the PR to "Add support for WebSocket streaming"? That's the term from the spec, and I'm renaming the other PRs too. The description still links connectrpc/connectrpc.com#452. It should mention:

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants