Sha256: ebd81731db907afc6d16aafa064c720910c8ce4af5d8f2a34b6a710df1b5389d

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module RProxy
  class UsageManager
    def initialize(config, cache_pool, redis)
      @enable_cache = config.enable_cache
      @cache_pool = cache_pool
      @redis = redis
      @no_cache_below = config.no_cache_below
      @check_snapshot_service = RProxy::CheckSnapshotService.new(@redis, config)
    end

    def auth_user(user, pass)
      value = fetch_usage(user, pass)

      return value if !value.nil? && value.to_i > 0
      nil
    end

    def report_usage(user, pass, value)
      return if user.nil? || pass.nil? || value.nil?

      key = proxy_key(user, pass)
      cache = @cache_pool[key]

      if cache.nil? || !@cache_pool.writable?
        @redis.decrby(key, value)
      else
        tmp = cache[:used]
        @cache_pool[key][:used] = tmp + value
      end
    end

    private

    def fetch_usage(user, pass)
      key = proxy_key(user, pass)

      if !@enable_cache || !@cache_pool.writable?

        value = @redis.get(key)
        @check_snapshot_service.call(user, pass, value)

        return value
      end

      cache = @cache_pool[key]

      if cache.nil?

        value = @redis.get(key)

        if !value.nil?
          @check_snapshot_service.call(user, pass, value)
          return value if value.to_i <= @no_cache_below
        end

        @cache_pool[key] = {
          usage: value,
          used: 0
        }
        return value
      end

      cache[:usage]
    end

    def proxy_key(user, pass)
      "proxy:#{user}-#{pass}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
r_proxy-0.2.8 lib/r_proxy/usage_manager.rb
r_proxy-0.2.7 lib/r_proxy/usage_manager.rb
r_proxy-0.2.6 lib/r_proxy/usage_manager.rb