Class: DiscordRDA::AnalyticsPlugin
- Defined in:
- lib/discord_rda/plugin/analytics_plugin.rb
Overview
Analytics plugin for tracking bot metrics. Provides beautiful analytics as inspired by Discordeno.
Constant Summary collapse
- CATEGORIES =
Metrics categories
{ gateway: [:events_received, :events_sent, :heartbeat_acks, :reconnects], rest: [:requests_made, :rate_limited, :errors, :avg_response_time], cache: [:hits, :misses, :evictions, :size], shards: [:guilds, :members, :channels, :messages_per_minute] }.freeze
Instance Attribute Summary collapse
-
#logger ⇒ Logger
readonly
Logger instance.
-
#metrics ⇒ Hash
readonly
Metrics storage.
-
#retention ⇒ Integer
readonly
Metrics retention period (seconds).
Attributes inherited from Plugin
#dependencies, #description, #name, #version
Instance Method Summary collapse
-
#check_cache_health ⇒ Hash
Check cache health.
-
#check_gateway_health ⇒ Hash
Check gateway health.
-
#check_rate_limiter_health ⇒ Hash
Check rate limiter health.
-
#check_rest_health ⇒ Hash
Check REST API health.
-
#cpu_usage ⇒ Hash
Get CPU usage (simplified).
-
#dashboard_data ⇒ Hash
Get real-time dashboard data.
-
#get_average(category, metric, window: 60) ⇒ Float
Get average metric value.
-
#get_metric(category, metric, window: 60) ⇒ Numeric
Get metric value (sum in time window).
-
#health_report ⇒ String
Generate health check report.
-
#initialize(retention: 3600, logger: nil) ⇒ AnalyticsPlugin
constructor
Initialize analytics plugin.
-
#memory_usage ⇒ Hash
Get memory usage.
-
#pretty_report ⇒ String
Generate pretty formatted report.
-
#ready(bot) ⇒ void
Called when bot is ready.
-
#record(category, metric, value = 1) ⇒ void
Record a metric.
-
#run_health_checks ⇒ Hash
Run comprehensive health checks.
-
#setup(bot) ⇒ void
Setup analytics on bot.
-
#summary ⇒ Hash
Get all metrics summary.
-
#system_metrics ⇒ Hash
Get system metrics.
-
#to_json ⇒ String
Export metrics to JSON.
Methods inherited from Plugin
after_setup, after_setup_hook, before_setup, before_setup_hook, command, commands, #dependencies_met?, #disable, #enable, #enabled?, handlers, #metadata, middleware, middlewares, on, #register_commands, #register_handlers, #register_middleware, #teardown
Constructor Details
#initialize(retention: 3600, logger: nil) ⇒ AnalyticsPlugin
Initialize analytics plugin
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 28 def initialize(retention: 3600, logger: nil) super( name: 'Analytics', version: '1.0.0', description: 'Track bot performance metrics' ) @metrics = {} @logger = logger @retention = retention @start_time = Time.now.utc @mutex = Mutex.new initialize_metrics end |
Instance Attribute Details
#logger ⇒ Logger (readonly)
Returns Logger instance.
12 13 14 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 12 def logger @logger end |
#metrics ⇒ Hash (readonly)
Returns Metrics storage.
9 10 11 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 9 def metrics @metrics end |
#retention ⇒ Integer (readonly)
Returns Metrics retention period (seconds).
15 16 17 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 15 def retention @retention end |
Instance Method Details
#check_cache_health ⇒ Hash
Check cache health
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 263 def check_cache_health return { status: :unknown, reason: 'No cache configured' } unless @bot&.cache stats = @bot.cache.stats hit_rate = calculate_cache_hit_rate(window: 300) status = if hit_rate < 10 && stats[:size].to_i > 100 :warning else :healthy end { status: status, hit_rate: hit_rate, size: stats[:size], memory_usage: stats[:memory_usage] } end |
#check_gateway_health ⇒ Hash
Check gateway health
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 214 def check_gateway_health reconnects_5min = get_metric(:gateway, :reconnects, window: 300) events_per_sec = get_metric(:gateway, :events_received, window: 1) status = if reconnects_5min > 10 :critical elsif reconnects_5min > 5 :warning elsif events_per_sec == 0 && uptime_seconds > 60 :warning else :healthy end { status: status, reconnects_5min: reconnects_5min, events_per_sec: events_per_sec, connected: @bot&.shard_manager&.shards&.all?(&:connected?) || false } end |
#check_rate_limiter_health ⇒ Hash
Check rate limiter health
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 285 def check_rate_limiter_health return { status: :unknown } unless @bot&.rest.respond_to?(:rate_limiter) rl_status = @bot.rest.rate_limiter.status status = if rl_status[:global_limited] :warning else :healthy end { status: status, global_limited: rl_status[:global_limited], routes_tracked: rl_status[:routes_tracked] } end |
#check_rest_health ⇒ Hash
Check REST API health
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 238 def check_rest_health rate_limited_1min = get_metric(:rest, :rate_limited, window: 60) errors_1min = get_metric(:rest, :errors, window: 60) avg_response = get_average(:rest, :avg_response_time, window: 60) status = if errors_1min > 10 :critical elsif rate_limited_1min > 5 || errors_1min > 3 :warning elsif avg_response > 5000 :warning else :healthy end { status: status, rate_limited_1min: rate_limited_1min, errors_1min: errors_1min, avg_response_ms: avg_response.round(2) } end |
#cpu_usage ⇒ Hash
Get CPU usage (simplified)
328 329 330 331 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 328 def cpu_usage # This is a simplified implementation { available: false } end |
#dashboard_data ⇒ Hash
Get real-time dashboard data
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 169 def dashboard_data { realtime: { events_per_second: get_metric(:gateway, :events_received, window: 1), requests_per_second: get_metric(:rest, :requests_made, window: 1), cache_hit_rate: calculate_cache_hit_rate(window: 60) }, health: { status: health_status, issues: detect_issues, checks: run_health_checks }, system: system_metrics } end |
#get_average(category, metric, window: 60) ⇒ Float
Get average metric value
102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 102 def get_average(category, metric, window: 60) key = "#{category}:#{metric}" cutoff = Time.now.utc.to_i - window @mutex.synchronize do data = @metrics[key] || [] recent = data.select { |d| d[:timestamp] >= cutoff } return 0.0 if recent.empty? recent.sum { |d| d[:value] }.to_f / recent.length end end |
#get_metric(category, metric, window: 60) ⇒ Numeric
Get metric value (sum in time window)
87 88 89 90 91 92 93 94 95 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 87 def get_metric(category, metric, window: 60) key = "#{category}:#{metric}" cutoff = Time.now.utc.to_i - window @mutex.synchronize do data = @metrics[key] || [] data.select { |d| d[:timestamp] >= cutoff }.sum { |d| d[:value] } end end |
#health_report ⇒ String
Generate health check report
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 335 def health_report checks = run_health_checks lines = [ '🏥 DiscordRDA Health Report', '=' * 40, "Overall: #{emoji_for_status(checks[:overall][:status])} #{checks[:overall][:status].upcase}", "Timestamp: #{checks[:overall][:timestamp]}", '', '📡 Gateway:', " Status: #{emoji_for_status(checks[:gateway][:status])} #{checks[:gateway][:status]}", " Connected: #{checks[:gateway][:connected]}", " Events/sec: #{checks[:gateway][:events_per_sec]}", '', '🌐 REST API:', " Status: #{emoji_for_status(checks[:rest][:status])} #{checks[:rest][:status]}", " Rate limited (1m): #{checks[:rest][:rate_limited_1min]}", " Errors (1m): #{checks[:rest][:errors_1min]}", " Avg response: #{checks[:rest][:avg_response_ms]}ms", '', '💾 Cache:', " Status: #{emoji_for_status(checks[:cache][:status])} #{checks[:cache][:status]}", " Hit rate: #{checks[:cache][:hit_rate]}%" ] lines.join("\n") end |
#memory_usage ⇒ Hash
Get memory usage
316 317 318 319 320 321 322 323 324 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 316 def memory_usage # Try to get memory info from GC { gc_stat: GC.stat, total_objects: ObjectSpace.count_objects[:TOTAL] } rescue { error: 'Unable to retrieve' } end |
#pretty_report ⇒ String
Generate pretty formatted report
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 131 def pretty_report data = summary lines = [ "📊 DiscordRDA Analytics Report", "=" * 40, "⏱️ Uptime: #{format_duration(data[:uptime])}", "", "📡 Gateway:", " Events/min: #{data[:gateway][:events_per_minute]}", " Reconnects: #{data[:gateway][:reconnects]}", "", "🌐 REST API:", " Requests/min: #{data[:rest][:requests_per_minute]}", " Avg Response: #{data[:rest][:avg_response_time]}ms", " Rate Limited: #{data[:rest][:rate_limited]}", "", "💾 Cache:", " Hit Rate: #{data[:cache][:hit_rate]}%", " Size: #{data[:cache][:size]}", "", "🗂️ Shards:", " Guilds: #{data[:shards][:total_guilds]}", " Members: #{data[:shards][:total_members]}", " Msg/min: #{data[:shards][:messages_per_minute]}" ] lines.join("\n") end |
#ready(bot) ⇒ void
This method returns an undefined value.
Called when bot is ready
57 58 59 60 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 57 def ready(bot) @logger&.info('Analytics plugin ready') start_metrics_collection end |
#record(category, metric, value = 1) ⇒ void
This method returns an undefined value.
Record a metric
67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 67 def record(category, metric, value = 1) return unless valid_metric?(category, metric) @mutex.synchronize do key = "#{category}:#{metric}" = Time.now.utc.to_i @metrics[key] ||= [] @metrics[key] << { timestamp: , value: value } # Clean old data clean_old_data(key) end end |
#run_health_checks ⇒ Hash
Run comprehensive health checks
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 187 def run_health_checks checks = {} # Gateway health checks[:gateway] = check_gateway_health # REST API health checks[:rest] = check_rest_health # Cache health checks[:cache] = check_cache_health # Rate limiter health checks[:rate_limiter] = check_rate_limiter_health # Overall status all_healthy = checks.values.all? { |c| c[:status] == :healthy } checks[:overall] = { status: all_healthy ? :healthy : :degraded, timestamp: Time.now.utc.iso8601 } checks end |
#setup(bot) ⇒ void
This method returns an undefined value.
Setup analytics on bot
47 48 49 50 51 52 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 47 def setup(bot) @bot = bot setup_event_tracking(bot) setup_rest_tracking(bot) setup_cache_tracking(bot) end |
#summary ⇒ Hash
Get all metrics summary
117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 117 def summary @mutex.synchronize do { uptime: uptime_seconds, gateway: gateway_metrics, rest: rest_metrics, cache: cache_metrics, shards: shard_metrics } end end |
#system_metrics ⇒ Hash
Get system metrics
305 306 307 308 309 310 311 312 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 305 def system_metrics { uptime: uptime_seconds, memory: memory_usage, cpu: cpu_usage, timestamp: Time.now.utc.iso8601 } end |
#to_json ⇒ String
Export metrics to JSON
163 164 165 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 163 def to_json Oj.dump(summary, mode: :compat) end |