Files
LEDMatrix/BACKGROUND_SERVICE_README.md
Chuck 9dc1118d79 Feature/background season data (#46)
* Fix NCAAFB ranking display issue

- Remove duplicate ranking system that was drawing rankings behind team logos
- Old system (_get_rank) was drawing rankings at top of logos
- New system (_fetch_team_rankings) correctly draws rankings in bottom corners
- Remove old ranking calls from live, recent, and upcoming game drawing functions
- Remove unnecessary _fetch_rankings() calls from update methods
- Rankings now only appear in designated corner positions, not overlapping logos

Fixes issue where team rankings/betting lines were being drawn behind
team logos instead of replacing team records in the corners.

* Add missing show_ranking and show_records options to NCAAFB web UI

- Add show_ranking option to NCAAFB scoreboard config template
- Add show_records and show_ranking toggle switches to NCAAFB web UI
- Update JavaScript form collection to include new fields
- Users can now control whether to show team records or rankings via web interface

This completes the fix for NCAAFB ranking display - users can now enable
show_ranking in the web UI to see AP Top 25 rankings instead of team records.

* Implement Background Threading for Season Data Fetching

Phase 1: Background Season Data Fetching - COMPLETED

Key Features:
- Created BackgroundDataService class with thread-safe operations
- Implemented automatic retry logic with exponential backoff
- Modified NFL manager to use background service
- Added immediate partial data return for non-blocking display
- Comprehensive logging and statistics tracking

Performance Benefits:
- Main display loop no longer blocked by API calls
- Season data always fresh with background updates
- Better user experience during data fetching

Files Added/Modified:
- src/background_data_service.py (NEW)
- src/nfl_managers.py (updated)
- config/config.template.json (updated)
- test_background_service.py (NEW)
- BACKGROUND_SERVICE_README.md (NEW)

* Fix data validation issues in background service

- Add comprehensive data structure validation in NFL managers
- Handle malformed events gracefully with proper error logging
- Validate cached data format and handle legacy formats
- Add data validation in background service response parsing
- Fix TypeError: string indices must be integers, not 'str'

This fixes the error where events were being treated as strings
instead of dictionaries, causing crashes in recent/upcoming games.

* Phase 2: Apply Background Service to Major Sport Managers

 Applied background service support to:
- NCAAFB Manager (College Football)
- NBA Manager (Basketball)
- NHL Manager (Hockey)
- MLB Manager (Baseball)

🔧 Key Features Added:
- Background service initialization for each sport
- Configurable workers, timeouts, and retry settings
- Graceful fallback when background service is disabled
- Comprehensive logging for monitoring

⚙️ Configuration Updates:
- Added background_service config section to NBA
- Added background_service config section to NHL
- Added background_service config section to NCAAFB
- Each sport can independently enable/disable background service

📈 Performance Benefits:
- Season data fetching no longer blocks display loops
- Immediate response with cached/partial data
- Background threads handle heavy API calls
- Better responsiveness across all supported sports

Next: Apply to remaining managers (MiLB, Soccer, etc.)

* Fix Python compatibility issue in BackgroundDataService shutdown

🐛 Bug Fix:
- Fixed TypeError in ThreadPoolExecutor.shutdown() for older Python versions
- Added try/catch to handle timeout parameter compatibility
- Fallback gracefully for Python < 3.9 that doesn't support timeout parameter

🔧 Technical Details:
- ThreadPoolExecutor.shutdown(timeout=) was added in Python 3.9
- Older versions only support shutdown(wait=)
- Added compatibility layer with proper error handling

 Result:
- No more shutdown exceptions on older Python versions
- Graceful degradation for different Python environments
- Maintains full functionality on newer Python versions

* Phase 2 Complete: Background Service Applied to All Sport Managers

🎉 MAJOR MILESTONE: Complete Background Service Rollout

 All Sport Managers Now Support Background Service:
- MiLB Manager (Minor League Baseball)
- Soccer Manager (Multiple leagues: Premier League, La Liga, etc.)
- Leaderboard Manager (Multi-sport standings)
- Odds Ticker Manager (Live betting odds)

🔧 Technical Implementation:
- Background service initialization in all managers
- Configurable workers, timeouts, and retry settings
- Graceful fallback when background service is disabled
- Comprehensive logging for monitoring and debugging
- Thread-safe operations with proper error handling

⚙️ Configuration Support Added:
- MiLB: background_service config section
- Soccer: background_service config section
- Leaderboard: background_service config section
- Odds Ticker: background_service config section
- Each manager can independently enable/disable background service

📈 Performance Benefits Achieved:
- Non-blocking data fetching across ALL sport managers
- Immediate response with cached/partial data
- Background threads handle heavy API calls
- Significantly improved responsiveness
- Better user experience during data loading

🚀 Production Ready:
- All major sport managers now support background threading
- Comprehensive configuration options
- Robust error handling and fallback mechanisms
- Ready for production deployment

Next: Phase 3 - Advanced features (priority queuing, analytics)

* Update wiki submodule with Background Service documentation

📚 Wiki Documentation Added:
- Complete Background Service Guide with architecture diagrams
- Configuration examples and best practices
- Performance benefits and troubleshooting guide
- Migration guide and advanced features

🔧 Navigation Updates:
- Added to sidebar under Technical section
- Updated home page with performance section
- Highlighted as NEW feature with  icon

The wiki now includes comprehensive documentation for the new
background threading system that improves performance across
all sport managers.

* Fix CacheManager constructor in test script

🐛 Bug Fix:
- Fixed CacheManager initialization in test_background_service.py
- CacheManager no longer takes config_manager parameter
- Updated constructor call to match current implementation

 Result:
- Test script now works with current CacheManager API
- Background service testing can proceed without errors

* Move test_background_service.py to test/ directory

📁 Organization Improvement:
- Moved test_background_service.py from root to test/ directory
- Updated import paths to work from new location
- Fixed sys.path to correctly reference src/ directory
- Updated imports to use relative paths

🔧 Technical Changes:
- Changed sys.path from 'src' to '../src' (go up from test/)
- Updated imports to remove 'src.' prefix
- Maintains all functionality while improving project structure

 Benefits:
- Better project organization
- Test files properly grouped in test/ directory
- Cleaner root directory structure
- Follows standard Python project layout

* Remove old test_background_service.py from root directory

📁 Cleanup:
- Removed test_background_service.py from root directory
- File has been moved to test/ directory for better organization
- Maintains clean project structure

* Fix NCAA FB team ranking display functionality

- Add missing _fetch_team_rankings() calls to all update methods (live, recent, upcoming)
- Add ranking display logic to live manager scorebug layout
- Remove unused old _fetch_rankings() method and top_25_rankings variable
- Rankings now properly display as #X format when show_ranking is enabled
- Fixes non-functional ranking feature despite existing UI and configuration options
2025-09-17 17:25:01 -04:00

6.1 KiB

Background Data Service for LEDMatrix

Overview

The Background Data Service is a new feature that implements background threading for season data fetching to prevent blocking the main display loop. This significantly improves responsiveness and user experience during data fetching operations.

Key Benefits

  • Non-blocking: Season data fetching no longer blocks the main display loop
  • Immediate Response: Returns cached or partial data immediately while fetching complete data in background
  • Configurable: Can be enabled/disabled per sport with customizable settings
  • Thread-safe: Uses proper synchronization for concurrent access
  • Retry Logic: Automatic retry with exponential backoff for failed requests
  • Progress Tracking: Comprehensive logging and statistics

Architecture

Core Components

  1. BackgroundDataService: Main service class managing background threads
  2. FetchRequest: Represents individual fetch operations
  3. FetchResult: Contains results of fetch operations
  4. Sport Managers: Updated to use background service

How It Works

  1. Cache Check: First checks for cached data and returns immediately if available
  2. Background Fetch: If no cache, starts background thread to fetch complete season data
  3. Partial Data: Returns immediate partial data (current/recent games) for quick display
  4. Completion: Background fetch completes and caches full dataset
  5. Future Requests: Subsequent requests use cached data for instant response

Configuration

NFL Configuration Example

{
    "nfl_scoreboard": {
        "enabled": true,
        "background_service": {
            "enabled": true,
            "max_workers": 3,
            "request_timeout": 30,
            "max_retries": 3,
            "priority": 2
        }
    }
}

Configuration Options

  • enabled: Enable/disable background service (default: true)
  • max_workers: Maximum number of background threads (default: 3)
  • request_timeout: HTTP request timeout in seconds (default: 30)
  • max_retries: Maximum retry attempts for failed requests (default: 3)
  • priority: Request priority (higher = more important, default: 2)

Implementation Status

Phase 1: Background Season Data Fetching COMPLETED

  • Created BackgroundDataService class
  • Implemented thread-safe data caching
  • Added retry logic with exponential backoff
  • Modified NFL manager to use background service
  • Added configuration support
  • Created test script

Phase 2: Rollout to Other Sports (Next Steps)

  • Apply to NCAAFB manager
  • Apply to NBA manager
  • Apply to NHL manager
  • Apply to MLB manager
  • Apply to other sport managers

Testing

Test Script

Run the test script to verify background service functionality:

python test_background_service.py

Test Scenarios

  1. Cache Hit: Verify immediate return of cached data
  2. Background Fetch: Verify non-blocking background data fetching
  3. Partial Data: Verify immediate return of partial data during background fetch
  4. Completion: Verify background fetch completion and caching
  5. Subsequent Requests: Verify cache usage for subsequent requests
  6. Service Disabled: Verify fallback to synchronous fetching

Expected Results

  • Initial fetch should return partial data immediately (< 1 second)
  • Background fetch should complete within 10-30 seconds
  • Subsequent fetches should use cache (< 0.1 seconds)
  • No blocking of main display loop

Performance Impact

Before Background Service

  • Season data fetch: 10-30 seconds (blocking)
  • Display loop: Frozen during fetch
  • User experience: Poor responsiveness

After Background Service

  • Initial response: < 1 second (partial data)
  • Background fetch: 10-30 seconds (non-blocking)
  • Display loop: Continues normally
  • User experience: Excellent responsiveness

Monitoring

Logs

The service provides comprehensive logging:

[NFL] Background service enabled with 3 workers
[NFL] Starting background fetch for 2024 season schedule...
[NFL] Using 15 immediate events while background fetch completes
[NFL] Background fetch completed for 2024: 256 events

Statistics

Access service statistics:

stats = background_service.get_statistics()
print(f"Total requests: {stats['total_requests']}")
print(f"Cache hits: {stats['cached_hits']}")
print(f"Average fetch time: {stats['average_fetch_time']:.2f}s")

Error Handling

Automatic Retry

  • Failed requests are automatically retried with exponential backoff
  • Maximum retry attempts are configurable
  • Failed requests are logged with error details

Fallback Behavior

  • If background service is disabled, falls back to synchronous fetching
  • If background fetch fails, returns partial data if available
  • Graceful degradation ensures system continues to function

Future Enhancements

Phase 2 Features

  • Apply to all sport managers
  • Priority-based request queuing
  • Dynamic worker scaling
  • Request batching for efficiency

Phase 3 Features

  • Real-time data streaming
  • WebSocket support for live updates
  • Advanced caching strategies
  • Performance analytics dashboard

Troubleshooting

Common Issues

  1. Background service not starting

    • Check configuration: background_service.enabled = true
    • Verify cache manager is properly initialized
    • Check logs for initialization errors
  2. Slow background fetches

    • Increase request_timeout in configuration
    • Check network connectivity
    • Monitor API rate limits
  3. Memory usage

    • Background service automatically cleans up old requests
    • Adjust max_workers if needed
    • Monitor cache size

Debug Mode

Enable debug logging for detailed information:

logging.getLogger('src.background_data_service').setLevel(logging.DEBUG)

Contributing

When adding background service support to new sport managers:

  1. Import the background service
  2. Initialize in __init__ method
  3. Update data fetching method to use background service
  4. Add configuration options
  5. Test thoroughly
  6. Update documentation

License

This feature is part of the LEDMatrix project and follows the same license terms.