Class: Prefab::RateLimitClient

Inherits:
Object
  • Object
show all
Defined in:
lib/prefab/ratelimit_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_client, timeout) ⇒ RateLimitClient

Returns a new instance of RateLimitClient.



5
6
7
8
# File 'lib/prefab/ratelimit_client.rb', line 5

def initialize(base_client, timeout)
  @timeout = timeout
  @base_client = base_client
end

Instance Method Details

#acquire(groups, acquire_amount, allow_partial_response: false, on_error: :log_and_pass) ⇒ Object



15
16
17
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
# File 'lib/prefab/ratelimit_client.rb', line 15

def acquire(groups, acquire_amount, allow_partial_response: false, on_error: :log_and_pass)
  expiry_cache_key = "prefab.ratelimit.expiry:#{groups.join('.')}"
  expiry = @base_client.shared_cache.read(expiry_cache_key)
  if !expiry.nil? && Integer(expiry) > Time.now.utc.to_f * 1000
    @base_client.stats.increment('prefab.ratelimit.limitcheck.expirycache.hit', tags: [])
    return Prefab::LimitResponse.new(passed: false, amount: 0)
  end

  req = Prefab::LimitRequest.new(
    account_id: @base_client.,
    acquire_amount: acquire_amount,
    groups: groups,
    allow_partial_response: allow_partial_response
  )

  result = @base_client.request Prefab::RateLimitService, :limit_check, req_options: { timeout: @timeout },
                                                                        params: req

  reset = result.limit_reset_at
  @base_client.shared_cache.write(expiry_cache_key, reset) unless reset < 1 # protobuf default int to 0

  @base_client.stats.increment('prefab.ratelimit.limitcheck',
                               tags: ["policy_group:#{result.policy_group}", "pass:#{result.passed}"])

  result
rescue StandardError => e
  handle_error(e, on_error, groups)
end

#pass?(group) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
# File 'lib/prefab/ratelimit_client.rb', line 10

def pass?(group)
  result = acquire([group], 1)
  result.passed
end

#upsert(key, policy_name, limit, burst: nil, safety_level: nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/prefab/ratelimit_client.rb', line 44

def upsert(key, policy_name, limit, burst: nil, safety_level: nil)
  burst = limit if burst.nil?
  limit_definition = Prefab::LimitDefinition.new(
    account_id: @base_client.,
    policy_name: Object.const_get("Prefab::LimitResponse::LimitPolicyNames::#{policy_name}"),
    limit: limit,
    burst: burst
  )
  limit_definition.safety_level = safety_level unless safety_level.nil?
  config_value = Prefab::ConfigValue.new(limit_definition: limit_definition)
  config_delta = Prefab::ConfigClient.value_to_delta(key, config_value)
  upsert_req = Prefab::UpsertRequest.new(config_delta: config_delta)

  @base_client.request Prefab::ConfigService, :upsert, req_options: { timeout: @timeout }, params: upsert_req
end