Repository navigation
Conversation
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
6f43be5 to
19c9891
Compare
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
stefanvanburen
left a comment
There was a problem hiding this comment.
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).
| 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: |
There was a problem hiding this comment.
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 403sProbably just want to tuple(...) it once up front.
| 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: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
| value = value_bytes.decode() | ||
| if name in ("content-type", CONNECT_STREAMING_HEADER_COMPRESSION): | ||
| continue | ||
| if name.startswith("trailer-"): |
There was a problem hiding this comment.
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?
| # RPCs also use the streaming message flow. | ||
| if ( | ||
| isinstance(endpoint, EndpointUnary) | ||
| and not is_websocket |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
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>
47286c6 to
50a4198
Compare
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>
This comment was marked as resolved.
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>
…nto websockets-asgi
|
@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()) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…nto websockets-asgi
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
stefanvanburen
left a comment
There was a problem hiding this comment.
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}: |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
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.
|
@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: 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 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