File size: 5,774 Bytes
31dc8dc | 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 | from __future__ import annotations
import asyncio
import uuid
from dataclasses import dataclass, field
from typing import Awaitable, Callable
from diffulex.logger import get_logger
from diffulex.server.protocol import (
ServingAbort,
ServingCommand,
ServingError,
ServingEvent,
ServingGenerate,
ServingReply,
ServingShutdown,
serving_command_to_dict,
serving_event_from_dict,
)
from diffulex.server.zmq_queue import ZmqAsyncPullQueue, ZmqAsyncPushQueue
logger = get_logger(__name__)
class ClientDisconnected(RuntimeError):
pass
@dataclass
class FrontendReqState:
rid: str
events: list[ServingEvent] = field(default_factory=list)
event: asyncio.Event = field(default_factory=asyncio.Event)
class FrontendManager:
def __init__(
self,
*,
model_id: str,
send_backend,
recv_backend,
request_state_wait_timeout_s: float = 0.5,
) -> None:
self.model_id = model_id
self.send_backend = send_backend
self.recv_backend = recv_backend
self.request_state_wait_timeout_s = request_state_wait_timeout_s
self.rid_to_state: dict[str, FrontendReqState] = {}
self._listen_task: asyncio.Task | None = None
@classmethod
def from_zmq(cls, *, model_id: str, command_addr: str, event_addr: str) -> "FrontendManager":
return cls(
model_id=model_id,
send_backend=ZmqAsyncPushQueue(command_addr, create=True, encoder=serving_command_to_dict),
recv_backend=ZmqAsyncPullQueue(event_addr, create=True, decoder=serving_event_from_dict),
)
async def start(self) -> None:
self._create_listener_once()
async def stop(self) -> None:
try:
await self.send_backend.put(ServingShutdown())
except Exception:
logger.debug("Failed to send backend shutdown command", exc_info=True)
if self._listen_task is not None:
self._listen_task.cancel()
try:
await self._listen_task
except asyncio.CancelledError:
pass
self._listen_task = None
for queue in (self.send_backend, self.recv_backend):
stop = getattr(queue, "stop", None)
if stop is not None:
stop()
def _create_listener_once(self) -> None:
if self._listen_task is None or self._listen_task.done():
self._listen_task = asyncio.create_task(self.listen(), name="diffulex-frontend-listen")
def new_request_id(self) -> str:
return f"diffulex-{uuid.uuid4().hex}"
def add_request_state(self, rid: str) -> FrontendReqState:
if rid in self.rid_to_state:
raise ValueError(f"Request id already exists: {rid}")
state = FrontendReqState(rid=rid)
self.rid_to_state[rid] = state
return state
def discard_request_state(self, rid: str) -> None:
self.rid_to_state.pop(rid, None)
async def listen(self) -> None:
while True:
event = await self.recv_backend.get()
state = self.rid_to_state.get(event.rid)
if state is None:
logger.debug("Received event for unknown rid=%s", event.rid)
continue
state.events.append(event)
state.event.set()
async def send_one(self, command: ServingCommand) -> None:
self._create_listener_once()
await self.send_backend.put(command)
async def generate(
self,
command: ServingGenerate,
*,
is_disconnected: Callable[[], Awaitable[bool]] | None = None,
) -> ServingReply:
async for event in self.generate_stream(command, is_disconnected=is_disconnected):
if isinstance(event, ServingError):
raise RuntimeError(event.message)
if isinstance(event, ServingReply):
return event
raise ClientDisconnected(f"Request {command.rid} disconnected before completion")
async def generate_stream(
self,
command: ServingGenerate,
*,
is_disconnected: Callable[[], Awaitable[bool]] | None = None,
):
self.add_request_state(command.rid)
completed = False
try:
await self.send_one(command)
while True:
event = await self.wait_for_event(command.rid, is_disconnected=is_disconnected)
if isinstance(event, (ServingReply, ServingError)):
completed = True
yield event
if completed:
break
except ClientDisconnected:
return
finally:
if not completed:
try:
await self.abort_request(command.rid)
except Exception:
logger.debug("Failed to abort rid=%s", command.rid, exc_info=True)
self.discard_request_state(command.rid)
async def wait_for_event(
self,
rid: str,
*,
is_disconnected: Callable[[], Awaitable[bool]] | None = None,
) -> ServingEvent:
state = self.rid_to_state[rid]
while True:
if state.events:
return state.events.pop(0)
try:
await asyncio.wait_for(state.event.wait(), timeout=self.request_state_wait_timeout_s)
except asyncio.TimeoutError:
if is_disconnected is not None and await is_disconnected():
raise ClientDisconnected(f"Request {rid} disconnected from client side")
continue
state.event.clear()
async def abort_request(self, rid: str) -> None:
await self.send_one(ServingAbort(rid=rid))
|