main
py 48 lines 1.41 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 from collections.abc import Awaitable
5
6 from fastapi.responses import JSONResponse
7 from starlette.types import ASGIApp, Receive, Scope, Send
8
9 # Global variable to track scaling state
10 _scaling_elastic_ep = False
11
12
13 def get_scaling_elastic_ep():
14 return _scaling_elastic_ep
15
16
17 def set_scaling_elastic_ep(value):
18 global _scaling_elastic_ep
19 _scaling_elastic_ep = value
20
21
22 class ScalingMiddleware:
23 """Middleware that checks if the model is currently scaling and
24 returns a 503 Service Unavailable response if it is.
25
26 This middleware applies to all HTTP requests and prevents
27 processing when the model is in a scaling state.
28 """
29
30 def __init__(self, app: ASGIApp) -> None:
31 self.app = app
32
33 def __call__(self, scope: Scope, receive: Receive, send: Send) -> Awaitable[None]:
34 if scope["type"] != "http":
35 return self.app(scope, receive, send)
36
37 # Check global scaling state
38 if get_scaling_elastic_ep():
39 # Return 503 Service Unavailable response
40 response = JSONResponse(
41 content={
42 "error": "The model is currently scaling. Please try again later."
43 },
44 status_code=503,
45 )
46 return response(scope, receive, send)
47
48 return self.app(scope, receive, send)