check.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. module Blazer
  2. class Check < ActiveRecord::Base
  3. belongs_to :creator, Blazer::BELONGS_TO_OPTIONAL.merge(class_name: Blazer.user_class.to_s) if Blazer.user_class
  4. belongs_to :query
  5. validates :query_id, presence: true
  6. before_validation :set_state
  7. before_validation :fix_emails
  8. def split_emails
  9. emails.to_s.downcase.split(",").map(&:strip)
  10. end
  11. def update_state(result)
  12. check_type =
  13. if respond_to?(:check_type)
  14. self.check_type
  15. elsif respond_to?(:invert)
  16. invert ? "missing_data" : "bad_data"
  17. else
  18. "bad_data"
  19. end
  20. message = result.error
  21. self.state =
  22. if result.timed_out?
  23. "timed out"
  24. elsif result.error
  25. "error"
  26. elsif check_type == "anomaly"
  27. anomaly, message = result.detect_anomaly
  28. if anomaly.nil?
  29. "error"
  30. elsif anomaly
  31. "failing"
  32. else
  33. "passing"
  34. end
  35. elsif result.rows.any?
  36. check_type == "missing_data" ? "passing" : "failing"
  37. else
  38. check_type == "missing_data" ? "failing" : "passing"
  39. end
  40. self.last_run_at = Time.now if respond_to?(:last_run_at=)
  41. self.message = message if respond_to?(:message=)
  42. if respond_to?(:timeouts=)
  43. if result.timed_out?
  44. self.timeouts += 1
  45. self.state = "disabled" if timeouts >= 3
  46. else
  47. self.timeouts = 0
  48. end
  49. end
  50. # do not notify on creation, except when not passing
  51. if (state_was != "new" || state != "passing") && state != state_was && emails.present?
  52. Blazer::CheckMailer.state_change(self, state, state_was, result.rows.size, message, result.columns, result.rows.first(10).as_json, result.column_types, check_type).deliver_later
  53. end
  54. save! if changed?
  55. end
  56. private
  57. def set_state
  58. self.state ||= "new"
  59. end
  60. def fix_emails
  61. # some people like doing ; instead of ,
  62. # but we know what they mean, so let's fix it
  63. self.emails = emails.gsub(";", ",") if emails.present?
  64. end
  65. end
  66. end