Chat System
Overview
The Chat System in PadawanForge provides real-time messaging capabilities through WebSocket connections, supporting both direct/private messages and group lobby conversations. The system is built on Cloudflare Durable Objects for scalable, stateful WebSocket management.
Architecture
Core Components
Durable Objects
- ChatLobby.ts: Manages individual chat rooms and WebSocket connections
- RoomManager.ts: Orchestrates multiple chat lobbies and room lifecycle
- WebSocket Connections: Persistent connections for real-time messaging
Database Tables
direct_messages: Stores private messages between usersrooms: Chat lobby information and metadataroom_messages: Group chat messages in lobbiesnotifications: System notifications and alerts
Chat Modes
1. Direct Messages (Private Chat)
Purpose: Private conversations between two users
Storage: direct_messages table
Features:
- End-to-end privacy
- Message history persistence
- Read receipts
- Typing indicators
API Endpoints:
GET /api/messages/conversation/{uuid}- Get conversation historyPOST /api/messages/message_send- Send private messagePUT /api/messages/{id}/read- Mark message as read
2. Lobby Chat (Group Conversations)
Purpose: Multi-user group conversations in game lobbies
Storage: room_messages table
Features:
- Real-time group messaging
- Room-based organization
- NPC participation support
- Activity feeds
API Endpoints:
GET /api/lobby/{id}/messages- Get lobby messagesPOST /api/lobby/{id}/messages- Send lobby messageGET /api/lobbies- List available lobbies
3. NPC Chat Integration
Purpose: AI-powered conversations with virtual tutors
Features:
- Individual NPC chat sessions
- Lobby NPC participation
- Context-aware responses
- Personality-driven interactions
API Endpoints:
POST /api/npcs/{id}/chat- Chat with specific NPCGET /api/lobby/admin-npc-chat/websocket- Admin NPC chat WebSocket
WebSocket Implementation
Connection Management
interface WebSocketConnection {
id: string;
userId: string;
roomId?: string;
connection: WebSocket;
lastActivity: Date;
}
Message Types
interface ChatMessage {
type: 'message' | 'join' | 'leave' | 'typing' | 'read';
userId: string;
content?: string;
timestamp: Date;
roomId?: string;
}
Real-time Features
- Live Messaging: Instant message delivery
- Typing Indicators: Show when users are typing
- Read Receipts: Track message read status
- Presence: Show online/offline status
- Activity Feeds: Real-time lobby activity updates
Security & Privacy
Authentication
- Session-based authentication for WebSocket connections
- UUID-based user identification
- Role-based access control
Message Privacy
- Direct messages are private between participants
- Lobby messages visible to room members only
- Admin oversight for moderation
Rate Limiting
- Message frequency limits
- Connection limits per user
- Spam protection
Performance Optimizations
Connection Pooling
- Efficient WebSocket connection management
- Automatic cleanup of inactive connections
- Load balancing across Durable Objects
Message Caching
- Recent message caching for fast retrieval
- Pagination for large message histories
- Optimized database queries
Scalability
- Horizontal scaling with Durable Objects
- Geographic distribution via Cloudflare edge
- Automatic failover and recovery
API Reference
WebSocket Endpoints
Connect to Chat Lobby
WebSocket: /api/lobby/{roomId}/websocket
Headers:
- Authorization: Bearer {session_token}
Connect to Admin NPC Chat
WebSocket: /api/lobby/admin-npc-chat/websocket
Headers:
- Authorization: Bearer {admin_token}
Message Format
Send Message
{
"type": "message",
"content": "Hello, world!",
"roomId": "optional-room-id"
}
Join Room
{
"type": "join",
"roomId": "room-uuid"
}
Typing Indicator
{
"type": "typing",
"isTyping": true
}
Error Handling
Connection Errors
- Automatic reconnection attempts
- Graceful degradation to polling
- Error logging and monitoring
Message Delivery
- Retry logic for failed messages
- Offline message queuing
- Delivery confirmation
Rate Limiting
- User-friendly error messages
- Progressive backoff
- Admin notification for abuse
Monitoring & Analytics
Metrics Tracked
- Active connections per room
- Message volume and frequency
- Connection duration
- Error rates and types
Health Checks
- WebSocket endpoint availability
- Database connection status
- Durable Object health
- Performance monitoring
Development Guidelines
Adding New Chat Features
- Define message types in TypeScript interfaces
- Update Durable Object handlers
- Add API endpoints for new functionality
- Update frontend components
- Add comprehensive testing
Testing Chat Features
- Unit tests for message handling
- Integration tests for WebSocket connections
- Load testing for scalability
- Security testing for authentication
Troubleshooting
Common Issues
Connection Drops
- Check network connectivity
- Verify session token validity
- Review rate limiting settings
Message Delays
- Monitor database performance
- Check Durable Object health
- Review message queue status
Missing Messages
- Verify user permissions
- Check message retention settings
- Review error logs
The Chat System provides a robust foundation for real-time communication in PadawanForge, supporting both private and group conversations with AI-powered NPCs.