0019_api_analytics.up.sql 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. -- Migration: 0018_api_analytics
  2. -- Description: Create tables for Web API usage analytics and tracking
  3. -- Date: 2024-12-28
  4. -- Create API usage logs table for detailed request tracking
  5. CREATE TABLE IF NOT EXISTS api_usage_logs (
  6. id INTEGER PRIMARY KEY AUTOINCREMENT,
  7. dev_id VARCHAR(255) NOT NULL,
  8. endpoint VARCHAR(255) NOT NULL,
  9. method VARCHAR(10) NOT NULL,
  10. timestamp INTEGER NOT NULL,
  11. response_time_ms INTEGER,
  12. status_code INTEGER,
  13. ip_address VARCHAR(45),
  14. user_agent TEXT,
  15. screen_name VARCHAR(16), -- User making the request (if authenticated)
  16. error_message TEXT, -- Store error details if request failed
  17. request_size INTEGER, -- Size of request in bytes
  18. response_size INTEGER -- Size of response in bytes
  19. );
  20. -- Create indexes for efficient querying
  21. CREATE INDEX idx_usage_dev_id ON api_usage_logs(dev_id);
  22. CREATE INDEX idx_usage_timestamp ON api_usage_logs(timestamp);
  23. CREATE INDEX idx_usage_endpoint ON api_usage_logs(endpoint);
  24. CREATE INDEX idx_usage_status ON api_usage_logs(status_code);
  25. CREATE INDEX idx_usage_screen_name ON api_usage_logs(screen_name);
  26. -- Create aggregated statistics table for performance
  27. CREATE TABLE IF NOT EXISTS api_usage_stats (
  28. id INTEGER PRIMARY KEY AUTOINCREMENT,
  29. dev_id VARCHAR(255) NOT NULL,
  30. endpoint VARCHAR(255) NOT NULL,
  31. period_type VARCHAR(10) NOT NULL, -- 'hour', 'day', 'month'
  32. period_start INTEGER NOT NULL,
  33. request_count INTEGER DEFAULT 0,
  34. error_count INTEGER DEFAULT 0,
  35. total_response_time_ms INTEGER DEFAULT 0,
  36. avg_response_time_ms INTEGER DEFAULT 0,
  37. total_request_bytes INTEGER DEFAULT 0,
  38. total_response_bytes INTEGER DEFAULT 0,
  39. unique_users INTEGER DEFAULT 0,
  40. UNIQUE(dev_id, endpoint, period_type, period_start)
  41. );
  42. -- Create indexes for aggregated stats
  43. CREATE INDEX idx_stats_dev_id ON api_usage_stats(dev_id);
  44. CREATE INDEX idx_stats_period ON api_usage_stats(period_type, period_start);
  45. CREATE INDEX idx_stats_endpoint ON api_usage_stats(endpoint);
  46. -- Create table for tracking API key quotas and limits
  47. CREATE TABLE IF NOT EXISTS api_quotas (
  48. dev_id VARCHAR(255) PRIMARY KEY,
  49. daily_limit INTEGER DEFAULT 10000,
  50. monthly_limit INTEGER DEFAULT 300000,
  51. daily_used INTEGER DEFAULT 0,
  52. monthly_used INTEGER DEFAULT 0,
  53. last_reset_daily INTEGER NOT NULL,
  54. last_reset_monthly INTEGER NOT NULL,
  55. overage_allowed BOOLEAN DEFAULT FALSE
  56. );