Spaces:
Sleeping
Sleeping
add long-polling: server blocks up to 5s on /poll, notifies immediately on new request
Browse files8 unmodified lines9101112131415162 unmodified lines192021222324256 unmodified lines32333435363738394041424344454647486 unmodified lines5556575859606113 unmodified lines75767778798081828384858687888 unmodified linesPORT = int(os.environ.get("PORT", 7860))pending = {}# Magic byte signatures for content type detectionMAGIC_SIGNATURES = [(b'\xff\xd8\xff', 'image/jpeg'),(b'\x89PNG\r\n\x1a\n', 'image/png'),2 unmodified lines(b'RIFF', 'image/webp', lambda b: b[8:12] == b'WEBP'),(b'%PDF', 'application/pdf'),(b'PK\x03\x04', 'application/zip'),(b'\x1aE\xdf\xa3', 'application/octet-stream'), # Matroska/WebM container]def detect_content_type(body, fallback="application/octet-stream"):6 unmodified linescondition = extra_check(body[:16]) if callable(extra_check) else Trueif body.startswith(magic) and condition:return ct# Check if it looks like HTMLtext = body[:500].decode('utf-8', errors='ignore').strip().lower()if text.startswith('<!doctype') or text.startswith('<html') or text.startswith('<!DOCTYPE') or text.startswith('<html'):return fallback if 'text/html' in fallback else fallback# Check if it looks like plain texttry:body.decode('utf-8')# It's valid UTF-8 text - keep the fallbackreturn fallbackexcept (UnicodeDecodeError, ValueError):# Binary data - use detected type or octet-streamreturn "application/octet-stream"async def proxy_handler(request):6 unmodified linesrid = str(uuid.uuid4())event = asyncio.Event()result = {"body": b"", "status": 502, "content_type": "text/plain"}pending[rid] = {"event": event, "result": result, "url": target_url, "claimed": False}try:await asyncio.wait_for(event.wait(), timeout=30)except asyncio.TimeoutError:13 unmodified linesreturn web.Response(body=body, content_type=ct)async def poll_handler(request):for rid, info in list(pending.items()):if not info["claimed"]:info["claimed"] = Truereturn web.json_response({"rid": rid,"url": info["url"],"url_encoded": urllib.parse.quote(info["url"], safe='')})return web.json_response({})async def respond_handler(request):8 unmodified lines9101112131415162 unmodified lines192021222324256 unmodified lines323334353637383940416 unmodified lines48495051525354555613 unmodified lines7071727374757677787980818283848586878889909192939495968 unmodified linesPORT = int(os.environ.get("PORT", 7860))pending = {}poll_cond = asyncio.Condition()MAGIC_SIGNATURES = [(b'\xff\xd8\xff', 'image/jpeg'),(b'\x89PNG\r\n\x1a\n', 'image/png'),2 unmodified lines(b'RIFF', 'image/webp', lambda b: b[8:12] == b'WEBP'),(b'%PDF', 'application/pdf'),(b'PK\x03\x04', 'application/zip'),(b'\x1aE\xdf\xa3', 'application/octet-stream'),]def detect_content_type(body, fallback="application/octet-stream"):6 unmodified linescondition = extra_check(body[:16]) if callable(extra_check) else Trueif body.startswith(magic) and condition:return cttry:body.decode('utf-8')return fallbackexcept (UnicodeDecodeError, ValueError):return "application/octet-stream"async def proxy_handler(request):6 unmodified linesrid = str(uuid.uuid4())event = asyncio.Event()result = {"body": b"", "status": 502, "content_type": "text/plain"}async with poll_cond:pending[rid] = {"event": event, "result": result, "url": target_url, "claimed": False}poll_cond.notify_all()try:await asyncio.wait_for(event.wait(), timeout=30)except asyncio.TimeoutError:13 unmodified linesreturn web.Response(body=body, content_type=ct)async def poll_handler(request):async with poll_cond:for rid, info in list(pending.items()):if not info["claimed"]:info["claimed"] = Truereturn web.json_response({"rid": rid,"url": info["url"],"url_encoded": urllib.parse.quote(info["url"], safe='')})try:await asyncio.wait_for(poll_cond.wait(), timeout=5.0)except asyncio.TimeoutError:return web.json_response({})for rid, info in list(pending.items()):if not info["claimed"]:info["claimed"] = Truereturn web.json_response({"rid": rid,"url": info["url"],"url_encoded": urllib.parse.quote(info["url"], safe='')})return web.json_response({})async def respond_handler(request):
app.py+26-18