|
| 1 | +import random |
| 2 | +from typing import FrozenSet, List, Optional, Tuple |
| 3 | + |
| 4 | +from fastapi import FastAPI, HTTPException, Request |
| 5 | + |
| 6 | +from ray import serve |
| 7 | +from ray.serve._private.common import ReplicaID |
| 8 | +from ray.serve.handle import DeploymentHandle |
| 9 | + |
| 10 | +_BODY_TRUNCATED_HEADER = "x-body-truncated" |
| 11 | + |
| 12 | +_ReplicaCacheSignature = FrozenSet[ReplicaID] |
| 13 | + |
| 14 | +router_app = FastAPI() |
| 15 | + |
| 16 | + |
| 17 | +@serve.ingress(router_app) |
| 18 | +class LLMRouter: |
| 19 | + """Ingress request router for direct streaming. |
| 20 | +
|
| 21 | + When direct streaming is enabled, HAProxy calls /internal/route on this |
| 22 | + deployment to get a data plane replica, then forwards traffic directly |
| 23 | + to the matching LLMServer replica's backend HTTP port. |
| 24 | +
|
| 25 | + /internal/route HTTP contract |
| 26 | + ----------------------------- |
| 27 | + Request: |
| 28 | + POST /internal/route |
| 29 | + Content-Type: application/json |
| 30 | + Body: the target ChatCompletions / Completions request payload. |
| 31 | + Today the router uses round-robin and ignores the body, but it |
| 32 | + is plumbed through so future routing policies (e.g. prefix |
| 33 | + cache aware) can score replicas against ``messages`` / |
| 34 | + ``prompt``. HAProxy should continue forwarding the payload |
| 35 | + (subject to truncation below). |
| 36 | +
|
| 37 | + Truncated bodies: |
| 38 | + HAProxy may forward only a prefix of the request body for routing. |
| 39 | + When it does, it must set the ``x-body-truncated`` header. The |
| 40 | + router forwards both the body bytes and this signal to |
| 41 | + ``_pick_replica`` for future body-aware policies. |
| 42 | +
|
| 43 | + Responses: |
| 44 | + 200 ``{"host": str, "port": int, "replica_id": str}``: pick |
| 45 | + succeeded. |
| 46 | + 4xx/5xx FastAPI ``{"detail": str}``: informational only; HAProxy |
| 47 | + treats any non-200 as a routing failure. |
| 48 | +
|
| 49 | + Health: |
| 50 | + ``GET /health`` is exposed as a human-operator convenience. |
| 51 | + Serve uses ``check_health()`` for replica readiness, not HTTP. |
| 52 | + """ |
| 53 | + |
| 54 | + async def __init__(self, server: DeploymentHandle): |
| 55 | + # Randomized so multiple LLMRouter replicas don't lockstep on the |
| 56 | + # same replica sequence. |
| 57 | + self._round_robin_counter = random.randrange(2**31) |
| 58 | + self._cached_dict_id: Optional[int] = None |
| 59 | + self._cached_replica_signature: Optional[_ReplicaCacheSignature] = None |
| 60 | + self._cached_endpoints: List[Tuple[str, int, str]] = [] |
| 61 | + self._handle: DeploymentHandle = server |
| 62 | + |
| 63 | + # Force the handle's local router and request router to construct |
| 64 | + # synchronously so /internal/route can read them in the hot path. |
| 65 | + # `curr_replicas` is populated separately by controller broadcast; |
| 66 | + # /internal/route returns 503 (HAProxy retries) until then, which |
| 67 | + # decouples router liveness from LLMServer cold start. |
| 68 | + self._handle._init() |
| 69 | + self._request_router = self._handle._get_request_router() |
| 70 | + if self._request_router is None: |
| 71 | + raise RuntimeError( |
| 72 | + "DeploymentHandle._get_request_router() returned None after " |
| 73 | + "_init(); Serve internals may have changed." |
| 74 | + ) |
| 75 | + |
| 76 | + async def check_health(self): |
| 77 | + if self._handle._get_request_router() is None: |
| 78 | + raise RuntimeError("request router not initialized") |
| 79 | + |
| 80 | + @router_app.post("/internal/route") |
| 81 | + async def route(self, request: Request): |
| 82 | + body = await request.body() |
| 83 | + body_truncated = _BODY_TRUNCATED_HEADER in request.headers |
| 84 | + try: |
| 85 | + host, port, replica_id = self._pick_replica( |
| 86 | + request_body=body, body_truncated=body_truncated |
| 87 | + ) |
| 88 | + except RuntimeError as e: |
| 89 | + raise HTTPException(status_code=503, detail=str(e)) |
| 90 | + return {"host": host, "port": port, "replica_id": replica_id} |
| 91 | + |
| 92 | + @router_app.get("/health") |
| 93 | + async def health(self): |
| 94 | + return {"status": "ok"} |
| 95 | + |
| 96 | + def _ready_endpoints(self) -> List[Tuple[str, int, str]]: |
| 97 | + """Backend (host, port, full_id) tuples, cached on replica-set change.""" |
| 98 | + curr_replicas = self._request_router.curr_replicas |
| 99 | + # RequestRouter swaps the dict wholesale on every controller broadcast, |
| 100 | + # so dict identity is a cheap "did anything change" check; the keyset |
| 101 | + # check then filters out broadcasts that didn't actually change the |
| 102 | + # replica set. |
| 103 | + if id(curr_replicas) == self._cached_dict_id: |
| 104 | + return self._cached_endpoints |
| 105 | + signature = frozenset(curr_replicas.keys()) |
| 106 | + if signature != self._cached_replica_signature: |
| 107 | + self._cached_replica_signature = signature |
| 108 | + ready = sorted( |
| 109 | + (r for r in curr_replicas.values() if r.backend_http_endpoint), |
| 110 | + key=lambda r: r.replica_id.unique_id, |
| 111 | + ) |
| 112 | + self._cached_endpoints = [ |
| 113 | + (*r.backend_http_endpoint, r.replica_id.to_full_id_str()) for r in ready |
| 114 | + ] |
| 115 | + self._cached_dict_id = id(curr_replicas) |
| 116 | + return self._cached_endpoints |
| 117 | + |
| 118 | + def _pick_replica( |
| 119 | + self, |
| 120 | + request_body: Optional[bytes] = None, |
| 121 | + body_truncated: bool = False, |
| 122 | + ) -> Tuple[str, int, str]: |
| 123 | + """Pick a backend HTTP replica. |
| 124 | +
|
| 125 | + Today this is plain round-robin and ignores the payload. The |
| 126 | + ``request_body`` (possibly a HAProxy-truncated prefix, indicated by |
| 127 | + ``body_truncated``) is plumbed through so a future prefix cache aware |
| 128 | + policy can score replicas against the request's prompt / messages |
| 129 | + without changing the /internal/route contract or the call site. |
| 130 | + """ |
| 131 | + del request_body, body_truncated |
| 132 | + candidates = self._ready_endpoints() |
| 133 | + if not candidates: |
| 134 | + raise RuntimeError("no backend-http replicas") |
| 135 | + |
| 136 | + index = self._round_robin_counter % len(candidates) |
| 137 | + self._round_robin_counter += 1 |
| 138 | + return candidates[index] |
0 commit comments