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.0.4 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.0.3 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.0.2 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.0.1 lib/macaw_framework/middlewares/rate_limiter_middleware.rb
macaw_framework-1.0.0 lib/macaw_framework/middlewares/rate_limiter_middleware.rb