8.9 KiB
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:
ConnectionTypeenum: Defines supported connection types (WEBSOCKET, WEBRTC, RELAY)ConnectionStateenum: Represents connection states (CONNECTING, CONNECTED, DISCONNECTED, FAILED, RECONNECTING)MessagePriorityenum: Represents message priority levels (CRITICAL, HIGH, MEDIUM, LOW)Connectioninterface: Represents a network connection with properties like id, type, state, statsConnectionStatsinterface: Tracks performance metrics like latency, jitter, packet loss, reliability score
2. Messages
Defines the structure and types for all network messages, including:
MessageTypeenum: Defines all supported message types (CONNECT, DISCONNECT, PING, PONG, OFFER, ANSWER, ICE_CANDIDATE, etc.)NetworkMessageinterface: Core message structure with type, sender, timestamp, payload, priorityMessagePayloadstype: Type mapping for payloads of different message typesMessageFactory: Utility class for creating properly formatted messages
3. Base Connection
Provides the foundation for all network connections:
- Abstract
BaseConnectionclass 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
BaseMessageHandlerclass:- 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:
RelayMessageclass:- 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:
RelayConnectionManagerclass:- 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
┌─────────────────┐ ┌─────────────────┐
│ ConnectionTypes│◄────┤ Messages │
└────────┬────────┘ └────────┬────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ BaseConnection │◄────┤ BaseMessageHandler
└────────┬────────┘ └────────┬────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│WebRTCConnection │ │ RelayMessage │
└────────┬────────┘ └────────┬────────┘
│ │
│ ▼
│ ┌─────────────────┐
└─────────────►│RelayConnection │
└─────────────────┘
Implementation Details
Connection Management
-
When establishing connections:
- First attempt direct WebRTC connection
- If WebRTC fails, fall back to WebSocket connection
- If WebSocket is unavailable, use relay server connection
-
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
-
Messages are processed according to priority:
- CRITICAL messages processed immediately
- HIGH, MEDIUM, LOW messages are queued for batch processing
-
Message Flow:
- Messages created through MessageFactory
- Messages added to priority queue
- Messages processed by BaseMessageHandler
- Connection-specific handlers implement sending logic
-
Message Batching:
- Related messages combined to reduce network overhead
- Batch processing interval adaptively adjusted based on network conditions
- Critical messages bypass batching
Reliability Mechanisms
-
Automatic Reconnection:
- Connection failures trigger reconnection attempts
- Exponential backoff strategy for retry attempts
- Connection monitoring through ping/pong messages
-
Fallback Strategy:
- Preferred connection method attempted first
- On failure, fall back to next available method
- Multiple relay servers used for redundancy
-
Statistics Tracking:
- Latency, jitter, packet loss measured
- Adaptive timing based on network performance
- Connection reliability scoring
Usage Patterns
Basic Connection
// 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
// 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
- Abstract Factory Pattern - MessageFactory creates different types of messages
- Strategy Pattern - Different connection implementations can be swapped
- Observer Pattern - Event handling for connection state changes and messages
- Command Pattern - Messages encapsulate operations to be performed
- Chain of Responsibility - Messages processed through handlers
- 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