lpedro commited on
Commit
e2aaf7c
·
1 Parent(s): 9f11300

main - Fix SSE reconnect loop: catch errors, set retry 60s, return HTTP status on failure

Browse files
Files changed (1) hide show
  1. main.py +15 -8
main.py CHANGED
@@ -158,16 +158,23 @@ async def logs_stream():
158
  token = os.environ.get("HF_TOKEN", "")
159
 
160
  async def _generate():
 
161
  if not token:
162
- yield "data: {\"type\":\"stream\",\"data\":\"HF_TOKEN not configured\\n\"}\n\n"
163
  return
164
- async with httpx.AsyncClient(timeout=None) as client:
165
- async with client.stream(
166
- "GET", _HF_LOGS_URL,
167
- headers={"Authorization": f"Bearer {token}"},
168
- ) as resp:
169
- async for chunk in resp.aiter_bytes():
170
- yield chunk
 
 
 
 
 
 
171
 
172
  return StreamingResponse(
173
  _generate(),
 
158
  token = os.environ.get("HF_TOKEN", "")
159
 
160
  async def _generate():
161
+ retry = "retry: 60000\n"
162
  if not token:
163
+ yield f"{retry}data: {{\"data\":\"HF_TOKEN not configured\\n\"}}\n\n"
164
  return
165
+ try:
166
+ async with httpx.AsyncClient(timeout=None) as client:
167
+ async with client.stream(
168
+ "GET", _HF_LOGS_URL,
169
+ headers={"Authorization": f"Bearer {token}"},
170
+ ) as resp:
171
+ if resp.status_code != 200:
172
+ yield f"{retry}data: {{\"data\":\"HF API returned {resp.status_code}\\n\"}}\n\n"
173
+ return
174
+ async for chunk in resp.aiter_bytes():
175
+ yield chunk
176
+ except Exception as exc:
177
+ yield f"{retry}data: {{\"data\":\"Stream error: {exc}\\n\"}}\n\n"
178
 
179
  return StreamingResponse(
180
  _generate(),