To integrate a command handler into your WebSocket connection use case that processes different commands and sends corresponding messages to Apache Pulsar using your PulsarManager, follow these steps:
-
Define Command Handlers:
Create specific handler methods for each command your application supports.
-
Parse and Dispatch Commands:
In the while True loop, parse incoming messages, identify the command, and dispatch it to the appropriate handler.
-
Integrate with PulsarManager:
Use your PulsarManager to send messages to Apache Pulsar within each command handler.
-
Optimize Pulsar Producer Usage:
Reuse Pulsar producers instead of creating and closing them for each message to improve performance.
-
Handle Errors and Responses:
Implement error handling and send appropriate responses back to the client.
Here's a comprehensive implementation based on your existing code:
1. Update ConnectionManager (if needed)
Ensure your ConnectionManager can handle any additional communication or state management required by the command handlers. From your provided code, it seems sufficient as is for managing active connections and sending messages.
2. Define the PulsarManager
Assuming you have a PulsarManager interface and a concrete implementation, ensure it efficiently manages Pulsar producers. Here's an example of how you might implement it:
# pulsar_manager.py
import pulsar
import asyncio
from typing import Dict
class PulsarManager:
def __init__(self, service_url: str):
self.client = pulsar.Client(service_url)
self.producers: Dict[str, pulsar.Producer] = {}
self.lock = asyncio.Lock()
async def get_producer(self, topic: str) -> pulsar.Producer:
async with self.lock:
if topic not in self.producers:
self.producers[topic] = self.client.create_producer(topic)
return self.producers[topic]
async def send_message(self, topic: str, message: str) -> None:
producer = await self.get_producer(topic)
producer.send_async(message.encode('utf-8'), callback=self._send_callback)
def _send_callback(self, message_id, exception):
if exception:
# Handle send failure (e.g., log it)
print(f"Failed to send message: {exception}")
else:
# Optionally handle send success
pass
def close(self):
for producer in self.producers.values():
producer.close()
self.client.close()
3. Update the HandleWebsocketConnectionUseCase
Enhance your HandleWebsocketConnectionUseCase to include command handling logic:
# handle_websocket_connection.py
import asyncio
import uuid
import json
from typing import Dict, Any
from fastapi import WebSocket
from fastapi.websockets import WebSocketDisconnect
from usecases import BaseUseCase
from auth.services import TokenServiceInterface
from diamond.services.diamond_service import DiamondServiceInterface
from pulsar_manager import PulsarManager
class HandleWebsocketConnectionUseCase(BaseUseCase):
def __init__(
self,
token_service: TokenServiceInterface,
diamond_service: DiamondServiceInterface,
pulsar_manager: PulsarManager,
) -> None:
self._token_service = token_service
self._diamond_service = diamond_service
self._pulsar_manager = pulsar_manager
self._command_handlers = {
"create_profile": self._handle_create_profile,
"update_profile": self._handle_update_profile,
# Add more command handlers as needed
}
self.websocket: WebSocket = None # Will be set in execute
async def execute(self, websocket: WebSocket, connection_state: str) -> None:
self.websocket = websocket # Store reference for sending responses
await self._diamond_service.accept_ws_connection(websocket, connection_state)
try:
# Receive and validate authentication token
token = await self._diamond_service.get_auth_token(await websocket.receive_text())
token_data = await self._token_service.get_access_token_data(token)
# Connect the WebSocket
await self._diamond_service.connect_websocket(
auth_user_uuid=token_data.auth_user_uuid,
state=connection_state,
websocket=websocket
)
# Listen for incoming messages
while True:
message_text = await websocket.receive_text()
await self._handle_message(message_text, token_data.auth_user_uuid)
except WebSocketDisconnect:
if token_data:
await self._diamond_service.disconnect_websocket(
auth_user_uuid=token_data.auth_user_uuid,
state=connection_state
)
except Exception as e:
await self._send_error(str(e))
async def _handle_message(self, message_text: str, auth_user_uuid: uuid.UUID):
try:
message = json.loads(message_text)
command = message.get("command")
payload = message.get("payload")
if not command:
raise ValueError("Missing 'command' in message.")
handler = self._command_handlers.get(command)
if not handler:
raise ValueError(f"Unsupported command: {command}")
await handler(payload, auth_user_uuid)
except json.JSONDecodeError:
await self._send_error("Invalid JSON format.")
except Exception as e:
await self._send_error(str(e))
async def _handle_create_profile(self, payload: Dict[str, Any], auth_user_uuid: uuid.UUID):
# Validate payload as necessary
command_message = {
"command": "create_profile",
"payload": payload,
"auth_user_uuid": str(auth_user_uuid) # Include user context if needed
}
# Send the command to Pulsar
await self._pulsar_manager.send_message("create_profile_topic", json.dumps(command_message))
# Optionally, send an acknowledgment back to the client
await self.websocket.send_text(json.dumps({"status": "create_profile command received."}))
async def _handle_update_profile(self, payload: Dict[str, Any], auth_user_uuid: uuid.UUID):
command_message = {
"command": "update_profile",
"payload": payload,
"auth_user_uuid": str(auth_user_uuid)
}
await self._pulsar_manager.send_message("update_profile_topic", json.dumps(command_message))
await self.websocket.send_text(json.dumps({"status": "update_profile command received."}))
async def _send_error(self, error_message: str):
error_response = {"error": error_message}
if self.websocket:
await self.websocket.send_text(json.dumps(error_response))
4. Integrate the Use Case into Your WebSocket Endpoint
Ensure your WebSocket endpoint utilizes the updated use case:
# main.py or your FastAPI route file
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends
from handle_websocket_connection import HandleWebsocketConnectionUseCase
from pulsar_manager import PulsarManager
from auth.services import TokenService
from diamond.services.diamond_service import DiamondService
app = FastAPI()
# Initialize your services and managers
token_service = TokenService()
diamond_service = DiamondService()
pulsar_manager = PulsarManager(service_url="pulsar://localhost:6650")
# Dependency injection function
def get_handle_websocket_use_case():
return HandleWebsocketConnectionUseCase(
token_service=token_service,
diamond_service=diamond_service,
pulsar_manager=pulsar_manager
)
@app.websocket("/ws/{connection_state}")
async def websocket_endpoint(
websocket: WebSocket,
connection_state: str,
use_case: HandleWebsocketConnectionUseCase = Depends(get_handle_websocket_use_case)
):
await use_case.execute(websocket, connection_state)
5. Ensure Proper Cleanup
Make sure to properly close Pulsar producers and the client when your application shuts down:
# main.py or your FastAPI startup/shutdown events
@app.on_event("shutdown")
def shutdown_event():
pulsar_manager.close()
6. Additional Considerations
- Validation: Enhance payload validation within each command handler to ensure data integrity.
- Security: Ensure that only authorized users can execute certain commands.
- Scalability: Depending on the load, consider how many concurrent WebSocket connections and Pulsar messages your system can handle.
- Error Handling: Implement comprehensive logging and error tracking to monitor and debug issues effectively.
- Extensibility: Design your command handlers to easily add new commands without significant refactoring.
7. Example Workflow
-
Client Connects:
- The client establishes a WebSocket connection and sends an authentication token.
-
Authentication:
- The server validates the token and establishes the connection.
-
Client Sends Command:
-
Server Processes Command:
- The server parses the message, identifies the
create_profile command, and invokes the _handle_create_profile method.
-
Server Sends to Pulsar:
- The
_handle_create_profile method constructs a message and sends it to the create_profile_topic in Pulsar using the PulsarManager.
-
Acknowledgment:
- The server optionally sends an acknowledgment back to the client confirming receipt of the command.
8. Testing
After implementing, thoroughly test each command:
- Valid Commands: Ensure that valid commands are processed correctly and messages are sent to Pulsar.
- Invalid Commands: Verify that unsupported commands are handled gracefully with appropriate error messages.
- Malformed Messages: Test how the system handles invalid JSON or incorrectly structured messages.
- Concurrency: Simulate multiple concurrent WebSocket connections to ensure the system scales and behaves as expected.
9. Sample Implementation
Here’s the complete sample implementation based on the steps above:
# pulsar_manager.py
import pulsar
import asyncio
from typing import Dict
class PulsarManager:
def __init__(self, service_url: str):
self.client = pulsar.Client(service_url)
self.producers: Dict[str, pulsar.Producer] = {}
self.lock = asyncio.Lock()
async def get_producer(self, topic: str) -> pulsar.Producer:
async with self.lock:
if topic not in self.producers:
self.producers[topic] = self.client.create_producer(topic)
return self.producers[topic]
async def send_message(self, topic: str, message: str) -> None:
producer = await self.get_producer(topic)
producer.send_async(message.encode('utf-8'), callback=self._send_callback)
def _send_callback(self, message_id, exception):
if exception:
print(f"Failed to send message: {exception}")
else:
pass # Message sent successfully
def close(self):
for producer in self.producers.values():
producer.close()
self.client.close()
# handle_websocket_connection.py
import asyncio
import uuid
import json
from typing import Dict, Any
from fastapi import WebSocket
from fastapi.websockets import WebSocketDisconnect
from usecases import BaseUseCase
from auth.services import TokenServiceInterface
from diamond.services.diamond_service import DiamondServiceInterface
from pulsar_manager import PulsarManager
class HandleWebsocketConnectionUseCase(BaseUseCase):
def __init__(
self,
token_service: TokenServiceInterface,
diamond_service: DiamondServiceInterface,
pulsar_manager: PulsarManager,
) -> None:
self._token_service = token_service
self._diamond_service = diamond_service
self._pulsar_manager = pulsar_manager
self._command_handlers = {
"create_profile": self._handle_create_profile,
"update_profile": self._handle_update_profile,
# Add other handlers as needed
}
self.websocket: WebSocket = None
async def execute(self, websocket: WebSocket, connection_state: str) -> None:
self.websocket = websocket
await self._diamond_service.accept_ws_connection(websocket, connection_state)
try:
token = await self._diamond_service.get_auth_token(await websocket.receive_text())
token_data = await self._token_service.get_access_token_data(token)
await self._diamond_service.connect_websocket(
auth_user_uuid=token_data.auth_user_uuid,
state=connection_state,
websocket=websocket
)
while True:
message_text = await websocket.receive_text()
await self._handle_message(message_text, token_data.auth_user_uuid)
except WebSocketDisconnect:
if token_data:
await self._diamond_service.disconnect_websocket(
auth_user_uuid=token_data.auth_user_uuid,
state=connection_state
)
except Exception as e:
await self._send_error(str(e))
async def _handle_message(self, message_text: str, auth_user_uuid: uuid.UUID):
try:
message = json.loads(message_text)
command = message.get("command")
payload = message.get("payload")
if not command:
raise ValueError("Missing 'command' in message.")
handler = self._command_handlers.get(command)
if not handler:
raise ValueError(f"Unsupported command: {command}")
await handler(payload, auth_user_uuid)
except json.JSONDecodeError:
await self._send_error("Invalid JSON format.")
except Exception as e:
await self._send_error(str(e))
async def _handle_create_profile(self, payload: Dict[str, Any], auth_user_uuid: uuid.UUID):
command_message = {
"command": "create_profile",
"payload": payload,
"auth_user_uuid": str(auth_user_uuid)
}
await self._pulsar_manager.send_message("create_profile_topic", json.dumps(command_message))
await self.websocket.send_text(json.dumps({"status": "create_profile command received."}))
async def _handle_update_profile(self, payload: Dict[str, Any], auth_user_uuid: uuid.UUID):
command_message = {
"command": "update_profile",
"payload": payload,
"auth_user_uuid": str(auth_user_uuid)
}
await self._pulsar_manager.send_message("update_profile_topic", json.dumps(command_message))
await self.websocket.send_text(json.dumps({"status": "update_profile command received."}))
async def _send_error(self, error_message: str):
error_response = {"error": error_message}
if self.websocket:
await self.websocket.send_text(json.dumps(error_response))
# main.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends
from handle_websocket_connection import HandleWebsocketConnectionUseCase
from pulsar_manager import PulsarManager
from auth.services import TokenService
from diamond.services.diamond_service import DiamondService
app = FastAPI()
# Initialize services and managers
token_service = TokenService()
diamond_service = DiamondService()
pulsar_manager = PulsarManager(service_url="pulsar://localhost:6650")
# Dependency Injection
def get_handle_websocket_use_case():
return HandleWebsocketConnectionUseCase(
token_service=token_service,
diamond_service=diamond_service,
pulsar_manager=pulsar_manager
)
@app.on_event("shutdown")
def shutdown_event():
pulsar_manager.close()
@app.websocket("/ws/{connection_state}")
async def websocket_endpoint(
websocket: WebSocket,
connection_state: str,
use_case: HandleWebsocketConnectionUseCase = Depends(get_handle_websocket_use_case)
):
await use_case.execute(websocket, connection_state)
10. Testing the Implementation
Setup Apache Pulsar:
Ensure that Apache Pulsar is running and the necessary topics (create_profile_topic, update_profile_topic, etc.) are created.
Test WebSocket Connection:
Use a WebSocket client (like websocat or browser-based tools) to connect to your WebSocket endpoint and send commands.
Example Commands:
-
Create Profile:
{
"command": "create_profile",
"payload": {
"username": "john_doe",
"email": "john@example.com"
}
}
-
Update Profile:
{
"command": "update_profile",
"payload": {
"user_id": "12345",
"email": "john_new@example.com"
}
}
Verify Pulsar Messages:
Consume messages from the respective Pulsar topics to ensure that commands are being sent correctly.
11. Enhancements and Best Practices
-
Dynamic Command Registration:
Instead of hardcoding command handlers, consider dynamic registration to make the system more extensible.
-
Payload Validation:
Use libraries like pydantic to validate incoming payloads against predefined schemas.
-
Logging:
Implement structured logging to monitor command handling and Pulsar interactions.
-
Retry Mechanisms:
Implement retry logic for failed Pulsar message sends to enhance reliability.
-
Security:
Ensure that only authenticated and authorized users can send specific commands. Use encryption (like WSS) for WebSocket connections to protect data in transit.
-
Scalability:
Consider the scalability of your PulsarManager and ensure it can handle high-throughput scenarios by properly managing producers and connections.
Conclusion
By following the outlined steps, you've integrated a robust command handling mechanism into your WebSocket connection use case. This setup ensures that client commands are efficiently processed and dispatched to Apache Pulsar, maintaining the integrity and scalability of your CQRS architecture. Remember to continually monitor and refine your implementation based on real-world usage and evolving requirements.