MockForge Analytics
Comprehensive traffic analytics and metrics dashboard for MockForge.
Features
- Time-Series Metrics - Store and query metrics at minute/hour/day granularity
- Endpoint Analytics - Track performance, latency, and error rates per endpoint
- Error Analysis - Detailed error tracking and categorization
- Client Analytics - Analyze traffic by client IP and User-Agent
- Traffic Patterns - Heatmap visualization of requests by hour/day
- Data Export - Export to CSV or JSON for external analysis
- Automatic Retention - Configurable data retention and cleanup policies
- Prometheus Integration - Aggregates metrics from Prometheus
Quick Start
Add to your Cargo.toml:
[]
= "0.1"
Basic Usage
use ;
use PathBuf;
async
With Aggregation Service
use ;
use Arc;
// Start the metrics aggregation service
let aggregator = new;
aggregator.start.await;
// Start the retention/cleanup service
let retention = new;
retention.start.await;
Configuration
Default Configuration
let config = default;
// Aggregation interval: 60 seconds
// Retention: 7d (minute), 30d (hour), 365d (day)
// Cleanup interval: 24 hours
Custom Configuration
use ;
let config = AnalyticsConfig ;
API Examples
Get Overview Metrics
// Last hour
let overview = db.get_overview_metrics.await?;
// Last 24 hours
let overview = db.get_overview_metrics.await?;
println!;
println!;
Get Top Endpoints
let top_endpoints = db.get_top_endpoints.await?;
for ep in top_endpoints
Get Time Series Data
use ;
use Utc;
let end_time = now.timestamp;
let start_time = end_time - 3600; // Last hour
let filter = AnalyticsFilter ;
let time_series = db.get_request_time_series.await?;
for series in time_series
Get Latency Trends
let filter = AnalyticsFilter ;
let trends = db.get_latency_trends.await?;
for trend in trends
Get Error Summary
let errors = db.get_error_summary.await?;
for err in errors
Data Export
Export to CSV
use File;
let filter = AnalyticsFilter ;
// Export metrics
let mut file = create?;
db.export_to_csv.await?;
// Export endpoints
let mut file = create?;
db.export_endpoints_to_csv.await?;
// Export errors
let mut file = create?;
db.export_errors_to_csv.await?;
Export to JSON
let json = db.export_to_json.await?;
write?;
Database Schema
The analytics database consists of 8 tables:
metrics_aggregates_minute- Per-minute metrics (7-day retention)metrics_aggregates_hour- Hourly rollups (30-day retention)metrics_aggregates_day- Daily rollups (365-day retention)endpoint_stats- Cumulative endpoint statisticserror_events- Individual error occurrences (7-day retention)client_analytics- Client-level analytics (30-day retention)traffic_patterns- Heatmap data (90-day retention)analytics_snapshots- System snapshots (90-day retention)
Total Indexes: 40 optimized indexes for fast queries
See database-schema.md for detailed schema documentation.
Architecture
┌─────────────────────┐
│ Prometheus │
│ (Metrics Source) │
└──────────┬──────────┘
│
├─ HTTP API (query metrics)
▼
┌─────────────────────┐
│ MetricsAggregator │ ← Runs every 1 minute
│ (Background Task) │
└──────────┬──────────┘
│
├─ Parse & aggregate
▼
┌─────────────────────┐
│ Analytics Database │
│ (SQLite) │
│ - Minute aggregates│
│ - Hour rollups │
│ - Day rollups │
│ - Endpoint stats │
│ - Error events │
│ - Traffic patterns │
└──────────┬──────────┘
│
├─ Query API
▼
┌─────────────────────┐
│ Dashboard / API │
│ - Overview metrics │
│ - Time series │
│ - Error analysis │
│ - Export │
└─────────────────────┘
┌─────────────────────┐
│ RetentionService │ ← Runs daily
│ (Background Task) │
└──────────┬──────────┘
│
├─ Cleanup old data
└─ Vacuum database
Performance
Storage Estimates
High Traffic (1000 req/sec):
- Minute-level (7 days): ~500 MB
- Hour-level (30 days): ~36 MB
- Day-level (365 days): ~18 MB
- Error events (7 days, 1% error rate): ~1.8 GB
- Total: ~2.4 GB
Typical Usage (100 req/sec):
- Total: ~240 MB
Optimization Features
- Path Normalization - Prevents cardinality explosion
- Pre-aggregation - Reduces query load
- Strategic Indexes - 40 indexes for common queries
- Batch Operations - Minimizes database round-trips
- Automatic Cleanup - Prevents unbounded growth
Testing
Run the test suite:
All tests:
- ✅ Database creation and migrations
- ✅ Metrics insertion and aggregation
- ✅ Endpoint statistics
- ✅ CSV export
- ✅ Retention service
Integration
With MockForge
The analytics system integrates with MockForge's observability infrastructure:
- Prometheus Metrics - Aggregates from Prometheus registry
- Request Logger - Complements in-memory logger with persistence
- Recorder - Links via
request_idandtrace_id - OpenTelemetry - Stores
trace_idandspan_idfor correlation
With External Tools
- Grafana - Query via REST API for dashboard creation
- Prometheus - Continue using existing Prometheus metrics
- Custom Analytics - Export to CSV/JSON for external processing
Roadmap
Completed:
- ✅ Core analytics database and schema
- ✅ Metrics aggregation service
- ✅ Query API
- ✅ Data export (CSV, JSON)
- ✅ Retention and cleanup
- ✅ Unit tests
Pending:
- ⏳ REST API endpoints for dashboard
- ⏳ WebSocket streaming for real-time updates
- ⏳ Dashboard UI components
- ⏳ Grafana dashboard templates
- ⏳ Integration tests
- ⏳ Benchmarks
Documentation
- Database Schema - Comprehensive schema documentation
- Implementation Summary - Architecture and design decisions
- API Documentation - Full API reference (coming soon)
Contributing
Contributions are welcome! Please:
- Write tests for new features
- Update documentation
- Follow existing code style
- Add changelog entries
License
Same as MockForge project - see root LICENSE file.
Support
For questions or issues:
- File an issue on GitHub
- Check existing documentation
- Review test cases for usage examples