Analyze API wrapper functionality#5
Conversation
This commit implements 5 major improvements to make the babel_binance
wrapper production-ready and enterprise-grade:
🎯 1. Custom Exception Classes
- Added hierarchical exception system with specific error types
- BinanceApiException, BinanceRateLimitException, BinanceAuthException
- BinanceNetworkException, BinanceTimeoutException, BinanceParameterException
- Smart error detection (isRetryable, isAuthError, isRateLimitError)
- Better error handling with specific catch blocks
⚡ 2. Rate Limiting System
- Implemented token bucket algorithm for rate limiting
- Tracks REQUEST_WEIGHT, ORDERS, and RAW_REQUESTS limits
- Automatic throttling to prevent API bans
- Syncs with server-reported usage from response headers
- Configurable: throw vs wait, safety margins
- Prevents hitting Binance limits (1200 weight/min, 10 orders/sec)
⏱️ 3. Timeout Configuration
- Added BinanceConfig for comprehensive configuration
- Configurable request and connection timeouts
- Server time synchronization for accurate signatures
- Custom headers, user-agent, proxy support
- Preset configs: default, slow network, high-frequency
- Per-request timeout overrides
🔌 4. WebSocket Improvements
- Complete WebSocket rewrite with auto-reconnection
- Exponential backoff for reconnection attempts
- Ping/pong heartbeat to detect dead connections
- Connection state management (connecting, connected, reconnecting, etc.)
- Support for ALL stream types (not just user data):
* Aggregate trades, kline, ticker, depth
* Combined streams support
* Market data streams
- Production-ready with proper error recovery
📊 5. Logging Mechanism
- Pluggable logging interface (BinanceLogger)
- ConsoleLogger with colored output
- Logs: requests, responses, WebSocket events, rate limits
- Custom logger support for monitoring integration
- Sanitizes sensitive data (API keys, signatures)
- Production observability and debugging
🏗️ Infrastructure Improvements:
- HTTP client wrapper with proper timeout handling
- Better error messages with context
- Resource cleanup with dispose() methods
- Backward compatible API
- Zero breaking changes to existing code
📦 New Files (20 files):
- lib/src/exceptions/* (4 files)
- lib/src/config/* (1 file)
- lib/src/http/* (1 file)
- lib/src/rate_limiting/* (4 files)
- lib/src/logging/* (3 files)
- lib/src/websocket/* (4 files)
Updated Files:
- lib/babel_binance.dart - Export new modules
- lib/src/babel_binance_base.dart - Add config/logger support
- lib/src/binance_base.dart - Integrate all improvements
- lib/src/websockets.dart - Use new WebSocket client
Impact:
✅ Production-ready error handling
✅ Prevents API rate limit bans
✅ Configurable timeouts
✅ Reliable WebSocket connections
✅ Observable and debuggable
✅ Enterprise-grade quality
Breaking Changes: None (backward compatible)
Usage Example:
```dart
final binance = Binance(
apiKey: 'YOUR_KEY',
apiSecret: 'YOUR_SECRET',
config: BinanceConfig(
requestTimeout: Duration(seconds: 30),
rateLimitConfig: RateLimitConfig.conservative,
),
logger: ConsoleLogger(minLevel: LogLevel.debug),
);
try {
final ticker = await binance.spot.market.get24HrTicker('BTCUSDT');
} on BinanceRateLimitException catch (e) {
print('Rate limited! Retry after ${e.retryAfterSeconds}s');
} on BinanceAuthException catch (e) {
print('Auth failed: ${e.message}');
}
```
|
Caution Review failedThe pull request is closed. WalkthroughThe PR significantly expands babel_binance's public API infrastructure by introducing configuration management, comprehensive logging, structured exception handling, rate limiting, an HTTP wrapper, and refactored WebSocket support. The main Binance classes are enhanced to integrate these systems throughout the request lifecycle, including server-time synchronization and request signing. Multiple new modules are added and exported. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Binance
participant BinanceBase
participant RateLimiter
participant ServerTimeSync
participant HttpClient
participant BinanceException
User->>Binance: new Binance(apiKey, apiSecret, config, logger)
Binance->>BinanceBase: constructor with config & logger
BinanceBase->>RateLimiter: initialize with config.rateLimitConfig
BinanceBase->>ServerTimeSync: initServerTimeSync()
ServerTimeSync-->>BinanceBase: serverTimeOffset established
User->>Binance: sendRequest(method, path, params, weight, isOrder)
Binance->>BinanceBase: delegate to sendRequest
BinanceBase->>RateLimiter: checkLimit(weight, isOrder)
alt Rate limit exceeded
RateLimiter-->>BinanceException: throw BinanceRateLimitException
else Within limits
RateLimiter->>RateLimiter: consume tokens
end
BinanceBase->>ServerTimeSync: getSyncedTimestamp()
alt Sync needed
ServerTimeSync->>HttpClient: GET /api/v3/time
HttpClient-->>ServerTimeSync: server time
ServerTimeSync->>ServerTimeSync: update serverTimeOffset
end
BinanceBase->>BinanceBase: compute signature with synced timestamp
BinanceBase->>HttpClient: get/post/delete/put with timeout
HttpClient-->>BinanceBase: http.Response
alt Error response
BinanceBase->>BinanceException: _createExceptionFromResponse()
BinanceException-->>BinanceBase: typed exception
else Success
BinanceBase->>RateLimiter: processResponse(headers)
RateLimiter->>RateLimiter: update weight from X-MBX-USED-WEIGHT-1M
end
BinanceBase-->>Binance: Map<String, dynamic>
Binance-->>User: response data
User->>Binance: dispose()
Binance->>BinanceBase: dispose()
BinanceBase->>HttpClient: close()
sequenceDiagram
participant User
participant BinanceWebSocket
participant BinanceWebSocketStream
participant WebSocketChannel
participant MessageLoop
participant ReconnectLogic
User->>BinanceWebSocket: connectMarketStream(streamConfig)
BinanceWebSocket->>BinanceWebSocketStream: _connectToStream(url)
alt Stream exists
BinanceWebSocketStream-->>BinanceWebSocket: return existing stream
else New stream
BinanceWebSocketStream->>BinanceWebSocketStream: new BinanceWebSocketStream(url, config)
BinanceWebSocket->>BinanceWebSocketStream: connect()
end
BinanceWebSocketStream->>WebSocketChannel: connect with timeout
WebSocketChannel-->>BinanceWebSocketStream: connected
BinanceWebSocketStream->>MessageLoop: start listening to messages
BinanceWebSocketStream->>MessageLoop: start ping/pong heartbeat
alt Message received
WebSocketChannel-->>MessageLoop: message event
MessageLoop->>MessageLoop: emit to _messageController
else Connection lost
MessageLoop->>ReconnectLogic: on error or close
ReconnectLogic->>ReconnectLogic: exponential backoff delay
ReconnectLogic->>BinanceWebSocketStream: auto-reconnect if enabled
else Pong timeout
ReconnectLogic->>BinanceWebSocketStream: trigger reconnect
end
User->>BinanceWebSocket: disconnectAll()
BinanceWebSocket->>BinanceWebSocketStream: disconnect each stream
BinanceWebSocketStream->>WebSocketChannel: close
BinanceWebSocketStream->>MessageLoop: cancel subscription
BinanceWebSocketStream->>ReconnectLogic: cancel timers
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas requiring extra attention:
Poem
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (21)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
This commit implements 5 major improvements to make the babel_binance wrapper production-ready and enterprise-grade:
🎯 1. Custom Exception Classes
⚡ 2. Rate Limiting System
⏱️ 3. Timeout Configuration
🔌 4. WebSocket Improvements
📊 5. Logging Mechanism
🏗️ Infrastructure Improvements:
📦 New Files (20 files):
Updated Files:
Impact:
✅ Production-ready error handling
✅ Prevents API rate limit bans
✅ Configurable timeouts
✅ Reliable WebSocket connections
✅ Observable and debuggable
✅ Enterprise-grade quality
Breaking Changes: None (backward compatible)
Usage Example:
Summary by CodeRabbit