Class: ThreeScale::Backend::Alerts::UsagesChecked

Inherits:
Object
  • Object
show all
Extended by:
KeyHelpers, StorageHelpers
Includes:
Memoizer::Decorator
Defined in:
lib/3scale/backend/alerts.rb

Overview

This class is useful to reduce the amount of information that we need to fetch from Redis to determine whether an alert should be raised. In summary, alerts are raised at the application level and we need to wait for 24h before raising a new one for the same level (ALERTS_BIN above).

This class allows us to check all the usage limits once and then not check all of them again (just the ones in the report job) until: 1) A specific alert has expired (24h passed since it was triggered). 2) A new alert bin is enabled for the service.

Class Method Summary collapse

Methods included from Memoizer::Decorator

included

Class Method Details

.invalidate(service_id, app_id) ⇒ Object



92
93
94
# File 'lib/3scale/backend/alerts.rb', line 92

def self.invalidate(service_id, app_id)
  storage.del(key_usage_already_checked(service_id, app_id))
end

.invalidate_for_service(service_id) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/3scale/backend/alerts.rb', line 96

def self.invalidate_for_service(service_id)
  app_ids = []
  cursor = 0

  loop do
    cursor, ids = storage.sscan(
      Application.applications_set_key(service_id), cursor, count: SCAN_SLICE
    )

    app_ids += ids

    break if cursor.to_i == 0
  end

  invalidate_batch(service_id, app_ids)
end

.mark_all_checked(service_id, app_id) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/3scale/backend/alerts.rb', line 73

def self.mark_all_checked(service_id, app_id)
  ttl = ALERT_BINS.map do |bin|
    ttl = storage.ttl(key_already_notified(service_id, app_id, bin))

    # Redis returns -2 if key does not exist, and -1 if it exists without
    # a TTL (we know this should not happen for the alert bins).
    # In those cases we should just set the TTL to the max (ALERT_TTL).
    ttl >= 0 ? ttl : ALERT_TTL
  end.min

  # Setex fails when ttl = 0. Also, if it's 0, we don't need to mark it
  # as checked, because the "already_notified" key for the bin is just
  # about to expire, so we'll need to check all the usages.
  if ttl > 0
    storage.setex(key_usage_already_checked(service_id, app_id), ttl, '1'.freeze)
    Memoizer.clear(Memoizer.build_key(self, :need_to_check_all?, service_id, app_id))
  end
end

.need_to_check_all?(service_id, app_id) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/3scale/backend/alerts.rb', line 68

def self.need_to_check_all?(service_id, app_id)
  !storage.exists(key_usage_already_checked(service_id, app_id))
end