Class: RailsErrorDashboard::ErrorLog

Inherits:
ErrorLogsRecord show all
Defined in:
app/models/rails_error_dashboard/error_log.rb

Constant Summary collapse

CRITICAL_ERROR_TYPES =
%w[
  SecurityError
  NoMemoryError
  SystemStackError
  SignalException
  ActiveRecord::StatementInvalid
  LoadError
  SyntaxError
  ActiveRecord::ConnectionNotEstablished
  Redis::ConnectionError
  OpenSSL::SSL::SSLError
].freeze
HIGH_SEVERITY_ERROR_TYPES =
%w[
  ActiveRecord::RecordNotFound
  ArgumentError
  TypeError
  NoMethodError
  NameError
  ZeroDivisionError
  FloatDomainError
  IndexError
  KeyError
  RangeError
].freeze
MEDIUM_SEVERITY_ERROR_TYPES =
%w[
  ActiveRecord::RecordInvalid
  Timeout::Error
  Net::ReadTimeout
  Net::OpenTimeout
  ActiveRecord::RecordNotUnique
  JSON::ParserError
  CSV::MalformedCSVError
  Errno::ECONNREFUSED
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.belongs_to(*args, **options) ⇒ Object

Override user association to use configured user model



540
541
542
543
544
545
546
# File 'app/models/rails_error_dashboard/error_log.rb', line 540

def self.belongs_to(*args, **options)
  if args.first == :user
    user_model = RailsErrorDashboard.configuration.user_model
    options[:class_name] = user_model if user_model.present?
  end
  super
end

.find_or_increment_by_hash(error_hash, attributes = {}) ⇒ Object

Find existing error by hash or create new one This is CRITICAL for accurate occurrence tracking Uses pessimistic locking to prevent race conditions in multi-app scenarios



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'app/models/rails_error_dashboard/error_log.rb', line 179

def self.find_or_increment_by_hash(error_hash, attributes = {})
  # Look for unresolved error with same hash in last 24 hours
  # (resolved errors are considered "fixed" so new occurrence = new issue)
  # CRITICAL: Scope by application_id to prevent cross-app locks
  existing = unresolved
              .where(error_hash: error_hash)
              .where(application_id: attributes[:application_id])
              .where("occurred_at >= ?", 24.hours.ago)
              .lock  # Row-level pessimistic lock
              .order(last_seen_at: :desc)
              .first

  if existing
    # Increment existing error
    existing.update!(
      occurrence_count: existing.occurrence_count + 1,
      last_seen_at: Time.current,
      # Update context from latest occurrence
      user_id: attributes[:user_id] || existing.user_id,
      request_url: attributes[:request_url] || existing.request_url,
      request_params: attributes[:request_params] || existing.request_params,
      user_agent: attributes[:user_agent] || existing.user_agent,
      ip_address: attributes[:ip_address] || existing.ip_address
    )
    existing
  else
    # Create new error record with retry logic for race conditions
    begin
      create!(attributes.reverse_merge(resolved: false))
    rescue ActiveRecord::RecordNotUnique
      # Race condition: another process created the record
      # Retry with lock to find and increment
      retry_existing = unresolved
                        .where(error_hash: error_hash)
                        .where(application_id: attributes[:application_id])
                        .where("occurred_at >= ?", 24.hours.ago)
                        .lock
                        .first

      if retry_existing
        retry_existing.update!(
          occurrence_count: retry_existing.occurrence_count + 1,
          last_seen_at: Time.current
        )
        retry_existing
      else
        raise  # Re-raise if still nil (unexpected scenario)
      end
    end
  end
end

.log_error(exception, context = {}) ⇒ Object

Log an error with context (delegates to Command)



232
233
234
# File 'app/models/rails_error_dashboard/error_log.rb', line 232

def self.log_error(exception, context = {})
  Commands::LogError.call(exception, context)
end

.statistics(days = 7) ⇒ Object

Get error statistics



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'app/models/rails_error_dashboard/error_log.rb', line 375

def self.statistics(days = 7)
  start_date = days.days.ago

  {
    total: where("occurred_at >= ?", start_date).count,
    unresolved: where("occurred_at >= ?", start_date).unresolved.count,
    by_type: where("occurred_at >= ?", start_date)
      .group(:error_type)
      .count
      .sort_by { |_, count| -count }
      .to_h,
    by_day: where("occurred_at >= ?", start_date)
      .group("DATE(occurred_at)")
      .count
  }
end

Instance Method Details

#assign_to!(assignee_name) ⇒ Object

Assignment methods



244
245
246
247
248
249
250
# File 'app/models/rails_error_dashboard/error_log.rb', line 244

def assign_to!(assignee_name)
  update!(
    assigned_to: assignee_name,
    assigned_at: Time.current,
    status: "in_progress" # Auto-transition to in_progress when assigned
  )
end

#assigned?Boolean

Returns:

  • (Boolean)


259
260
261
# File 'app/models/rails_error_dashboard/error_log.rb', line 259

def assigned?
  assigned_to.present?
end

#backtrace_framesObject

Extract backtrace frames for similarity comparison



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'app/models/rails_error_dashboard/error_log.rb', line 401

def backtrace_frames
  return [] if backtrace.blank?

  # Handle different backtrace formats
  lines = if backtrace.is_a?(Array)
    backtrace
  elsif backtrace.is_a?(String)
    # Check if it's a serialized array (starts with "[")
    if backtrace.strip.start_with?("[")
      # Try to parse as JSON array
      begin
        JSON.parse(backtrace)
      rescue JSON::ParserError
        # Fall back to newline split
        backtrace.split("\n")
      end
    else
      backtrace.split("\n")
    end
  else
    []
  end

  lines.first(20).map do |line|
    # Extract file path and method name, ignore line numbers
    if line =~ %r{([^/]+\.rb):.*?in `(.+)'$}
      "#{Regexp.last_match(1)}:#{Regexp.last_match(2)}"
    elsif line =~ %r{([^/]+\.rb)}
      Regexp.last_match(1)
    end
  end.compact.uniq
end

#baseline_anomaly(sensitivity: 2) ⇒ Hash

Check if this error is anomalous compared to baseline

Parameters:

  • sensitivity (Integer) (defaults to: 2)

    Standard deviations threshold (default: 2)

Returns:

  • (Hash)

    Anomaly check result



496
497
498
499
500
501
502
503
504
505
506
507
# File 'app/models/rails_error_dashboard/error_log.rb', line 496

def baseline_anomaly(sensitivity: 2)
  return { anomaly: false, message: "Feature disabled" } unless RailsErrorDashboard.configuration.enable_baseline_alerts
  return { anomaly: false, message: "No baseline available" } unless defined?(Queries::BaselineStats)

  # Get count of this error type today
  today_count = ErrorLog.where(
    error_type: error_type,
    platform: platform
  ).where("occurred_at >= ?", Time.current.beginning_of_day).count

  Queries::BaselineStats.new(error_type, platform).check_anomaly(today_count, sensitivity: sensitivity)
end

#baselinesHash

Get baseline statistics for this error type

Returns:

  • (Hash)

    ErrorBaseline, daily: ErrorBaseline, weekly: ErrorBaseline



486
487
488
489
490
491
# File 'app/models/rails_error_dashboard/error_log.rb', line 486

def baselines
  return {} unless RailsErrorDashboard.configuration.enable_baseline_alerts
  return {} unless defined?(Queries::BaselineStats)

  Queries::BaselineStats.new(error_type, platform).all_baselines
end

#calculate_backtrace_signatureObject

Calculate backtrace signature for fast similarity matching Signature is a hash of the unique file paths in the backtrace



436
437
438
439
440
441
442
443
# File 'app/models/rails_error_dashboard/error_log.rb', line 436

def calculate_backtrace_signature
  frames = backtrace_frames
  return nil if frames.empty?

  # Create signature from sorted file paths (order-independent)
  file_paths = frames.map { |frame| frame.split(":").first }.sort
  Digest::SHA256.hexdigest(file_paths.join("|"))[0..15]
end

#calculate_priorityObject



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'app/models/rails_error_dashboard/error_log.rb', line 305

def calculate_priority
  # Automatic priority calculation based on severity and frequency
  severity_weight = case severity
  when :critical then 3
  when :high then 2
  when :medium then 1
  else 0
  end

  frequency_weight = if occurrence_count >= 100
    3
  elsif occurrence_count >= 10
    2
  elsif occurrence_count >= 5
    1
  else
    0
  end

  # Take the higher of severity or frequency
  [ severity_weight, frequency_weight ].max
end

#calculate_priority_scoreObject



87
88
89
90
91
# File 'app/models/rails_error_dashboard/error_log.rb', line 87

def calculate_priority_score
  return unless respond_to?(:priority_score=)
  self.priority_score = compute_priority_score
  save if persisted?
end

#can_transition_to?(new_status) ⇒ Boolean

Returns:

  • (Boolean)


340
341
342
343
344
345
346
347
348
349
350
351
# File 'app/models/rails_error_dashboard/error_log.rb', line 340

def can_transition_to?(new_status)
  # Define valid status transitions
  valid_transitions = {
    "new" => [ "in_progress", "investigating", "wont_fix" ],
    "in_progress" => [ "investigating", "resolved", "new" ],
    "investigating" => [ "resolved", "in_progress", "wont_fix" ],
    "resolved" => [ "new" ], # Can reopen if error recurs
    "wont_fix" => [ "new" ]  # Can reopen
  }

  valid_transitions[status]&.include?(new_status) || false
end

#co_occurring_errors(window_minutes: 5, min_frequency: 2, limit: 10) ⇒ Array<Hash>

Find errors that occur together in time

Parameters:

  • window_minutes (Integer) (defaults to: 5)

    Time window in minutes (default: 5)

  • min_frequency (Integer) (defaults to: 2)

    Minimum co-occurrence count (default: 2)

  • limit (Integer) (defaults to: 10)

    Maximum results (default: 10)

Returns:

  • (Array<Hash>)

    Array of ErrorLog, frequency: Integer, avg_delay_seconds: Float



460
461
462
463
464
465
466
467
468
469
470
471
# File 'app/models/rails_error_dashboard/error_log.rb', line 460

def co_occurring_errors(window_minutes: 5, min_frequency: 2, limit: 10)
  return [] unless persisted?
  return [] unless RailsErrorDashboard.configuration.enable_co_occurring_errors
  return [] unless defined?(Queries::CoOccurringErrors)

  Queries::CoOccurringErrors.call(
    error_log_id: id,
    window_minutes: window_minutes,
    min_frequency: min_frequency,
    limit: limit
  )
end

#critical?Boolean

Check if this is a critical error

Returns:

  • (Boolean)


111
112
113
# File 'app/models/rails_error_dashboard/error_log.rb', line 111

def critical?
  CRITICAL_ERROR_TYPES.include?(error_type)
end

#error_bursts(days: 7) ⇒ Array<Hash>

Detect error bursts (many errors in short time)

Parameters:

  • days (Integer) (defaults to: 7)

    Number of days to analyze (default: 7)

Returns:

  • (Array<Hash>)

    Array of burst metadata



526
527
528
529
530
531
532
533
534
535
# File 'app/models/rails_error_dashboard/error_log.rb', line 526

def error_bursts(days: 7)
  return [] unless RailsErrorDashboard.configuration.enable_occurrence_patterns
  return [] unless defined?(Services::PatternDetector)

  Services::PatternDetector.detect_bursts(
    error_type: error_type,
    platform: platform,
    days: days
  )
end

#error_cascades(min_probability: 0.5) ⇒ Hash

Find cascade patterns (what causes this error, what this error causes)

Parameters:

  • min_probability (Float) (defaults to: 0.5)

    Minimum cascade probability (0.0-1.0), default 0.5

Returns:

  • (Hash)

    Array, children: Array of cascade patterns



476
477
478
479
480
481
482
# File 'app/models/rails_error_dashboard/error_log.rb', line 476

def error_cascades(min_probability: 0.5)
  return { parents: [], children: [] } unless persisted?
  return { parents: [], children: [] } unless RailsErrorDashboard.configuration.enable_error_cascades
  return { parents: [], children: [] } unless defined?(Queries::ErrorCascades)

  Queries::ErrorCascades.call(error_id: id, min_probability: min_probability)
end

#generate_error_hashObject

Generate unique hash for error grouping Includes controller/action/application for better context-aware grouping Per-app deduplication: same error in App A vs App B creates separate records



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'app/models/rails_error_dashboard/error_log.rb', line 96

def generate_error_hash
  # Hash based on error class, normalized message, first stack frame, controller, action, and application
  digest_input = [
    error_type,
    message&.gsub(/\d+/, "N")&.gsub(/"[^"]*"/, '""'), # Normalize numbers and strings
    backtrace&.lines&.first&.split(":")&.first, # Just the file, not line number
    controller_name,  # Controller context
    action_name,      # Action context
    application_id.to_s  # Application context (for per-app deduplication)
  ].compact.join("|")

  Digest::SHA256.hexdigest(digest_input)[0..15]
end

#occurrence_pattern(days: 30) ⇒ Hash

Detect cyclical occurrence patterns (daily/weekly rhythms)

Parameters:

  • days (Integer) (defaults to: 30)

    Number of days to analyze (default: 30)

Returns:

  • (Hash)

    Pattern analysis result



512
513
514
515
516
517
518
519
520
521
# File 'app/models/rails_error_dashboard/error_log.rb', line 512

def occurrence_pattern(days: 30)
  return {} unless RailsErrorDashboard.configuration.enable_occurrence_patterns
  return {} unless defined?(Services::PatternDetector)

  Services::PatternDetector.analyze_cyclical_pattern(
    error_type: error_type,
    platform: platform,
    days: days
  )
end

#priority_colorObject



295
296
297
298
299
300
301
302
303
# File 'app/models/rails_error_dashboard/error_log.rb', line 295

def priority_color
  case priority_level
  when 3 then "danger"    # Critical = red
  when 2 then "warning"   # High = orange
  when 1 then "info"      # Medium = blue
  when 0 then "secondary" # Low = gray
  else "light"
  end
end

#priority_labelObject

Priority methods



285
286
287
288
289
290
291
292
293
# File 'app/models/rails_error_dashboard/error_log.rb', line 285

def priority_label
  case priority_level
  when 3 then "Critical"
  when 2 then "High"
  when 1 then "Medium"
  when 0 then "Low"
  else "Unset"
  end
end

#recent?Boolean

Check if error is recent (< 1 hour)

Returns:

  • (Boolean)


116
117
118
# File 'app/models/rails_error_dashboard/error_log.rb', line 116

def recent?
  occurred_at >= 1.hour.ago
end

Find related errors of the same type



393
394
395
396
397
398
# File 'app/models/rails_error_dashboard/error_log.rb', line 393

def related_errors(limit: 5, application_id: nil)
  scope = self.class.where(error_type: error_type)
          .where.not(id: id)
  scope = scope.where(application_id: application_id) if application_id.present?
  scope.order(occurred_at: :desc).limit(limit)
end

#resolve!(resolution_data = {}) ⇒ Object

Mark error as resolved (delegates to Command)



237
238
239
# File 'app/models/rails_error_dashboard/error_log.rb', line 237

def resolve!(resolution_data = {})
  Commands::ResolveError.call(id, resolution_data)
end

#set_defaultsObject



70
71
72
# File 'app/models/rails_error_dashboard/error_log.rb', line 70

def set_defaults
  self.platform ||= "API"
end

#set_release_infoObject



81
82
83
84
85
# File 'app/models/rails_error_dashboard/error_log.rb', line 81

def set_release_info
  return unless respond_to?(:app_version=)
  self.app_version ||= fetch_app_version
  self.git_sha ||= fetch_git_sha
end

#set_tracking_fieldsObject



74
75
76
77
78
79
# File 'app/models/rails_error_dashboard/error_log.rb', line 74

def set_tracking_fields
  self.error_hash ||= generate_error_hash
  self.first_seen_at ||= Time.current
  self.last_seen_at ||= Time.current
  self.occurrence_count ||= 1
end

#severityObject

Get severity level Checks custom severity rules first, then falls back to default classification



127
128
129
130
131
132
133
134
135
136
137
# File 'app/models/rails_error_dashboard/error_log.rb', line 127

def severity
  # Check custom severity rules first
  custom_severity = RailsErrorDashboard.configuration.custom_severity_rules[error_type]
  return custom_severity.to_sym if custom_severity.present?

  # Fall back to default classification
  return :critical if CRITICAL_ERROR_TYPES.include?(error_type)
  return :high if HIGH_SEVERITY_ERROR_TYPES.include?(error_type)
  return :medium if MEDIUM_SEVERITY_ERROR_TYPES.include?(error_type)
  :low
end

#similar_errors(threshold: 0.6, limit: 10) ⇒ Array<Hash>

Find similar errors using fuzzy matching

Parameters:

  • threshold (Float) (defaults to: 0.6)

    Minimum similarity score (0.0-1.0), default 0.6

  • limit (Integer) (defaults to: 10)

    Maximum results, default 10

Returns:

  • (Array<Hash>)

    Array of ErrorLog, similarity: Float



449
450
451
452
453
# File 'app/models/rails_error_dashboard/error_log.rb', line 449

def similar_errors(threshold: 0.6, limit: 10)
  return [] unless persisted?
  return [] unless RailsErrorDashboard.configuration.enable_similar_errors
  Queries::SimilarErrors.call(id, threshold: threshold, limit: limit)
end

#snooze!(hours, reason: nil) ⇒ Object

Snooze methods



264
265
266
267
268
269
270
271
272
273
274
# File 'app/models/rails_error_dashboard/error_log.rb', line 264

def snooze!(hours, reason: nil)
  snooze_until = hours.hours.from_now
  # Store snooze reason in comments if provided
  if reason.present?
    comments.create!(
      author_name: assigned_to || "System",
      body: "Snoozed for #{hours} hours: #{reason}"
    )
  end
  update!(snoozed_until: snooze_until)
end

#snoozed?Boolean

Returns:

  • (Boolean)


280
281
282
# File 'app/models/rails_error_dashboard/error_log.rb', line 280

def snoozed?
  snoozed_until.present? && snoozed_until >= Time.current
end

#stale?Boolean

Check if error is old unresolved (> 7 days)

Returns:

  • (Boolean)


121
122
123
# File 'app/models/rails_error_dashboard/error_log.rb', line 121

def stale?
  !resolved? && occurred_at < 7.days.ago
end

#status_badge_colorObject

Status transition methods



329
330
331
332
333
334
335
336
337
338
# File 'app/models/rails_error_dashboard/error_log.rb', line 329

def status_badge_color
  case status
  when "new" then "primary"
  when "in_progress" then "info"
  when "investigating" then "warning"
  when "resolved" then "success"
  when "wont_fix" then "secondary"
  else "light"
  end
end

#unassign!Object



252
253
254
255
256
257
# File 'app/models/rails_error_dashboard/error_log.rb', line 252

def unassign!
  update!(
    assigned_to: nil,
    assigned_at: nil
  )
end

#unsnooze!Object



276
277
278
# File 'app/models/rails_error_dashboard/error_log.rb', line 276

def unsnooze!
  update!(snoozed_until: nil)
end

#update_status!(new_status, comment: nil) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'app/models/rails_error_dashboard/error_log.rb', line 353

def update_status!(new_status, comment: nil)
  return false unless can_transition_to?(new_status)

  transaction do
    update!(status: new_status)

    # Auto-resolve if status is "resolved"
    update!(resolved: true) if new_status == "resolved"

    # Add comment about status change
    if comment.present?
      comments.create!(
        author_name: assigned_to || "System",
        body: "Status changed to #{new_status}: #{comment}"
      )
    end
  end

  true
end