Spaces:
Sleeping
Sleeping
fix WS dispatch: single reader pattern
Browse files2 unmodified lines34567891011121314157 unmodified lines232425262728293015 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991002 unmodified linesimport jsonimport osimport sysfrom aiohttp import web, WSMsgTypefrom urllib.parse import urlencodePORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"clients = {}async def ws_handler(request):ws = web.WebSocketResponse(max_msg_size=0)7 unmodified linesif msg.type == WSMsgType.TEXT:try:data = json.loads(msg.data)if data.get("type") == "pong":continueexcept json.JSONDecodeError:passelif msg.type == WSMsgType.ERROR:15 unmodified linestarget_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 = {}event = asyncio.Event()result = {}async def on_msg(ws_msg):nonlocal resultif ws_msg.type == aiohttp.WSMsgType.TEXT:try:data = json.loads(ws_msg.data)if data.get("rid") == rid and data.get("type") == "response":result = dataevent.set()except json.JSONDecodeError:passlistener_task = Nonews = next(iter(clients.values()))try:listener_task = asyncio.create_task(_listen_for_rid(ws, rid, event, result))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"])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()breakexcept json.JSONDecodeError:passelif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):breakexcept (asyncio.CancelledError, Exception):passasync def health(request):return web.json_response({"status": "ok", "clients": len(clients), "port": PORT})2 unmodified lines3456789101112131415167 unmodified lines242526272829303132333415 unmodified lines50515253545556575859606162636465666768697071727374752 unmodified linesimport jsonimport osimport sysimport uuidfrom aiohttp import web, WSMsgTypePORT = 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 linesif msg.type == WSMsgType.TEXT:try:data = json.loads(msg.data)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:passelif msg.type == WSMsgType.ERROR:15 unmodified linestarget_url = TARGET_ORIGIN.rstrip("/") + "/" + target_url.lstrip("/")if not clients:return web.json_response({"error": "no router connected"}, status=503)rid = str(uuid.uuid4())event = asyncio.Event()result = {}pending[rid] = {"event": event, "result": result}try: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)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:pending.pop(rid, None)async def health(request):return web.json_response({"status": "ok", "clients": len(clients), "port": PORT})
app.py+14-39