Overview
TheWebSocketManager class manages WebSocket connections and coordinates audio processing with the AudioProcessor.
Location: backend/src/websocket_manager.py:9-92
Class Definition
Constructor
Parameters
AudioProcessor instance for handling audio processing and OpenAI API calls
ServerMetrics instance for tracking connection counts, errors, and processing times
Example
Methods
handle_connection
websocket_manager.py:18-92
Parameters
FastAPI WebSocket instance representing the client connection
Returns
No return value. Handles the connection until completion or error.Connection Lifecycle
-
Initialize
- Generates 8-character
connection_idfrom UUID - Accepts WebSocket connection
- Increments
active_connectionsandtotal_requestsmetrics - Logs connection establishment
- Generates 8-character
-
Buffer Audio
- Receives binary data chunks via
websocket.receive_bytes() - Buffers chunks in memory
- Tracks total buffered size
- Minimum buffer size: 20,000 bytes (~1 second of audio)
- Receives binary data chunks via
-
Process Audio
- Once minimum size reached, joins buffer chunks
- Calls
audio_processor.process_audio() - Waits for language detection result
-
Send Response
- Success: Sends JSON with language detection results
- Error: Sends JSON with error message
- Always includes timestamp and connection_id
-
Close Connection
- Closes WebSocket
- Decrements
active_connections - Logs connection duration
- Logs current metrics
Response Formats
Success Response:Implementation Details
Fromwebsocket_manager.py:29-72:
Error Handling
Handles three types of errors:- WebSocketDisconnect: Client disconnects (logged, metrics updated)
- Processing errors: Errors from audio processing (error response sent)
- General exceptions: Unexpected errors (logged, error response sent, connection closed)
Example Usage
Frommain.py:51-58:
Constants
Minimum audio buffer size in bytes before processing. Approximately 1 second of audio at 16 kbps.
Connection Tracking
Each connection receives a unique identifier:- Generated from
uuid.uuid4()and truncated to 8 characters - Used in all log messages:
[connection_id] Message - Included in all JSON responses
- Enables end-to-end request tracing
Metrics Integration
The manager updates metrics throughout the connection lifecycle:| Metric | When Updated | How |
|---|---|---|
active_connections | Connection start | +1 |
active_connections | Connection end | -1 |
total_requests | Connection start | +1 |
errors | Processing error | +1 |
processing_times | Successful processing | Append time |
Logging
Comprehensive logging at multiple levels:- INFO: Connection lifecycle, processing results, metrics
- DEBUG: Audio chunk reception, buffer sizes
- ERROR: Processing errors, exceptions
connection_id for correlation.

