Sha256: 884e49530e38d0186019dc75b3a79c945d7cb502557fdf655dd8e1e233029325

Contents?: true

Size: 701 Bytes

Versions: 25

Compression:

Stored size: 701 Bytes

Contents

# frozen_string_literal: true

##
# Middleware responsible for implementing
# rate limiting
class RateLimiterMiddleware
  attr_reader :window_size, :max_requests

  def initialize(window_size, max_requests)
    @window_size = window_size
    @max_requests = max_requests
    @client_timestamps = Hash.new { |key, value| key[value] = [] }
    @mutex = Mutex.new
  end

  def allow?(client_id)
    @mutex.synchronize do
      now = Time.now.to_i
      timestamps = @client_timestamps[client_id]

      timestamps.reject! { |timestamp| timestamp <= now - window_size }

      if timestamps.length < max_requests
        timestamps << now
        true
      else
        false
      end
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
macaw_framework-1.3.21 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.3.1 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.3.0 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.6 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.5 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.4 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.3 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.2 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.1 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.2.0 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.8 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.7 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.6 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.5 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.4 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.3 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.2 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.1 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.1.0 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.0.5 lib/macaw_framework/middlewares/rate_limiter_middleware.rb