Skip to content

Commit b0af18f

Browse files
committed
refactor(collab): move all error messages to error.py
1 parent 1900ec8 commit b0af18f

File tree

4 files changed

+28
-74
lines changed

4 files changed

+28
-74
lines changed
Lines changed: 9 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from typing import Dict
2-
from fastapi import WebSocket, WebSocketDisconnect
32
import uuid
43
import asyncio
54
from app.schemas.messages import CollaboratorConnectMessage, CollaboratorDisconnectMessage, DisplayMessage
5+
from app.core.errors import SessionNotFoundError, UserNotFoundError, InvalidUserIDsError
66

77
class ConnectionManager:
88
def __init__(self):
@@ -11,7 +11,7 @@ def __init__(self):
1111

1212
def init_session(self, user_ids: list[str]) -> str:
1313
if len(user_ids) != 2:
14-
raise ValueError("user_ids must contain exactly two user IDs.")
14+
raise InvalidUserIDsError()
1515
session_id = self.generate_uuid(user_ids[0], user_ids[1])
1616

1717
self.active_connections[session_id] = {}
@@ -28,11 +28,11 @@ def _get_collaborator_q(self, session_id, user_id):
2828

2929
async def on_connect(self, session_id: str, user_id: str, out_q: asyncio.Queue):
3030
if session_id not in self.active_connections:
31-
raise ValueError("Session not initialized")
31+
raise SessionNotFoundError()
3232

3333
if user_id not in self.active_connections[session_id]:
34-
raise ValueError("user_id not available in this session")
35-
34+
raise UserNotFoundError()
35+
3636
self.active_connections[session_id][user_id] = out_q
3737

3838
collaborator_q = self._get_collaborator_q(session_id, user_id)
@@ -48,11 +48,11 @@ async def on_connect(self, session_id: str, user_id: str, out_q: asyncio.Queue):
4848

4949
async def on_disconnect(self, session_id: str, user_id: str):
5050
if session_id not in self.active_connections:
51-
raise ValueError("Session not initialized")
51+
raise SessionNotFoundError()
5252

5353
if user_id not in self.active_connections[session_id]:
54-
raise ValueError("user_id not available in this session")
55-
54+
raise UserNotFoundError()
55+
5656
self.active_connections[session_id][user_id] = None
5757

5858
collaborator_q = self._get_collaborator_q(session_id, user_id)
@@ -71,70 +71,9 @@ async def on_message(self, session_id: str, user_id: str, msg: str):
7171
await collaborator_q.put(DisplayMessage(msg=msg))
7272

7373
def generate_uuid(self, user1: str, user2: str) -> str:
74-
namespace = uuid.NAMESPACE_DNS # or uuid.NAMESPACE_URL, etc.
74+
namespace = uuid.NAMESPACE_DNS
7575
seed = ''.join(sorted([user1, user2]))
7676
return str(uuid.uuid5(namespace, seed))
7777

78-
# async def connect(self, session_id: str, user_id: str, ws: WebSocket):
79-
# if session_id not in self.active_connections:
80-
# raise ValueError("Session not initialized.")
81-
82-
# if user_id not in self.active_connections[session_id]:
83-
# raise ValueError("user_id not recognized in this session.")
84-
85-
# await ws.accept()
86-
# self.active_connections[session_id][user_id] = ws
87-
88-
# # Notify any waiting coroutines that a user has connected
89-
# async with self.condition:
90-
# self.condition.notify_all()
91-
92-
# return None
93-
94-
# async def await_collaborator_ws(self, session_id: str, user_id: str) -> WebSocket | None:
95-
# if session_id not in self.active_connections:
96-
# raise ValueError("Session not initialized.")
97-
98-
# session_data = self.active_connections[session_id]
99-
# collaborator_id = next((uid for uid in session_data if uid != user_id), None)
100-
101-
# user_ws = session_data[user_id]
102-
# collaborator_ws = session_data[collaborator_id]
103-
104-
# try:
105-
# if collaborator_ws is None:
106-
# async with self.condition:
107-
# await user_ws.send_text(f"Waiting for collaborator {collaborator_id} to connect...")
108-
# await self.condition.wait_for(lambda: session_data[collaborator_id] is not None)
109-
# await user_ws.send_text(f"Collaborator {collaborator_id} connected!")
110-
# collaborator_ws = session_data[collaborator_id]
111-
# except Exception as e:
112-
# print(f"Error while waiting for collaborator: {e}")
113-
# return None
114-
115-
# return session_data[collaborator_id]
116-
117-
# async def disconnect(self, session_id: str, user_id: str):
118-
# if session_id not in self.active_connections:
119-
# return
120-
121-
# session_data = self.active_connections[session_id]
122-
123-
# ws = session_data[user_id]
124-
# session_data[user_id] = None
125-
126-
# # Notify any waiting coroutines that a user has disconnected
127-
# async with self.condition:
128-
# self.condition.notify_all()
129-
130-
# if ws:
131-
# try:
132-
# await ws.close()
133-
# except Exception:
134-
# pass
135-
136-
# def get_active_connections(self, session_id: str):
137-
# return self.active_connections.get(session_id, {})
138-
13978

14079
connection_manager = ConnectionManager()
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
3+
class InvalidUserIDsError(Exception):
4+
"""Exception raised when the provided user IDs are invalid."""
5+
msg = "user_ids must contain exactly two user IDs."
6+
pass
7+
8+
class UserNotFoundError(Exception):
9+
"""Exception raised when a user is not found in the system."""
10+
msg = "user_id not available in this session"
11+
pass
12+
13+
class SessionNotFoundError(Exception):
14+
"""Exception raised when a session is not found."""
15+
msg = "Session not initialized"
16+
pass

services/collaboration-service/app/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
app.include_router(ws_sessions.router, prefix="/ws/sessions")
88

99
## API for testing connection
10-
@app.get("/ping")
11-
def ping():
12-
return {"message": "Pong"}
10+
@app.get("/health")
11+
def health_check():
12+
return {"status": "Healthy"}

services/collaboration-service/app/rest/sessions.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
@router.post("/", response_model=CreateSessionResponse)
99
def create_session(request: CreateSessionRequest):
10-
# print(f"Creating session for users: {request.user_ids}")
1110
user_ids = request.user_ids
1211
session_id = connection_manager.init_session(user_ids)
1312
return CreateSessionResponse(session_id=session_id)

0 commit comments

Comments
 (0)