check.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. module Blazer
  2. class Check < Record
  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. validate :validate_emails
  7. validate :validate_variables, if: -> { query_id_changed? }
  8. before_validation :set_state
  9. before_validation :fix_emails
  10. def split_emails
  11. emails.to_s.downcase.split(",").map(&:strip)
  12. end
  13. def update_state(result)
  14. check_type =
  15. if respond_to?(:check_type)
  16. self.check_type
  17. elsif respond_to?(:invert)
  18. invert ? "missing_data" : "bad_data"
  19. else
  20. "bad_data"
  21. end
  22. message = result.error
  23. self.state =
  24. if result.timed_out?
  25. "timed out"
  26. elsif result.error
  27. "error"
  28. elsif check_type == "anomaly"
  29. anomaly, message = result.detect_anomaly
  30. if anomaly.nil?
  31. "error"
  32. elsif anomaly
  33. "failing"
  34. else
  35. "passing"
  36. end
  37. elsif result.rows.any?
  38. check_type == "missing_data" ? "passing" : "failing"
  39. else
  40. check_type == "missing_data" ? "failing" : "passing"
  41. end
  42. self.last_run_at = Time.now if respond_to?(:last_run_at=)
  43. self.message = message if respond_to?(:message=)
  44. if respond_to?(:timeouts=)
  45. if result.timed_out?
  46. self.timeouts += 1
  47. self.state = "disabled" if timeouts >= 3
  48. else
  49. self.timeouts = 0
  50. end
  51. end
  52. # do not notify on creation, except when not passing
  53. if (state_was != "new" || state != "passing") && state != state_was && emails.present?
  54. 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_now
  55. end
  56. save! if changed?
  57. end
  58. private
  59. def set_state
  60. self.state ||= "new"
  61. end
  62. def fix_emails
  63. # some people like doing ; instead of ,
  64. # but we know what they mean, so let's fix it
  65. # also, some people like to use whitespace
  66. if emails.present?
  67. self.emails = emails.strip.gsub(/[;\s]/, ",").gsub(/,+/, ", ")
  68. end
  69. end
  70. def validate_emails
  71. unless split_emails.all? { |e| e =~ /\A\S+@\S+\.\S+\z/ }
  72. errors.add(:base, "Invalid emails")
  73. end
  74. end
  75. def validate_variables
  76. if query.variables.any?
  77. errors.add(:base, "Query can't have variables")
  78. end
  79. end
  80. end
  81. end