Sha256: e6340e64ee982558a76f9482d3b168eed01e996db68a50f69179b7f0c94fadb0

Contents?: true

Size: 1.55 KB

Versions: 22

Compression:

Stored size: 1.55 KB

Contents

require 'digest'

module Stackify
  class ErrorsGovernor

    def initialize purge_period=5
      @history = {}
      @@history_lock = Mutex.new
      @purge_period = purge_period
      update_purge_times
    end

    def can_send? ex
      key = unique_key_of(ex)
      @@history_lock.synchronize do
        epoch_minute = current_minute
        init_history_key_if_not_exists key, epoch_minute
        history_entry = @history[key]
        if history_entry[:epoch_minute] == epoch_minute
          history_entry[:count] += 1
          answer = history_entry[:count] <= Stackify.configuration.flood_limit
        else
          @history[key]={
            epoch_minute: epoch_minute,
            count: 1
          }
          answer = true
        end
        clear_old_history_entries if time_for_purge_is_come?
        answer
      end
    end

    private

    def unique_key_of ex
      str = "#{ex.backtrace[0]['LineNum']}-#{ex.source_method}-#{ex.error_type}"
      Digest::MD5.hexdigest str
    end

    def init_history_key_if_not_exists key, minute
      @history[key] ||= {
        epoch_minute: minute,
        count: 0
      }
    end

    def clear_old_history_entries
      @history.keep_if{ |_key, entry| entry[:epoch_minute] == current_minute }
      update_purge_times
    end

    def update_purge_times
      @last_purge_minute = current_minute
      @next_purge_minute = @last_purge_minute + @purge_period
    end

    def current_minute
      Time.now.to_i/60
    end

    def time_for_purge_is_come?
      !(current_minute < @next_purge_minute)
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
stackify-api-ruby-2.1.0 lib/stackify/errors_governor.rb
stackify-api-ruby-2.1.0.beta1 lib/stackify/errors_governor.rb
stackify-api-ruby-2.0.0 lib/stackify/errors_governor.rb
stackify-api-ruby-1.3.0.beta1 lib/stackify/errors_governor.rb
stackify-api-ruby-1.2.10 lib/stackify/errors_governor.rb
stackify-api-ruby-1.2.9 lib/stackify/errors_governor.rb
stackify-api-ruby-1.2.7 lib/stackify/errors_governor.rb
stackify-api-ruby-1.2.4 lib/stackify/errors_governor.rb
stackify-api-ruby-1.2.3 lib/stackify/errors_governor.rb
stackify-api-ruby-1.1.0 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.15 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.14 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.13 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.12 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.11 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.10 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.9 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.8 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.7 lib/stackify/errors_governor.rb
stackify-api-ruby-1.0.6 lib/stackify/errors_governor.rb