LiamKhoaLe commited on
Commit
67e2bd6
·
1 Parent(s): d6fcb7e

Upd ws foward_progress

Browse files
Files changed (1) hide show
  1. app/routers/ws_progress.py +30 -17
app/routers/ws_progress.py CHANGED
@@ -26,28 +26,41 @@ async def _delete_everything(doc_id: str):
26
 
27
  async def forward_progress(websocket: WebSocket, document_id: str):
28
  """Handle state change allowing frontend to connect and update seamlessly."""
29
- db = get_db()
30
  try:
 
 
 
 
 
 
31
  while True:
32
  doc = await db.documents.find_one({"_id": document_id})
33
  if not doc:
34
  await websocket.send_json({"status": "NOT_FOUND"})
35
- else:
36
- status = doc.get("status", "UNKNOWN")
37
- await websocket.send_json({"status": status})
38
- if status in {"READY", "FAILED"}:
39
- break
40
- await asyncio.sleep(2)
41
-
42
- except WebSocketDisconnect:
43
- logger.info(f"💨 client closed WS for {document_id} – deleting artefacts")
44
- await _delete_everything(document_id)
45
-
 
 
 
 
 
 
46
  except Exception as e:
47
- logger.exception(f"📡 WS loop crashed for {document_id}: {e}")
48
- with contextlib.suppress(Exception):
49
  await websocket.send_json({"status": "ERROR"})
50
-
51
- finally:
52
- with contextlib.suppress(Exception):
53
  await websocket.close()
 
 
 
 
 
26
 
27
  async def forward_progress(websocket: WebSocket, document_id: str):
28
  """Handle state change allowing frontend to connect and update seamlessly."""
29
+ logger.info(f"📡 WebSocket accepted for doc {document_id}")
30
  try:
31
+ db = get_db()
32
+ doc = await db.documents.find_one({"_id": document_id})
33
+ if not doc:
34
+ await websocket.send_json({"status": "NOT_FOUND"})
35
+ return
36
+ # Valid doc
37
  while True:
38
  doc = await db.documents.find_one({"_id": document_id})
39
  if not doc:
40
  await websocket.send_json({"status": "NOT_FOUND"})
41
+ return
42
+ # Get status real-time
43
+ status = doc.get("status")
44
+ if status == "READY":
45
+ await websocket.send_json({
46
+ "status": "READY",
47
+ "id": doc["_id"],
48
+ "title": doc.get("title"),
49
+ "source": doc.get("metadata", {}).get("source", "unknown"),
50
+ "documentId": doc["_id"],
51
+ "uri": f"/import/textbook/{doc['_id']}",
52
+ })
53
+ break
54
+ elif status == "FAILED":
55
+ await websocket.send_json({"status": "FAILED"})
56
+ break
57
+ await asyncio.sleep(1.5)
58
  except Exception as e:
59
+ logger.exception(f"📡 WebSocket failed for doc {document_id}: {e}")
60
+ try:
61
  await websocket.send_json({"status": "ERROR"})
 
 
 
62
  await websocket.close()
63
+ except Exception:
64
+ pass
65
+ finally:
66
+ logger.info(f"📡 WebSocket closed for doc {document_id}")