Spaces:
Sleeping
Sleeping
fix WS dispatch: single reader pattern
Browse files2 unmodified lines34567789101112131415167 unmodified lines2425262627272829303132333415 unmodified lines50515249505354555354555657585960616263645657665859606162636473746566676869707179808182838485868788899091929394959697727374752 unmodified linesimport jsonimport osimport sysimport uuidfrom aiohttp import web, WSMsgTypefrom urllib.parse import urlencode
PORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"
clients = {}pending = {}
async def ws_handler(request): ws = web.WebSocketResponse(max_msg_size=0)7 unmodified lines if msg.type == WSMsgType.TEXT: try: data = json.loads(msg.data) if data.get("type") == "pong": continue if data.get("type") == "response": rid = data.get("rid") if rid and rid in pending: pending[rid]["result"].update(data) pending[rid]["event"].set() except json.JSONDecodeError: pass elif msg.type == WSMsgType.ERROR:15 unmodified lines target_url = TARGET_ORIGIN.rstrip("/") + "/" + target_url.lstrip("/") if not clients: return web.json_response({"error": "no router connected"}, status=503) rid = str(id(request)) futures = {} rid = str(uuid.uuid4()) event = asyncio.Event() result = {} async def on_msg(ws_msg): nonlocal result if ws_msg.type == aiohttp.WSMsgType.TEXT: try: data = json.loads(ws_msg.data) if data.get("rid") == rid and data.get("type") == "response": result = data event.set() except json.JSONDecodeError: pass listener_task = None ws = next(iter(clients.values())) pending[rid] = {"event": event, "result": result} try: listener_task = asyncio.create_task(_listen_for_rid(ws, rid, event, result)) ws = next(iter(clients.values())) payload = json.dumps({"type": "request", "rid": rid, "url": target_url}) await ws.send_str(payload) try: await asyncio.wait_for(event.wait(), timeout=30) except asyncio.TimeoutError: return web.json_response({"error": "timeout"}, status=504) if result.get("status") and result["status"] != 200: return web.json_response({"error": result.get("body", "upstream error")}, status=result["status"]) status = result.get("status", 502) if status != 200: return web.json_response({"error": result.get("body", "upstream error")}, status=status) body = result.get("body", "") ct = result.get("content_type", "text/html") return web.Response(body=body, content_type=ct) finally: if listener_task: listener_task.cancel()
async def _listen_for_rid(ws, rid, event, result): try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: try: data = json.loads(msg.data) if data.get("rid") == rid and data.get("type") == "response": result.update(data) event.set() break except json.JSONDecodeError: pass elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): break except (asyncio.CancelledError, Exception): pass pending.pop(rid, None)
async def health(request): return web.json_response({"status": "ok", "clients": len(clients), "port": PORT})app.py+14-39