# Network Library Architecture This document describes the architecture and functionality of the network library, which provides a modular, extensible system for handling network connections across different transport protocols with fallback mechanisms. ## Overview The network library is designed to provide a robust networking layer for real-time applications, particularly focusing on peer-to-peer connections with fallback mechanisms. It supports WebRTC as the primary connection method, with WebSocket and relay server fallbacks when direct connections can't be established. Key features include: - Multiple transport protocols (WebRTC, WebSocket, Relay) - Connection state management - Priority-based message queuing - Message batching and optimization - Network statistics tracking - Automatic reconnection handling - Fallback mechanism when preferred connection methods fail ## Core Components ### 1. Connection Types Defines fundamental types, enums, and interfaces used throughout the system including: - `ConnectionType` enum: Defines supported connection types (WEBSOCKET, WEBRTC, RELAY) - `ConnectionState` enum: Represents connection states (CONNECTING, CONNECTED, DISCONNECTED, FAILED, RECONNECTING) - `MessagePriority` enum: Represents message priority levels (CRITICAL, HIGH, MEDIUM, LOW) - `Connection` interface: Represents a network connection with properties like id, type, state, stats - `ConnectionStats` interface: Tracks performance metrics like latency, jitter, packet loss, reliability score ### 2. Messages Defines the structure and types for all network messages, including: - `MessageType` enum: Defines all supported message types (CONNECT, DISCONNECT, PING, PONG, OFFER, ANSWER, ICE_CANDIDATE, etc.) - `NetworkMessage` interface: Core message structure with type, sender, timestamp, payload, priority - `MessagePayloads` type: Type mapping for payloads of different message types - `MessageFactory`: Utility class for creating properly formatted messages ### 3. Base Connection Provides the foundation for all network connections: - Abstract `BaseConnection` class implementing core functionality: - Connection state management - Message priority queuing - Network statistics tracking (latency, jitter, packet loss) - Automatic reconnection handling - Adaptive batch processing - Ping/Pong heartbeat system ### 4. Base Message Handler Provides foundational message handling functionality: - Abstract `BaseMessageHandler` class: - Message validation and type checking - Message queue management - Priority-based message processing - Error handling and recovery - Event emission for message lifecycle - Batch processing capabilities ### 5. Relay Message Specialized handling for relay-based messaging: - `RelayMessage` class: - Relay message encapsulation - Message routing between peers - Relay chain tracking - Loop prevention - Priority handling for relayed messages - Relay statistics tracking ### 6. Relay Connection Handles relay server-based connections: - `RelayConnectionManager` class: - Fallback connectivity for failed WebRTC connections - Message relaying between peers - Connection state management - Automatic relay server selection - Message priority handling - Connection statistics tracking ### 7. WebRTC Connection Implements WebRTC-specific connection handling: - WebRTC signaling - ICE candidate handling - Direct peer connections - Data channel management - Media stream handling (if needed) ### 8. WebSocket Connection Implements WebSocket-specific connection handling: - Direct server connections - Message serialization/deserialization - Connection monitoring - Automatic reconnection ## Architecture Relationships ```text ┌─────────────────┐ ┌─────────────────┐ │ ConnectionTypes│◄────┤ Messages │ └────────┬────────┘ └────────┬────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ BaseConnection │◄────┤ BaseMessageHandler └────────┬────────┘ └────────┬────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │WebRTCConnection │ │ RelayMessage │ └────────┬────────┘ └────────┬────────┘ │ │ │ ▼ │ ┌─────────────────┐ └─────────────►│RelayConnection │ └─────────────────┘ ``` ## Implementation Details ### Connection Management 1. When establishing connections: - First attempt direct WebRTC connection - If WebRTC fails, fall back to WebSocket connection - If WebSocket is unavailable, use relay server connection 2. Connection State Machine: - CONNECTING → Attempting to establish connection - CONNECTED → Successfully connected - DISCONNECTED → Connection lost - RECONNECTING → Attempting to reestablish lost connection - FAILED → All connection attempts failed ### Message Handling 1. Messages are processed according to priority: - CRITICAL messages processed immediately - HIGH, MEDIUM, LOW messages are queued for batch processing 2. Message Flow: - Messages created through MessageFactory - Messages added to priority queue - Messages processed by BaseMessageHandler - Connection-specific handlers implement sending logic 3. Message Batching: - Related messages combined to reduce network overhead - Batch processing interval adaptively adjusted based on network conditions - Critical messages bypass batching ### Reliability Mechanisms 1. Automatic Reconnection: - Connection failures trigger reconnection attempts - Exponential backoff strategy for retry attempts - Connection monitoring through ping/pong messages 2. Fallback Strategy: - Preferred connection method attempted first - On failure, fall back to next available method - Multiple relay servers used for redundancy 3. Statistics Tracking: - Latency, jitter, packet loss measured - Adaptive timing based on network performance - Connection reliability scoring ## Usage Patterns ### Basic Connection ```typescript // Create connection manager const connectionManager = new ConnectionManager(); // Connect to a peer await connectionManager.connect(peerId); // Send a message connectionManager.sendMessage(peerId, { type: MessageType.STATE_UPDATE, payload: { position: { x: 100, y: 200 } } }); // Listen for messages connectionManager.on('message', (message) => { console.log('Received message:', message); }); // Disconnect connectionManager.disconnect(peerId); ``` ### Advanced Usage ```typescript // Configure connection manager with options const connectionManager = new ConnectionManager({ preferredConnectionType: ConnectionType.WEBRTC, maxRetries: 5, retryDelay: 2000, relayServers: ['wss://relay1.example.com', 'wss://relay2.example.com'] }); // Connect with options await connectionManager.connect(peerId, { timeout: 10000, metadata: { username: 'Player1' } }); // Send prioritized message connectionManager.sendMessage(peerId, { type: MessageType.STATE_UPDATE, payload: { position: { x: 100, y: 200 } }, priority: MessagePriority.HIGH }); // Register type-specific handlers connectionManager.on(MessageType.STATE_UPDATE, (message) => { updateGameState(message.payload); }); // Monitor connection quality connectionManager.on('statistics', (stats, peerId) => { updateNetworkIndicator(stats.latency, stats.packetLoss); }); ``` ## Key Design Patterns 1. **Abstract Factory Pattern** - MessageFactory creates different types of messages 2. **Strategy Pattern** - Different connection implementations can be swapped 3. **Observer Pattern** - Event handling for connection state changes and messages 4. **Command Pattern** - Messages encapsulate operations to be performed 5. **Chain of Responsibility** - Messages processed through handlers 6. **Adapter Pattern** - Consistent interface across different connection technologies ## Testing Requirements The library should be tested with: - Jest tests (.test.ts) for unit testing - Playwright tests (.spec.ts) for integration testing Test coverage should include: - Connection establishment and teardown - Message sending and receiving - Error handling and recovery - Fallback mechanisms - Performance under various network conditions