WebSocket API¶
NewLoom provides real-time updates through WebSocket connections using Django Channels. This section documents the available WebSocket endpoints and their usage.
Authentication¶
WebSocket connections require authentication. Authentication is handled through URL parameters:
Token Authentication:
?token=<your-token>Session Authentication: Uses Django session cookie (for browser-based access)
Connection URLs¶
Chat WebSocket¶
ws://localhost:8000/ws/chat/?token=<your-token>
- Features:
Real-time chat messages
Message status updates
Typing indicators
Error notifications
Message Formats:
Send Message:
{
"type": "message",
"content": "Your message here",
"chat_id": 123
}
Receive Message:
{
"type": "message",
"message": {
"id": 456,
"content": "Message content",
"user": "username",
"timestamp": "2024-02-05T12:00:00Z",
"chat_id": 123
}
}
Typing Indicator:
{
"type": "typing",
"chat_id": 123,
"user": "username",
"is_typing": true
}
Stream Status WebSocket¶
ws://localhost:8000/ws/streams/?token=<your-token>
- Features:
Real-time stream status updates
Execution statistics
Error notifications
Message Formats:
Stream Status Update:
{
"type": "status_update",
"stream_id": 123,
"status": "running",
"timestamp": "2024-02-05T12:00:00Z"
}
Execution Statistics:
{
"type": "execution_stats",
"stream_id": 123,
"stats": {
"processed_count": 50,
"failed_count": 2,
"total_count": 52,
"execution_time": "00:05:23"
}
}
Error Notification:
{
"type": "error",
"stream_id": 123,
"error": {
"message": "Error description",
"code": "ERROR_CODE",
"timestamp": "2024-02-05T12:00:00Z"
}
}
Error Handling¶
Connection Errors:
{
"type": "error",
"code": "connection_error",
"message": "Authentication failed"
}
Message Format Errors:
{
"type": "error",
"code": "invalid_format",
"message": "Invalid message format"
}
Permission Errors:
{
"type": "error",
"code": "permission_denied",
"message": "Not authorized for this chat"
}
Connection Management¶
1. Heartbeat¶
Send periodic heartbeat to keep connection alive:
{
"type": "heartbeat"
}
2. Disconnection¶
Clean disconnection message:
{
"type": "disconnect"
}
Best Practices¶
- Connection Management:
Implement exponential backoff for reconnection attempts
Handle connection errors gracefully
Send periodic heartbeats
- Message Handling:
Validate message format before sending
Handle all message types appropriately
Implement error handling for failed messages
- Performance:
Limit subscription to necessary channels
Implement message batching for bulk updates
Handle reconnection efficiently
Example Usage¶
JavaScript WebSocket Client:
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/chat/?token='
+ yourAuthToken
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
switch(data.type) {
case 'message':
handleNewMessage(data.message);
break;
case 'typing':
handleTypingIndicator(data);
break;
case 'error':
handleError(data);
break;
}
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
// Send a message
chatSocket.send(JSON.stringify({
'type': 'message',
'content': 'Hello, World!',
'chat_id': 123
}));
Security Considerations¶
- Authentication:
Always use secure tokens
Implement token expiration
Validate user permissions
- Data Validation:
Validate all incoming messages
Sanitize user input
Implement rate limiting
- Connection Security:
Use WSS (WebSocket Secure) in production
Implement proper error handling
Monitor for suspicious activity