/
proxy.py
1488 lines (1300 loc) · 56.2 KB
/
proxy.py
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import logging
import os
import pickle
import socket
import time
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Type
import grpc
import starlette
import starlette.routing
import uvicorn
from packaging import version
from starlette.datastructures import MutableHeaders
from starlette.middleware import Middleware
from starlette.types import Receive
import ray
from ray import serve
from ray._private.utils import get_or_create_event_loop
from ray.actor import ActorHandle
from ray.exceptions import RayActorError, RayTaskError
from ray.serve._private.common import (
DeploymentID,
EndpointInfo,
NodeId,
RequestProtocol,
)
from ray.serve._private.constants import (
DEFAULT_LATENCY_BUCKET_MS,
DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S,
PROXY_MIN_DRAINING_PERIOD_S,
RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH,
SERVE_CONTROLLER_NAME,
SERVE_LOGGER_NAME,
SERVE_MULTIPLEXED_MODEL_ID,
SERVE_NAMESPACE,
)
from ray.serve._private.grpc_util import DummyServicer, create_serve_grpc_server
from ray.serve._private.http_util import (
MessageQueue,
convert_object_to_asgi_messages,
receive_http_body,
set_socket_reuse_port,
validate_http_proxy_callback_return,
)
from ray.serve._private.logging_utils import (
access_log_msg,
configure_component_cpu_profiler,
configure_component_logger,
configure_component_memory_profiler,
get_component_logger_file_path,
)
from ray.serve._private.long_poll import LongPollClient, LongPollNamespace
from ray.serve._private.proxy_request_response import (
ASGIProxyRequest,
HandlerMetadata,
ProxyRequest,
ResponseGenerator,
ResponseHandlerInfo,
ResponseStatus,
gRPCProxyRequest,
)
from ray.serve._private.proxy_response_generator import ProxyResponseGenerator
from ray.serve._private.proxy_router import (
EndpointRouter,
LongestPrefixRouter,
ProxyRouter,
)
from ray.serve._private.usage import ServeUsageTag
from ray.serve._private.utils import call_function_from_import_path, generate_request_id
from ray.serve.config import gRPCOptions
from ray.serve.exceptions import BackPressureError
from ray.serve.generated.serve_pb2 import HealthzResponse, ListApplicationsResponse
from ray.serve.generated.serve_pb2_grpc import add_RayServeAPIServiceServicer_to_server
from ray.serve.handle import DeploymentHandle
from ray.serve.schema import LoggingConfig
from ray.util import metrics
logger = logging.getLogger(SERVE_LOGGER_NAME)
HTTP_REQUEST_MAX_RETRIES = int(os.environ.get("RAY_SERVE_HTTP_REQUEST_MAX_RETRIES", 10))
assert HTTP_REQUEST_MAX_RETRIES >= 0, (
f"Got unexpected value {HTTP_REQUEST_MAX_RETRIES} for "
"RAY_SERVE_HTTP_REQUEST_MAX_RETRIES environment variable. "
"RAY_SERVE_HTTP_REQUEST_MAX_RETRIES cannot be negative."
)
TIMEOUT_ERROR_CODE = "timeout"
DISCONNECT_ERROR_CODE = "disconnection"
SOCKET_REUSE_PORT_ENABLED = (
os.environ.get("SERVE_SOCKET_REUSE_PORT_ENABLED", "1") == "1"
)
RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S = int(
os.environ.get("RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S", 0)
)
# TODO (shrekris-anyscale): Deprecate SERVE_REQUEST_PROCESSING_TIMEOUT_S env var
RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S = (
float(os.environ.get("RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0))
or float(os.environ.get("SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0))
or None
)
# Controls whether Ray Serve is operating in debug-mode switching off some
# of the performance optimizations to make troubleshooting easier
RAY_SERVE_DEBUG_MODE = bool(os.environ.get("RAY_SERVE_DEBUG_MODE", 0))
if os.environ.get("SERVE_REQUEST_PROCESSING_TIMEOUT_S") is not None:
logger.warning(
"The `SERVE_REQUEST_PROCESSING_TIMEOUT_S` environment variable has "
"been deprecated. Please set `request_timeout_s` in your Serve config's "
"`http_options` field instead. `SERVE_REQUEST_PROCESSING_TIMEOUT_S` will be "
"ignored in future versions. See: https://docs.ray.io/en/releases-2.5.1/serve/a"
"pi/doc/ray.serve.schema.HTTPOptionsSchema.html#ray.serve.schema.HTTPOptionsSch"
"ema.request_timeout_s"
)
INITIAL_BACKOFF_PERIOD_SEC = 0.05
MAX_BACKOFF_PERIOD_SEC = 5
HEALTHY_MESSAGE = "success"
DRAINING_MESSAGE = "This node is being drained."
NO_ROUTES_MESSAGE = "Route table is not populated yet."
class GenericProxy(ABC):
"""This class is served as the base class for different types of proxies.
It contains all the common setup and methods required for running a proxy.
The proxy subclass need to implement the following methods:
- `protocol()`
- `not_found_response()`
- `routes_response()`
- `health_response()`
- `setup_request_context_and_handle()`
- `send_request_to_replica()`
"""
def __init__(
self,
node_id: NodeId,
node_ip_address: str,
proxy_router_class: Type[ProxyRouter],
request_timeout_s: Optional[float] = None,
):
self.request_timeout_s = request_timeout_s
if self.request_timeout_s is not None and self.request_timeout_s < 0:
self.request_timeout_s = None
self._node_id = node_id
# Flipped to `True` once the route table has been updated at least once.
# Health checks will not pass until the route table is populated.
self._route_table_populated = False
# Used only for displaying the route table.
self.route_info: Dict[str, DeploymentID] = dict()
self.proxy_router = proxy_router_class(
partial(serve.get_deployment_handle, _record_telemetry=False), self.protocol
)
self.request_counter = metrics.Counter(
f"serve_num_{self.protocol.lower()}_requests",
description=f"The number of {self.protocol} requests processed.",
tag_keys=("route", "method", "application", "status_code"),
)
self.request_error_counter = metrics.Counter(
f"serve_num_{self.protocol.lower()}_error_requests",
description=f"The number of errored {self.protocol} responses.",
tag_keys=(
"route",
"error_code",
"method",
"application",
),
)
self.deployment_request_error_counter = metrics.Counter(
f"serve_num_deployment_{self.protocol.lower()}_error_requests",
description=(
f"The number of errored {self.protocol} "
"responses returned by each deployment."
),
tag_keys=(
"deployment",
"error_code",
"method",
"route",
"application",
),
)
self.processing_latency_tracker = metrics.Histogram(
f"serve_{self.protocol.lower()}_request_latency_ms",
description=(
f"The end-to-end latency of {self.protocol} requests "
f"(measured from the Serve {self.protocol} proxy)."
),
boundaries=DEFAULT_LATENCY_BUCKET_MS,
tag_keys=(
"method",
"route",
"application",
"status_code",
),
)
self.num_ongoing_requests_gauge = metrics.Gauge(
name=f"serve_num_ongoing_{self.protocol.lower()}_requests",
description=f"The number of ongoing requests in this {self.protocol} "
"proxy.",
tag_keys=("node_id", "node_ip_address"),
).set_default_tags(
{
"node_id": node_id,
"node_ip_address": node_ip_address,
}
)
# `self._ongoing_requests` is used to count the number of ongoing requests
self._ongoing_requests = 0
# The time when the node starts to drain.
# The node is not draining if it's None.
self._draining_start_time: Optional[float] = None
getattr(ServeUsageTag, f"{self.protocol.upper()}_PROXY_USED").record("1")
@property
@abstractmethod
def protocol(self) -> RequestProtocol:
"""Protocol used in the proxy.
Each proxy needs to implement its own logic for setting up the protocol.
"""
raise NotImplementedError
def _is_draining(self) -> bool:
"""Whether is proxy actor is in the draining status or not."""
return self._draining_start_time is not None
def update_routes(self, endpoints: Dict[DeploymentID, EndpointInfo]):
self._route_table_populated = True
self.route_info: Dict[str, DeploymentID] = dict()
for deployment_id, info in endpoints.items():
route = info.route
self.route_info[route] = deployment_id
self.proxy_router.update_routes(endpoints)
def is_drained(self):
"""Check whether the proxy actor is drained or not.
A proxy actor is drained if it has no ongoing requests
AND it has been draining for more than
`PROXY_MIN_DRAINING_PERIOD_S` seconds.
"""
if not self._is_draining():
return False
return (not self._ongoing_requests) and (
(time.time() - self._draining_start_time) > PROXY_MIN_DRAINING_PERIOD_S
)
def update_draining(self, draining: bool):
"""Update the draining status of the proxy.
This is called by the proxy state manager
to drain or un-drain the proxy actor.
"""
if draining and (not self._is_draining()):
logger.info(
f"Start to drain the proxy actor on node {self._node_id}.",
extra={"log_to_stderr": False},
)
self._draining_start_time = time.time()
if (not draining) and self._is_draining():
logger.info(
f"Stop draining the proxy actor on node {self._node_id}.",
extra={"log_to_stderr": False},
)
self._draining_start_time = None
@abstractmethod
async def not_found_response(
self, proxy_request: ProxyRequest
) -> ResponseGenerator:
raise NotImplementedError
@abstractmethod
async def routes_response(
self, *, healthy: bool, message: str
) -> ResponseGenerator:
raise NotImplementedError
@abstractmethod
async def health_response(
self, *, healthy: bool, message: str
) -> ResponseGenerator:
raise NotImplementedError
def _ongoing_requests_start(self):
"""Ongoing requests start.
The current autoscale logic can downscale nodes with ongoing requests if the
node doesn't have replicas and has no primary copies of objects in the object
store. The counter and the dummy object reference will help to keep the node
alive while draining requests, so they are not dropped unintentionally.
"""
self._ongoing_requests += 1
self.num_ongoing_requests_gauge.set(self._ongoing_requests)
def _ongoing_requests_end(self):
"""Ongoing requests end.
Decrement the ongoing request counter and drop the dummy object reference
signaling that the node can be downscaled safely.
"""
self._ongoing_requests -= 1
self.num_ongoing_requests_gauge.set(self._ongoing_requests)
def _get_health_or_routes_reponse(
self, proxy_request: ProxyRequest
) -> ResponseHandlerInfo:
"""Get the response handler for system health and route endpoints.
If the proxy is draining or has not yet received a route table update from the
controller, both will return a non-OK status.
"""
if not self._route_table_populated:
healthy = False
message = NO_ROUTES_MESSAGE
elif self._is_draining():
healthy = False
message = DRAINING_MESSAGE
else:
healthy = True
message = HEALTHY_MESSAGE
if proxy_request.is_health_request:
response_generator = self.health_response(healthy=healthy, message=message)
else:
assert proxy_request.is_route_request
response_generator = self.routes_response(healthy=healthy, message=message)
return ResponseHandlerInfo(
response_generator=response_generator,
metadata=HandlerMetadata(
route=proxy_request.route_path,
),
should_record_access_log=False,
should_increment_ongoing_requests=False,
)
def _get_response_handler_info(
self, proxy_request: ProxyRequest
) -> ResponseHandlerInfo:
if proxy_request.is_health_request or proxy_request.is_route_request:
return self._get_health_or_routes_reponse(proxy_request)
matched_route = None
if self.protocol == RequestProtocol.HTTP:
matched_route = self.proxy_router.match_route(proxy_request.route_path)
elif self.protocol == RequestProtocol.GRPC:
matched_route = self.proxy_router.get_handle_for_endpoint(
proxy_request.route_path
)
if matched_route is None:
return ResponseHandlerInfo(
response_generator=self.not_found_response(proxy_request),
metadata=HandlerMetadata(
route=proxy_request.route_path,
),
should_record_access_log=True,
should_increment_ongoing_requests=False,
)
else:
route_prefix, handle, app_is_cross_language = matched_route
# Modify the path and root path so that reverse lookups and redirection
# work as expected. We do this here instead of in replicas so it can be
# changed without restarting the replicas.
route_path = proxy_request.route_path
if route_prefix != "/" and self.protocol == RequestProtocol.HTTP:
assert not route_prefix.endswith("/")
proxy_request.set_root_path(proxy_request.root_path + route_prefix)
# NOTE(edoakes): starlette<0.33.0 expected the ASGI 'root_prefix'
# to be stripped from the 'path', which wasn't technically following
# the standard. See https://github.com/encode/starlette/pull/2352.
if version.parse(starlette.__version__) < version.parse("0.33.0"):
proxy_request.set_path(route_path.replace(route_prefix, "", 1))
handle, request_id = self.setup_request_context_and_handle(
app_name=handle.deployment_id.app_name,
handle=handle,
route_path=route_path,
proxy_request=proxy_request,
)
response_generator = self.send_request_to_replica(
request_id=request_id,
handle=handle,
proxy_request=proxy_request,
app_is_cross_language=app_is_cross_language,
)
return ResponseHandlerInfo(
response_generator=response_generator,
metadata=HandlerMetadata(
application_name=handle.deployment_id.app_name,
deployment_name=handle.deployment_id.name,
route=route_path,
),
should_record_access_log=True,
should_increment_ongoing_requests=True,
)
async def proxy_request(self, proxy_request: ProxyRequest) -> ResponseGenerator:
"""Wrapper for proxy request.
This method is served as common entry point by the proxy. It handles the
routing, including routes and health checks, ongoing request counter,
and metrics.
"""
assert proxy_request.request_type in {"http", "websocket", "grpc"}
response_handler_info = self._get_response_handler_info(proxy_request)
start_time = time.time()
if response_handler_info.should_increment_ongoing_requests:
self._ongoing_requests_start()
try:
# The final message yielded must always be the `ResponseStatus`.
status: Optional[ResponseStatus] = None
async for message in response_handler_info.response_generator:
if isinstance(message, ResponseStatus):
status = message
yield message
assert status is not None and isinstance(status, ResponseStatus)
finally:
# If anything during the request failed, we still want to ensure the ongoing
# request counter is decremented.
if response_handler_info.should_increment_ongoing_requests:
self._ongoing_requests_end()
latency_ms = (time.time() - start_time) * 1000.0
if response_handler_info.should_record_access_log:
logger.info(
access_log_msg(
method=proxy_request.method,
status=str(status.code),
latency_ms=latency_ms,
),
extra={"log_to_stderr": False, "serve_access_log": True},
)
self.request_counter.inc(
tags={
"route": response_handler_info.metadata.route,
"method": proxy_request.method,
"application": response_handler_info.metadata.application_name,
"status_code": str(status.code),
}
)
self.processing_latency_tracker.observe(
latency_ms,
tags={
"method": proxy_request.method,
"route": response_handler_info.metadata.route,
"application": response_handler_info.metadata.application_name,
"status_code": str(status.code),
},
)
if status.is_error:
self.request_error_counter.inc(
tags={
"route": response_handler_info.metadata.route,
"error_code": str(status.code),
"method": proxy_request.method,
"application": response_handler_info.metadata.application_name,
}
)
self.deployment_request_error_counter.inc(
tags={
"deployment": response_handler_info.metadata.deployment_name,
"error_code": str(status.code),
"method": proxy_request.method,
"route": response_handler_info.metadata.route,
"application": response_handler_info.metadata.application_name,
}
)
@abstractmethod
def setup_request_context_and_handle(
self,
app_name: str,
handle: DeploymentHandle,
route_path: str,
proxy_request: ProxyRequest,
) -> Tuple[DeploymentHandle, str]:
"""Setup the request context and handle for the request.
Each proxy needs to implement its own logic for setting up the request context
and handle.
"""
raise NotImplementedError
@abstractmethod
async def send_request_to_replica(
self,
request_id: str,
handle: DeploymentHandle,
proxy_request: ProxyRequest,
app_is_cross_language: bool = False,
) -> ResponseGenerator:
"""Send the request to the replica and handle streaming response.
Each proxy needs to implement its own logic for sending the request and
handling the streaming response.
"""
raise NotImplementedError
class gRPCProxy(GenericProxy):
"""This class is meant to be instantiated and run by an gRPC server.
This is the servicer class for the gRPC server. It implements `unary_unary`
as the entry point for unary gRPC request and `unary_stream` as the entry
point for streaming gRPC request.
"""
@property
def protocol(self) -> RequestProtocol:
return RequestProtocol.GRPC
async def not_found_response(
self, proxy_request: ProxyRequest
) -> ResponseGenerator:
if not proxy_request.app_name:
application_message = "Application metadata not set."
else:
application_message = f"Application '{proxy_request.app_name}' not found."
not_found_message = (
f"{application_message} Ping "
"/ray.serve.RayServeAPIService/ListApplications for available applications."
)
yield ResponseStatus(
code=grpc.StatusCode.NOT_FOUND,
message=not_found_message,
is_error=True,
)
async def routes_response(
self, *, healthy: bool, message: str
) -> ResponseGenerator:
yield ListApplicationsResponse(
application_names=[
endpoint.app_name for endpoint in self.route_info.values()
],
).SerializeToString()
yield ResponseStatus(
code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE,
message=message,
is_error=not healthy,
)
async def health_response(self, *, healthy: bool, message) -> ResponseGenerator:
yield HealthzResponse(message=message).SerializeToString()
yield ResponseStatus(
code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE,
message=message,
is_error=not healthy,
)
def service_handler_factory(self, service_method: str, stream: bool) -> Callable:
def set_grpc_code_and_details(
context: grpc._cython.cygrpc._ServicerContext, status: ResponseStatus
):
# Only the latest code and details will take effect. If the user already
# set them to a truthy value in the context, skip setting them with Serve's
# default values. By default, if nothing is set, the code is 0 and the
# details is "", which both are falsy. So if the user did not set them or
# if they're explicitly set to falsy values, such as None, Serve will
# continue to set them with our default values.
if not context.code():
context.set_code(status.code)
if not context.details():
context.set_details(status.message)
async def unary_unary(
request_proto: Any, context: grpc._cython.cygrpc._ServicerContext
) -> bytes:
"""Entry point of the gRPC proxy unary request.
This method is called by the gRPC server when a unary request is received.
It wraps the request in a ProxyRequest object and calls proxy_request.
The return value is serialized user defined protobuf bytes.
"""
proxy_request = gRPCProxyRequest(
request_proto=request_proto,
context=context,
service_method=service_method,
stream=False,
)
status = None
response = None
async for message in self.proxy_request(proxy_request=proxy_request):
if isinstance(message, ResponseStatus):
status = message
else:
response = message
set_grpc_code_and_details(context, status)
return response
async def unary_stream(
request_proto: Any, context: grpc._cython.cygrpc._ServicerContext
) -> Generator[bytes, None, None]:
"""Entry point of the gRPC proxy streaming request.
This method is called by the gRPC server when a streaming request is
received. It wraps the request in a ProxyRequest object and calls
proxy_request. The return value is a generator of serialized user defined
protobuf bytes.
"""
proxy_request = gRPCProxyRequest(
request_proto=request_proto,
context=context,
service_method=service_method,
stream=True,
)
status = None
async for message in self.proxy_request(proxy_request=proxy_request):
if isinstance(message, ResponseStatus):
status = message
else:
yield message
set_grpc_code_and_details(context, status)
return unary_stream if stream else unary_unary
def setup_request_context_and_handle(
self,
app_name: str,
handle: DeploymentHandle,
route_path: str,
proxy_request: ProxyRequest,
) -> Tuple[DeploymentHandle, str]:
"""Setup request context and handle for the request.
Unpack gRPC request metadata and extract info to set up request context and
handle.
"""
multiplexed_model_id = proxy_request.multiplexed_model_id
request_id = proxy_request.request_id
if not request_id:
request_id = generate_request_id()
proxy_request.request_id = request_id
handle = handle.options(
stream=proxy_request.stream,
multiplexed_model_id=multiplexed_model_id,
method_name=proxy_request.method_name,
)
request_context_info = {
"route": route_path,
"request_id": request_id,
"app_name": app_name,
"multiplexed_model_id": multiplexed_model_id,
"grpc_context": proxy_request.ray_serve_grpc_context,
}
ray.serve.context._serve_request_context.set(
ray.serve.context._RequestContext(**request_context_info)
)
proxy_request.send_request_id(request_id=request_id)
return handle, request_id
async def send_request_to_replica(
self,
request_id: str,
handle: DeploymentHandle,
proxy_request: ProxyRequest,
app_is_cross_language: bool = False,
) -> ResponseGenerator:
handle_arg = proxy_request.request_object()
response_generator = ProxyResponseGenerator(
handle.remote(handle_arg),
timeout_s=self.request_timeout_s,
)
try:
async for context, result in response_generator:
context._set_on_grpc_context(proxy_request.context)
yield result
yield ResponseStatus(code=grpc.StatusCode.OK)
except TimeoutError:
message = f"Request timed out after {self.request_timeout_s}s."
logger.warning(message)
yield ResponseStatus(
code=grpc.StatusCode.DEADLINE_EXCEEDED,
is_error=True,
message=message,
)
except asyncio.CancelledError:
message = f"Client for request {request_id} disconnected."
logger.info(message)
yield ResponseStatus(
code=grpc.StatusCode.CANCELLED,
is_error=True,
message=message,
)
except BackPressureError as e:
yield ResponseStatus(
code=grpc.StatusCode.UNAVAILABLE,
is_error=True,
message=e.message,
)
except Exception as e:
if isinstance(e, (RayActorError, RayTaskError)):
logger.warning(f"Request failed: {e}", extra={"log_to_stderr": False})
else:
logger.exception("Request failed due to unexpected error.")
yield ResponseStatus(
code=grpc.StatusCode.INTERNAL,
is_error=True,
message=str(e),
)
class HTTPProxy(GenericProxy):
"""This class is meant to be instantiated and run by an ASGI HTTP server."""
def __init__(
self,
node_id: NodeId,
node_ip_address: str,
proxy_router_class: Type[ProxyRouter],
request_timeout_s: Optional[float] = None,
proxy_actor: Optional[ActorHandle] = None,
):
super().__init__(
node_id,
node_ip_address,
proxy_router_class,
request_timeout_s=request_timeout_s,
)
self.self_actor_handle = proxy_actor or ray.get_runtime_context().current_actor
self.asgi_receive_queues: Dict[str, MessageQueue] = dict()
@property
def protocol(self) -> RequestProtocol:
return RequestProtocol.HTTP
async def not_found_response(
self, proxy_request: ProxyRequest
) -> ResponseGenerator:
status_code = 404
for message in convert_object_to_asgi_messages(
f"Path '{proxy_request.path}' not found. "
"Ping http://.../-/routes for available routes.",
status_code=status_code,
):
yield message
yield ResponseStatus(code=status_code, is_error=True)
async def routes_response(
self, *, healthy: bool, message: str
) -> ResponseGenerator:
status_code = 200 if healthy else 503
if healthy:
response = dict()
for route, endpoint in self.route_info.items():
# For 2.x deployments, return {route -> app name}
if endpoint.app_name:
response[route] = endpoint.app_name
# Keep compatibility with 1.x deployments.
else:
response[route] = endpoint.name
else:
response = message
for asgi_message in convert_object_to_asgi_messages(
response,
status_code=status_code,
):
yield asgi_message
yield ResponseStatus(
code=status_code,
message=message,
is_error=not healthy,
)
async def health_response(
self, *, healthy: bool, message: str = ""
) -> ResponseGenerator:
status_code = 200 if healthy else 503
for asgi_message in convert_object_to_asgi_messages(
message,
status_code=status_code,
):
yield asgi_message
yield ResponseStatus(
code=status_code,
is_error=not healthy,
message=message,
)
async def receive_asgi_messages(self, request_id: str) -> ResponseGenerator:
queue = self.asgi_receive_queues.get(request_id, None)
if queue is None:
raise KeyError(f"Request ID {request_id} not found.")
await queue.wait_for_message()
return queue.get_messages_nowait()
async def __call__(self, scope, receive, send):
"""Implements the ASGI protocol.
See details at:
https://asgi.readthedocs.io/en/latest/specs/index.html.
"""
proxy_request = ASGIProxyRequest(scope=scope, receive=receive, send=send)
async for message in self.proxy_request(proxy_request):
if not isinstance(message, ResponseStatus):
await send(message)
async def proxy_asgi_receive(
self, receive: Receive, queue: MessageQueue
) -> Optional[int]:
"""Proxies the `receive` interface, placing its messages into the queue.
Once a disconnect message is received, the call exits and `receive` is no longer
called.
For HTTP messages, `None` is always returned.
For websocket messages, the disconnect code is returned if a disconnect code is
received.
"""
try:
while True:
msg = await receive()
await queue(msg)
if msg["type"] == "http.disconnect":
return None
if msg["type"] == "websocket.disconnect":
return msg["code"]
finally:
# Close the queue so any subsequent calls to fetch messages return
# immediately: https://github.com/ray-project/ray/issues/38368.
queue.close()
def setup_request_context_and_handle(
self,
app_name: str,
handle: DeploymentHandle,
route_path: str,
proxy_request: ProxyRequest,
) -> Tuple[DeploymentHandle, str]:
"""Setup request context and handle for the request.
Unpack HTTP request headers and extract info to set up request context and
handle.
"""
request_context_info = {
"route": route_path,
"app_name": app_name,
}
for key, value in proxy_request.headers:
if key.decode() == SERVE_MULTIPLEXED_MODEL_ID:
multiplexed_model_id = value.decode()
handle = handle.options(multiplexed_model_id=multiplexed_model_id)
request_context_info["multiplexed_model_id"] = multiplexed_model_id
if key.decode() == "x-request-id":
request_context_info["request_id"] = value.decode()
ray.serve.context._serve_request_context.set(
ray.serve.context._RequestContext(**request_context_info)
)
return handle, request_context_info["request_id"]
async def _format_handle_arg_for_java(
self,
proxy_request: ProxyRequest,
) -> bytes:
"""Convert an HTTP request to the Java-accepted format (single byte string)."""
query_string = proxy_request.scope.get("query_string")
http_body_bytes = await receive_http_body(
proxy_request.scope, proxy_request.receive, proxy_request.send
)
if query_string:
arg = query_string.decode().split("=", 1)[1]
else:
arg = http_body_bytes.decode()
return arg
async def send_request_to_replica(
self,
request_id: str,
handle: DeploymentHandle,
proxy_request: ProxyRequest,
app_is_cross_language: bool = False,
) -> ResponseGenerator:
"""Send the request to the replica and yield its response messages.
The yielded values will be ASGI messages until the final one, which will be
the status code.
"""
if app_is_cross_language:
handle_arg = await self._format_handle_arg_for_java(proxy_request)
# Response is returned as raw bytes, convert it to ASGI messages.
result_callback = convert_object_to_asgi_messages
else:
self_actor_handle = self.self_actor_handle
handle_arg = proxy_request.request_object(
receive_asgi_messages=self_actor_handle.receive_asgi_messages.remote
)
# Messages are returned as pickled dictionaries.
result_callback = pickle.loads
# Proxy the receive interface by placing the received messages on a queue.
# The downstream replica must call back into `receive_asgi_messages` on this
# actor to receive the messages.
receive_queue = MessageQueue()
self.asgi_receive_queues[request_id] = receive_queue
proxy_asgi_receive_task = get_or_create_event_loop().create_task(
self.proxy_asgi_receive(proxy_request.receive, receive_queue)
)
response_generator = ProxyResponseGenerator(
handle.remote(handle_arg),
timeout_s=self.request_timeout_s,
disconnected_task=proxy_asgi_receive_task,
result_callback=result_callback,
)
status: Optional[ResponseStatus] = None
response_started = False
expecting_trailers = False
try:
async for asgi_message_batch in response_generator:
# See the ASGI spec for message details:
# https://asgi.readthedocs.io/en/latest/specs/www.html.
for asgi_message in asgi_message_batch:
if asgi_message["type"] == "http.response.start":
# HTTP responses begin with exactly one
# "http.response.start" message containing the "status"
# field. Other response types (e.g., WebSockets) may not.
status_code = str(asgi_message["status"])
status = ResponseStatus(
code=status_code,
# TODO(edoakes): we need a more nuanced check than this.
is_error=status_code != "200",
)
expecting_trailers = asgi_message.get("trailers", False)
elif asgi_message["type"] == "websocket.accept":
# Websocket code explicitly handles client disconnects,
# so let the ASGI disconnect message propagate instead of
# cancelling the handler.
response_generator.stop_checking_for_disconnect()
elif (
asgi_message["type"] == "http.response.body"
and not asgi_message.get("more_body", False)
and not expecting_trailers
):
# If the body is completed and we aren't expecting trailers, the
# response is done so we should stop listening for disconnects.
response_generator.stop_checking_for_disconnect()
elif asgi_message["type"] == "http.response.trailers":
# If we are expecting trailers, the response is only done when
# the trailers message has been sent.
if not asgi_message.get("more_trailers", False):
response_generator.stop_checking_for_disconnect()
elif asgi_message["type"] == "websocket.disconnect":
status = ResponseStatus(
code=str(asgi_message["code"]),
# TODO(edoakes): we need a more nuanced check than this.
is_error=False,