Class: DiscordRDA::AnalyticsPlugin

Inherits:
Plugin
  • Object
show all
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

Attributes inherited from Plugin

#dependencies, #description, #name, #version

Instance Method Summary collapse

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

Parameters:

  • retention (Integer) (defaults to: 3600)

    Metrics retention in seconds (default: 1 hour)

  • logger (Logger) (defaults to: nil)

    Logger instance



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

#loggerLogger (readonly)

Returns Logger instance.

Returns:

  • (Logger)

    Logger instance



12
13
14
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 12

def logger
  @logger
end

#metricsHash (readonly)

Returns Metrics storage.

Returns:

  • (Hash)

    Metrics storage



9
10
11
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 9

def metrics
  @metrics
end

#retentionInteger (readonly)

Returns Metrics retention period (seconds).

Returns:

  • (Integer)

    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_healthHash

Check cache health

Returns:

  • (Hash)

    Cache health status



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_healthHash

Check gateway health

Returns:

  • (Hash)

    Gateway health status



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_healthHash

Check rate limiter health

Returns:

  • (Hash)

    Rate limiter health status



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_healthHash

Check REST API health

Returns:

  • (Hash)

    REST health status



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_usageHash

Get CPU usage (simplified)

Returns:

  • (Hash)

    CPU usage info



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_dataHash

Get real-time dashboard data

Returns:

  • (Hash)

    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

Parameters:

  • category (Symbol)

    Metric category

  • metric (Symbol)

    Metric name

  • window (Integer) (defaults to: 60)

    Time window in seconds

Returns:

  • (Float)

    Average 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)

Parameters:

  • category (Symbol)

    Metric category

  • metric (Symbol)

    Metric name

  • window (Integer) (defaults to: 60)

    Time window in seconds

Returns:

  • (Numeric)

    Sum of metric values



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_reportString

Generate health check report

Returns:

  • (String)

    Formatted health 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_usageHash

Get memory usage

Returns:

  • (Hash)

    Memory usage info



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_reportString

Generate pretty formatted report

Returns:

  • (String)

    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

Parameters:

  • bot (Bot)

    Bot instance



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

Parameters:

  • category (Symbol)

    Metric category

  • metric (Symbol)

    Metric name

  • value (Numeric) (defaults to: 1)

    Metric value



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}"
    timestamp = Time.now.utc.to_i

    @metrics[key] ||= []
    @metrics[key] << { timestamp: timestamp, value: value }

    # Clean old data
    clean_old_data(key)
  end
end

#run_health_checksHash

Run comprehensive health checks

Returns:

  • (Hash)

    Health check results



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

Parameters:

  • bot (Bot)

    Bot instance



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

#summaryHash

Get all metrics summary

Returns:

  • (Hash)

    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_metricsHash

Get system metrics

Returns:

  • (Hash)

    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_jsonString

Export metrics to JSON

Returns:

  • (String)

    JSON string



163
164
165
# File 'lib/discord_rda/plugin/analytics_plugin.rb', line 163

def to_json
  Oj.dump(summary, mode: :compat)
end