high-command-api/
├── src/ # Core application code
│ ├── __init__.py # Package initialization
│ ├── app.py # FastAPI application
│ ├── scraper.py # Hell Divers 2 API scraper
│ ├── database.py # SQLite database layer
│ ├── collector.py # Background task scheduler
│ └── config.py # Configuration management
├── tests/ # Test suite
│ ├── __init__.py
│ └── demo.py # Comprehensive integration tests
├── docs/ # Documentation
│ ├── ARCHITECTURE.md # This file
│ ├── DEPLOYMENT.md # Production deployment guide
│ ├── API.md # API reference
│ └── QUICKREF.md # Quick reference guide
├── main.py # Application entry point
├── Makefile # Project automation (40+ targets)
├── Dockerfile # Production container image
├── docker-compose.yml # Multi-container setup
├── requirements.txt # Python dependencies
├── pyproject.toml # Project metadata
├── .env.example # Environment template
├── .gitignore # Git patterns
└── README.md # Project overview
-
Purpose: Main FastAPI application with all endpoint handlers
-
Key Components:
lifespan(): Async context manager for startup/shutdown- 30+ endpoint handlers organized by resource type
- CORS middleware for cross-origin requests
- Error handling with HTTPExceptions
-
Endpoints: War status, planets, statistics, campaigns, factions, biomes
-
Documentation: Auto-generated at
/docs(Swagger) and/redoc(ReDoc)
-
Purpose: Fetch external game data from Hell Divers 2 API
-
Class:
HellDivers2Scraper -
Methods:
get_war_status(): Current war statusget_planets(): All planets informationget_statistics(): Global game statisticsget_campaigns(): Active campaignsget_factions(): Faction informationget_biomes(): Biome data
-
Error Handling: Graceful error handling with logging
-
Purpose: Persistent data storage with optimized queries
-
Class:
Database -
Tables:
war_status: War data with timestampsstatistics: Player stats and metricsplanet_status: Individual planet datacampaigns: Campaign information
-
Indexes: Optimized for timestamp and planet_index queries
-
Methods: Save/retrieve data, history queries
-
Purpose: Automatic periodic data collection
-
Class:
DataCollector -
Features:
- APScheduler integration for background tasks
- Configurable collection interval (default: 5 minutes)
- Comprehensive error handling
- Collects all data types automatically
-
Methods:
start(),stop(),collect_all_data(),collect_planet_data()
-
Purpose: Environment-based settings and configuration
-
Classes:
Config: Base configurationDevelopmentConfig: Development overridesProductionConfig: Production settingsTestingConfig: Testing environment
-
Settings: Database URL, API timeouts, collection intervals, log levels
┌──────────────────────────────────────────────────────────────┐
│ Client Requests │
└─────────────────────────┬──────────────────────────────────────┘
│
▼
┌─────────────┐
│ FastAPI │
│ (app.py) │
└─────────────┘
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
Database Scraper Collector
(database) (scraper) (collector)
│ │ │
│ │ │
▼ ▼ ▼
Cache/SQLite External API Background
(with fallback) (Hell Divers 2) Tasks
│
├─ Success ──> set_upstream_status(True)
└─ Failure ──> set_upstream_status(False)
For endpoints with cache fallback (/api/campaigns, /api/planets, etc.):
Client Request
│
▼
Try Live API (scraper.get_*)
│
├─ Success ──> Return 200 with fresh data
│
└─ Failure (None returned)
│
▼
Try Cache (db.get_latest_*_snapshot)
│
├─ Cache Hit ──> Return 200 with cached data
│
└─ Cache Miss ──> Return 503 Service Unavailable
This pattern ensures:
- Maximum uptime during upstream API outages
- Transparent fallback to consumers (200 status for both live and cached)
- Clear failure signal (503) when truly no data is available
- FastAPI app initializes
- Lifespan context manager's startup code runs
- DataCollector starts (schedules background tasks)
- Application ready to receive requests
- Collector runs
collect_all_data() - Scraper fetches data from Hell Divers 2 API
- Database stores the retrieved data
- Collector updates system_status:
set_upstream_status(True)on successset_upstream_status(False)on failure
- Logging records the operation
- Client sends HTTP request
- FastAPI routes to appropriate handler
- Handler attempts to fetch live data (if applicable)
- On failure, handler may fall back to cached data
- Response returned to client (200 for success/cache, 503 for total failure, 404 for not found)
- Shutdown signal received
- DataCollector stops scheduler
- Scraper session closed
- Application exits gracefully
CREATE TABLE war_status (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
data TEXT NOT NULL
);
CREATE INDEX idx_war_timestamp ON war_status(timestamp);CREATE TABLE statistics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
total_players INTEGER,
total_kills INTEGER,
missions_won INTEGER,
data TEXT NOT NULL
);
CREATE INDEX idx_stats_timestamp ON statistics(timestamp);CREATE TABLE planet_status (
id INTEGER PRIMARY KEY AUTOINCREMENT,
planet_index INTEGER NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
planet_name TEXT,
owner TEXT,
status TEXT,
data TEXT NOT NULL
);
CREATE INDEX idx_planet_index ON planet_status(planet_index);CREATE TABLE campaigns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
campaign_id INTEGER UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
planet_index INTEGER,
status TEXT,
data TEXT NOT NULL
);CREATE TABLE assignments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
assignment_id INTEGER UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
data TEXT NOT NULL
);
CREATE INDEX idx_assignment_timestamp ON assignments(timestamp);CREATE TABLE dispatches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dispatch_id INTEGER UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
data TEXT NOT NULL
);
CREATE INDEX idx_dispatch_timestamp ON dispatches(timestamp);CREATE TABLE planet_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id INTEGER UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
data TEXT NOT NULL
);
CREATE INDEX idx_event_timestamp ON planet_events(timestamp);New in cache-fallback feature: Tracks internal system metadata and upstream API health.
CREATE TABLE system_status (
id INTEGER PRIMARY KEY AUTOINCREMENT,
status_key TEXT UNIQUE,
status_value BOOLEAN,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_system_status_key ON system_status(status_key);Current status keys:
upstream_api_available: Boolean tracking if Hell Divers 2 API is reachable- Updated to
TRUEafter successful collection cycle - Updated to
FALSEafter failed collection cycle - Used for monitoring and alerting on upstream availability
- Updated to
All FastAPI handlers use async def for non-blocking I/O
Lifespan pattern manages application lifecycle
APScheduler for background task management
Database class abstracts data access
Environment-based configuration classes
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txtpython main.pypython -m tests.demopython main.py --reloadAll functions include type hints for better IDE support and documentation
Comprehensive error handling with logging throughout the codebase
- Docstrings for all classes and methods
- Inline comments for complex logic
- Comprehensive README and deployment guides
- Database Indexing: Timestamps and planet_index are indexed for fast queries
- Async Operations: Non-blocking I/O for better concurrency
- Session Management: Reused HTTP session for connection pooling
- Background Collection: Off-loads heavy operations from request handlers
- JSON Serialization: Efficient storage and retrieval of complex data
- CORS Middleware: Configurable cross-origin requests
- Input Validation: FastAPI's built-in validation
- Error Messages: Generic error messages in production
- Logging: Secure logging of operations and errors
- Environment Variables: Sensitive config via .env files