forked from connectrpc/connect-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_server_async.py
More file actions
667 lines (592 loc) · 25 KB
/
_server_async.py
File metadata and controls
667 lines (592 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
from __future__ import annotations
import base64
import contextlib
import functools
import inspect
from abc import ABC, abstractmethod
from asyncio import CancelledError, Event, create_task, sleep
from dataclasses import replace
from http import HTTPStatus
from typing import TYPE_CHECKING, Generic, TypeVar, cast
from urllib.parse import parse_qs
from ._codec import Codec, get_default_codecs
from ._compression import negotiate_compression, resolve_compressions
from ._envelope import EnvelopeReader
from ._interceptor_async import (
BidiStreamInterceptor,
ClientStreamInterceptor,
Interceptor,
ServerStreamInterceptor,
UnaryInterceptor,
resolve_interceptors,
)
from ._protocol import ConnectWireError, HTTPException, ServerProtocol
from ._protocol_connect import CONNECT_UNARY_CONTENT_TYPE_PREFIX, ConnectServerProtocol
from ._protocol_server import negotiate_server_protocol
from ._server_shared import (
EndpointBidiStream,
EndpointClientStream,
EndpointServerStream,
EndpointUnary,
)
from .code import Code
from .errors import ConnectError
from .request import Headers, RequestContext
if TYPE_CHECKING:
# We don't use asgiref code so only import from it for type checking
from collections.abc import (
AsyncGenerator,
AsyncIterator,
Callable,
Iterable,
Mapping,
Sequence,
)
from asgiref.typing import ASGIReceiveCallable, ASGISendCallable, HTTPScope, Scope
from . import _server_shared
from .compression import Compression
else:
ASGIReceiveCallable = "asgiref.typing.ASGIReceiveCallable"
ASGISendCallable = "asgiref.typing.ASGISendCallable"
HTTPScope = "asgiref.typing.HTTPScope"
Scope = "asgiref.typing.Scope"
_SVC = TypeVar("_SVC")
_REQ = TypeVar("_REQ")
_RES = TypeVar("_RES")
# We don't mutate query params so use a singleton for when they're not set.
_UNSET_QUERY_PARAMS: dict[str, list[str]] = {}
# While _server_shared.Endpoint is a closed type, we can't indicate that to Python so define
# a more precise type here.
Endpoint = (
EndpointBidiStream[_REQ, _RES]
| EndpointClientStream[_REQ, _RES]
| EndpointServerStream[_REQ, _RES]
| EndpointUnary[_REQ, _RES]
)
class ConnectASGIApplication(ABC, Generic[_SVC]):
"""An ASGI application for the Connect protocol."""
_resolved_endpoints: Mapping[str, Endpoint] | None
@property
@abstractmethod
def path(self) -> str: ...
def __init__(
self,
*,
service: _SVC | AsyncGenerator[_SVC],
endpoints: Callable[[_SVC], Mapping[str, Endpoint]],
interceptors: Iterable[Interceptor] = (),
read_max_bytes: int | None = None,
compressions: Iterable[Compression] | None = None,
codecs: Iterable[Codec] | None = None,
) -> None:
"""Initialize the ASGI application.
Args:
service: The service instance or async generator that yields the service during lifespan.
endpoints: A callable that takes the service instance and returns a mapping of URL
paths to endpoints. Typically provided directly by generated code from the
Connect Python plugin.
interceptors: A sequence of interceptors to apply to the endpoints.
read_max_bytes: Maximum size of request messages.
compressions: Supported compression algorithms. If unset, defaults to gzip.
If set to empty, disables compression.
codecs: The codecs supported by the server. If unset, defaults to Protocol Buffers
binary and JSON codecs.
"""
super().__init__()
self._service = service
self._endpoints = endpoints
self._interceptors = interceptors
self._resolved_endpoints = None
self._read_max_bytes = read_max_bytes
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}
async def __call__(
self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
if scope["type"] == "websocket":
msg = "connect does not support websockets"
raise RuntimeError(msg)
if scope["type"] == "lifespan":
service_iter = None
while True:
msg = await receive()
match msg["type"]:
case "lifespan.startup":
# Need to cast since type checking doesn't seem to narrow well with isasyncgen
if inspect.isasyncgen(self._service):
service_iter = cast(
"AsyncGenerator[_SVC, None]", self._service
)
try:
service = await anext(service_iter)
except Exception as e:
await send(
{
"type": "lifespan.startup.failed",
"message": str(e),
}
)
return None
else:
service = cast("_SVC", self._service)
self._resolved_endpoints = self._resolve_endpoints(service)
await send({"type": "lifespan.startup.complete"})
case "lifespan.shutdown":
if service_iter is not None:
try:
await service_iter.aclose()
except Exception as e:
await send(
{
"type": "lifespan.shutdown.failed",
"message": str(e),
}
)
return None
await send({"type": "lifespan.shutdown.complete"})
return None
if not self._resolved_endpoints:
if inspect.isasyncgen(self._service):
msg = "ASGI server does not support lifespan but async generator passed for service. Enable lifespan support."
raise RuntimeError(msg)
self._resolved_endpoints = self._resolve_endpoints(
cast("_SVC", self._service)
)
endpoints = self._resolved_endpoints
ctx: RequestContext | None = None
try:
path = scope["path"]
endpoint = endpoints.get(path)
if not endpoint and scope["root_path"]:
# The application was mounted at some root so try stripping the prefix.
path = path.removeprefix(scope["root_path"])
endpoint = endpoints.get(path)
if not endpoint:
raise HTTPException(HTTPStatus.NOT_FOUND, [])
http_method = scope["method"]
http_scheme = scope.get("scheme", "http")
headers = _process_headers(scope.get("headers", ()))
client_address = f"{ca[0]}:{ca[1]}" if (ca := scope.get("client")) else None
content_type = headers.get("content-type", "")
protocol = negotiate_server_protocol(content_type)
if protocol.uses_trailers() and "http.response.trailers" not in cast(
"dict", scope.get("extensions", {})
):
msg = f"ASGI server does not support ASGI trailers extension but protocol for content-type '{content_type}' requires trailers"
raise RuntimeError(msg)
ctx = protocol.create_request_context(
endpoint.method, http_method, http_scheme, headers, client_address
)
is_unary = isinstance(endpoint, EndpointUnary)
if http_method == "GET":
query_string = scope.get("query_string", b"").decode("utf-8")
query_params = parse_qs(query_string, keep_blank_values=True)
codec_name = query_params.get("encoding", ("",))[0]
else:
query_params = _UNSET_QUERY_PARAMS
codec_name = protocol.codec_name_from_content_type(
headers.get("content-type", ""), stream=not is_unary
)
codec = self._codecs.get(codec_name.lower())
if not codec:
raise HTTPException(
HTTPStatus.UNSUPPORTED_MEDIA_TYPE,
[("Accept-Post", "application/json, application/proto")],
)
if is_unary and isinstance(protocol, ConnectServerProtocol):
return await self._handle_unary_connect(
http_method,
headers,
codec,
query_params,
endpoint,
receive,
send,
ctx,
)
except Exception as e:
await self._handle_error(e, ctx, send)
if not isinstance(e, (ConnectError, HTTPException)):
raise
return None
# Streams have their own error handling so move out of the try block.
return await self._handle_stream(
receive, send, protocol, endpoint, codec, headers, ctx
)
async def _handle_unary_connect(
self,
http_method: str,
headers: Headers,
codec: Codec,
query_params: dict[str, list[str]],
endpoint: EndpointUnary[_REQ, _RES],
receive: ASGIReceiveCallable,
send: ASGISendCallable,
ctx: RequestContext,
) -> None:
accept_encoding = headers.get("accept-encoding", "")
compression = negotiate_compression(accept_encoding, self._compressions)
if http_method == "GET":
request = await self._read_get_request(endpoint, codec, query_params)
else:
request = await self._read_post_request(endpoint, receive, codec, headers)
response_data = await endpoint.function(request, ctx)
res_bytes = codec.encode(response_data)
response_headers: list[tuple[bytes, bytes]] = [
(
b"content-type",
f"{CONNECT_UNARY_CONTENT_TYPE_PREFIX}{codec.name()}".encode(),
)
]
res_bytes = compression.compress(res_bytes)
response_headers.append((b"content-encoding", compression.name().encode()))
response_headers.append((b"vary", b"Accept-Encoding"))
_add_context_headers(response_headers, ctx)
await send(
{
"type": "http.response.start",
"status": 200,
"headers": response_headers,
"trailers": False,
}
)
await send(
{"type": "http.response.body", "body": res_bytes, "more_body": False}
)
async def _read_get_request(
self,
endpoint: EndpointUnary[_REQ, _RES],
codec: Codec,
params: dict[str, list[str]],
) -> _REQ:
"""Handle GET request with query parameters."""
# Validation
if "message" not in params:
raise ConnectError(
Code.INVALID_ARGUMENT,
"'message' parameter is required for GET requests",
)
# Get and decode message
message = params["message"][0]
is_base64 = "base64" in params and params["base64"][0] == "1"
if is_base64:
try:
message = base64.urlsafe_b64decode(message + "===")
except Exception as e:
raise ConnectError(
Code.INVALID_ARGUMENT, "Invalid base64 encoding"
) from e
else:
message = message.encode("utf-8")
# Handle compression
compression_name = params.get("compression", ["identity"])[0]
compression = self._compressions.get(compression_name)
if not compression:
raise ConnectError(
Code.UNIMPLEMENTED,
f"unknown compression: '{compression_name}': supported encodings are {', '.join(self._compressions.keys())}",
)
# Decompress and decode message
if message: # Don't decompress empty messages
message = compression.decompress(message)
# Get the appropriate decoder for the endpoint
return codec.decode(message, endpoint.method.input())
async def _read_post_request(
self,
endpoint: Endpoint[_REQ, _RES],
receive: ASGIReceiveCallable,
codec: Codec,
headers: Headers,
) -> _REQ:
"""Handle POST request with body."""
# Get request body
chunks: list[bytes] = [chunk async for chunk in _read_body(receive)]
req_body = b"".join(chunks)
# Handle compression if specified
compression_name = headers.get("content-encoding", "identity").lower()
compression = self._compressions.get(compression_name)
if not compression:
raise ConnectError(
Code.UNIMPLEMENTED,
f"unknown compression: '{compression_name}': supported encodings are {', '.join(self._compressions.keys())}",
)
if req_body: # Don't decompress empty body
req_body = compression.decompress(req_body)
if self._read_max_bytes is not None and len(req_body) > self._read_max_bytes:
raise ConnectError(
Code.RESOURCE_EXHAUSTED,
f"message is larger than configured max {self._read_max_bytes}",
)
return codec.decode(req_body, endpoint.method.input())
async def _handle_stream(
self,
receive: ASGIReceiveCallable,
send: ASGISendCallable,
protocol: ServerProtocol,
endpoint: Endpoint[_REQ, _RES],
codec: Codec,
headers: Headers,
ctx: _server_shared.RequestContext,
) -> None:
req_compression, resp_compression = protocol.negotiate_stream_compression(
headers, self._compressions
)
writer = protocol.create_envelope_writer(codec, resp_compression)
error: Exception | None = None
sent_headers = False
try:
if not req_compression:
raise ConnectError(
Code.UNIMPLEMENTED, "Unrecognized request compression"
)
request_stream = _request_stream(
receive,
endpoint.method.input,
codec,
req_compression,
self._read_max_bytes,
)
disconnect_detected: Event | None = None
monitor_task = None
match endpoint:
case EndpointUnary():
request = await _consume_single_request(request_stream)
response = await endpoint.function(request, ctx)
response_stream = _yield_single_response(response)
case EndpointClientStream():
response = await endpoint.function(request_stream, ctx)
response_stream = _yield_single_response(response)
case EndpointServerStream():
request = await _consume_single_request(request_stream)
response_stream = endpoint.function(request, ctx)
# The request has been fully consumed; monitor receive() for a
# client disconnect so we can stop streaming promptly.
disconnect_detected = Event()
async def _watch_for_disconnect() -> None:
while True:
msg = await receive()
if msg["type"] == "http.disconnect":
disconnect_detected.set()
return
monitor_task = create_task(_watch_for_disconnect())
case EndpointBidiStream():
response_stream = endpoint.function(request_stream, ctx)
try:
async for message in response_stream:
if disconnect_detected is not None and disconnect_detected.is_set():
raise ConnectError(Code.CANCELED, "Client disconnected")
# Don't send headers until the first message to allow logic a chance to add
# response headers.
if not sent_headers:
await _send_stream_response_headers(
send, protocol, codec, resp_compression.name(), ctx
)
sent_headers = True
body = writer.write(message)
await send(
{"type": "http.response.body", "body": body, "more_body": True}
)
finally:
# Cancel the monitor first so a throwing generator finally-block
# doesn't leak the task.
if monitor_task is not None:
monitor_task.cancel()
with contextlib.suppress(CancelledError):
await monitor_task
# Explicitly close the stream so that any generator finally-blocks
# run promptly (Python defers async-generator cleanup to GC otherwise).
aclose = getattr(response_stream, "aclose", None)
if aclose is not None:
await aclose()
except CancelledError as e:
raise ConnectError(Code.CANCELED, "Request was cancelled") from e
except Exception as e:
error = e
finally:
end_message = writer.end(
ctx.response_trailers(),
ConnectWireError.from_exception(error) if error else None,
)
if not sent_headers:
# Exception before any response message is returned
await _send_stream_response_headers(
send, protocol, codec, resp_compression.name(), ctx
)
if isinstance(end_message, bytes):
await send(
{
"type": "http.response.body",
"body": end_message,
"more_body": False,
}
)
else:
await send(
{"type": "http.response.body", "body": b"", "more_body": False}
)
await send(
{
"type": "http.response.trailers",
"headers": [
(k.encode(), v.encode()) for k, v in end_message.allitems()
],
"more_trailers": False,
}
)
if error and not isinstance(error, ConnectError):
raise error
async def _handle_error(
self, exc: Exception, ctx: RequestContext | None, send: ASGISendCallable
) -> None:
"""Handle errors that occur during request processing."""
headers: list[tuple[bytes, bytes]]
body: bytes
status: int
if isinstance(exc, HTTPException):
status = exc.status.value
headers = [(k.encode("utf-8"), v.encode("utf-8")) for k, v in exc.headers]
body = b""
else:
wire_error = ConnectWireError.from_exception(exc)
status = wire_error.to_http_status().code
headers = [(b"content-type", b"application/json")]
body = wire_error.to_json_bytes()
if ctx:
_add_context_headers(headers, ctx)
await send(
{
"type": "http.response.start",
"status": status,
"headers": headers,
"trailers": False,
}
)
await send({"type": "http.response.body", "body": body, "more_body": False})
def _resolve_endpoints(self, service: _SVC) -> Mapping[str, Endpoint]:
resolved_endpoints = self._endpoints(service)
if self._interceptors:
resolved_endpoints = {
path: _apply_interceptors(
endpoint, resolve_interceptors(self._interceptors)
)
for path, endpoint in resolved_endpoints.items()
}
return resolved_endpoints
async def _send_stream_response_headers(
send: ASGISendCallable,
protocol: ServerProtocol,
codec: Codec,
compression_name: str,
ctx: RequestContext,
) -> None:
response_headers = [
(b"content-type", protocol.content_type(codec).encode()),
(protocol.compression_header_name().encode(), compression_name.encode()),
]
response_headers.extend(
(key.encode(), value.encode())
for key, value in ctx.response_headers().allitems()
)
await send(
{
"type": "http.response.start",
"status": 200,
"headers": response_headers,
"trailers": protocol.uses_trailers(),
}
)
async def _request_stream(
receive: ASGIReceiveCallable,
request_class: type[_REQ],
codec: Codec,
compression: Compression,
read_max_bytes: int | None = None,
) -> AsyncIterator[_REQ]:
reader = EnvelopeReader(request_class, codec, compression, read_max_bytes)
try:
async for chunk in _read_body(receive):
for message in reader.feed(chunk):
yield message
# Check for cancellation each message. While this seems heavyweight,
# conformance tests require it.
await sleep(0)
except CancelledError as e:
raise ConnectError(Code.CANCELED, "Request was cancelled") from e
async def _read_body(receive: ASGIReceiveCallable) -> AsyncIterator[bytes]:
"""Read the body of the request."""
while True:
message = await receive()
match message["type"]:
case "http.request":
body = message.get("body", b"")
yield body
if not message.get("more_body", False):
return
case "http.disconnect":
raise ConnectError(
Code.CANCELED, "Client disconnected before request completion"
)
case _:
raise ConnectError(Code.UNKNOWN, "Unexpected message type")
async def _consume_single_request(stream: AsyncIterator[_REQ]) -> _REQ:
req = None
async for message in stream:
if req is not None:
raise ConnectError(
Code.UNIMPLEMENTED, "unary request has multiple messages"
)
req = message
if req is None:
raise ConnectError(Code.UNIMPLEMENTED, "unary request has zero messages")
return req
async def _yield_single_response(response: _RES) -> AsyncIterator[_RES]:
yield response
def _process_headers(iterable: Iterable[tuple[bytes, bytes]]) -> Headers:
result = Headers()
for key, value in iterable:
result.add(key.decode(), value.decode())
return result
def _add_context_headers(
headers: list[tuple[bytes, bytes]], ctx: RequestContext
) -> None:
headers.extend(
(key.encode(), value.encode())
for key, value in ctx.response_headers().allitems()
)
headers.extend(
(f"trailer-{key}".encode(), value.encode())
for key, value in ctx.response_trailers().allitems()
)
def _apply_interceptors(
endpoint: Endpoint[_REQ, _RES], interceptors: Sequence[Interceptor]
) -> Endpoint[_REQ, _RES]:
match endpoint:
case EndpointUnary():
func = endpoint.function
for interceptor in reversed(interceptors):
if not isinstance(interceptor, UnaryInterceptor):
continue
func = functools.partial(interceptor.intercept_unary, func)
return replace(endpoint, function=func)
case EndpointClientStream():
func = endpoint.function
for interceptor in reversed(interceptors):
if not isinstance(interceptor, ClientStreamInterceptor):
continue
func = functools.partial(interceptor.intercept_client_stream, func)
return replace(endpoint, function=func)
case EndpointServerStream():
func = endpoint.function
for interceptor in reversed(interceptors):
if not isinstance(interceptor, ServerStreamInterceptor):
continue
func = functools.partial(interceptor.intercept_server_stream, func)
return replace(endpoint, function=func)
case EndpointBidiStream():
func = endpoint.function
for interceptor in reversed(interceptors):
if not isinstance(interceptor, BidiStreamInterceptor):
continue
func = functools.partial(interceptor.intercept_bidi_stream, func)
return replace(endpoint, function=func)