Class: RateThrottleClient::GcraFakeServer

Inherits:
Object
  • Object
show all
Defined in:
lib/rate_throttle_client/servers/gcra/gcra_fake_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(starting_limit: 0) ⇒ GcraFakeServer

Returns a new instance of GcraFakeServer.



11
12
13
14
15
16
# File 'lib/rate_throttle_client/servers/gcra/gcra_fake_server.rb', line 11

def initialize(starting_limit: 0)
  @limit_left = starting_limit.to_f
  @mutex = Mutex.new
  @rate_of_gain = RateThrottleClient.max_limit / 3600.to_f
  @max_requests = RateThrottleClient.max_limit
end

Instance Method Details

#call(_) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rate_throttle_client/servers/gcra/gcra_fake_server.rb', line 18

def call(_)
  @last_request ||= Time.now
  headers = nil
  successful_request = false

  @mutex.synchronize do
    if @limit_left < @max_requests
      current_request = Time.now
      time_diff = current_request - @last_request
      @last_request = current_request

      @limit_left = [@limit_left + time_diff * @rate_of_gain, @max_requests].min
    end

    if @limit_left >= 1
      @limit_left -= 1
      successful_request = true
    end

    headers = { "RateLimit-Remaining" => [@limit_left.floor, 0].max, "RateLimit-Multiplier" => 1, "Content-Type" => "text/plain".freeze }
  end


  if !successful_request
    status = 429
    body = "!!!!! Nope !!!!!".freeze
  else
    status = 200
    body = "<3<3<3 Hello world <3<3<3".freeze
  end

  return [status, headers, [body]]
end