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 process CPU usage.
-
#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).
- #grafana_dashboard(title: 'DiscordRDA Overview') ⇒ Object
-
#health_report ⇒ String
Generate health check report.
-
#initialize(retention: 3600, logger: nil) ⇒ AnalyticsPlugin
constructor
Initialize analytics plugin.
-
#memory_usage ⇒ Hash
Get memory usage.
- #metric_panel(id:, title:, expr:) ⇒ Object
-
#pretty_report ⇒ String
Generate pretty formatted report.
- #prometheus_export ⇒ Object
-
#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
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 302 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
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 253 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
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 324 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
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 277 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 process CPU usage
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 378 def cpu_usage process_times = Process.times elapsed = uptime_seconds total_cpu_seconds = process_times.utime + process_times.stime cpu_percent = elapsed.positive? ? ((total_cpu_seconds / elapsed) * 100.0).round(2) : 0.0 { available: true, user_seconds: process_times.utime.round(4), system_seconds: process_times.stime.round(4), total_seconds: total_cpu_seconds.round(4), utilization_percent: cpu_percent } rescue StandardError { 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 |
#grafana_dashboard(title: 'DiscordRDA Overview') ⇒ Object
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 207 def grafana_dashboard(title: 'DiscordRDA Overview') dashboard = { title: title, schemaVersion: 39, version: 1, editable: true, panels: [ metric_panel(id: 1, title: 'Gateway Events / Min', expr: 'discord_rda_gateway_events_per_minute'), metric_panel(id: 2, title: 'REST Requests / Min', expr: 'discord_rda_rest_requests_per_minute'), metric_panel(id: 3, title: 'Cache Hit Rate', expr: 'discord_rda_cache_hit_rate'), metric_panel(id: 4, title: 'Guilds', expr: 'discord_rda_shards_total_guilds') ] } Oj.dump(dashboard, mode: :compat) end |
#health_report ⇒ String
Generate health check report
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 397 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
366 367 368 369 370 371 372 373 374 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 366 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 |
#metric_panel(id:, title:, expr:) ⇒ Object
353 354 355 356 357 358 359 360 361 362 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 353 def metric_panel(id:, title:, expr:) { id: id, type: 'stat', title: title, datasource: { type: 'prometheus', uid: '${DS_PROMETHEUS}' }, targets: [{ expr: expr, refId: "A#{id}" }], gridPos: { h: 8, w: 12, x: ((id - 1) % 2) * 12, y: ((id - 1) / 2) * 8 } } 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 |
#prometheus_export ⇒ Object
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 185 def prometheus_export data = summary [ '# HELP discord_rda_uptime_seconds Process uptime in seconds', '# TYPE discord_rda_uptime_seconds gauge', "discord_rda_uptime_seconds #{data[:uptime]}", '# HELP discord_rda_gateway_events_per_minute Gateway events per minute', '# TYPE discord_rda_gateway_events_per_minute gauge', "discord_rda_gateway_events_per_minute #{data[:gateway][:events_per_minute]}", '# HELP discord_rda_rest_requests_per_minute REST requests per minute', '# TYPE discord_rda_rest_requests_per_minute gauge', "discord_rda_rest_requests_per_minute #{data[:rest][:requests_per_minute]}", '# HELP discord_rda_cache_hit_rate Cache hit rate percentage', '# TYPE discord_rda_cache_hit_rate gauge', "discord_rda_cache_hit_rate #{data[:cache][:hit_rate]}", '# HELP discord_rda_shards_total_guilds Guilds across shards', '# TYPE discord_rda_shards_total_guilds gauge', "discord_rda_shards_total_guilds #{data[:shards][:total_guilds]}" ].join("\n") + "\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
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 226 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
344 345 346 347 348 349 350 351 |
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 344 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 |