Class: Prefab::RateLimitClient
- Inherits:
-
Object
- Object
- Prefab::RateLimitClient
- Defined in:
- lib/prefab/ratelimit_client.rb
Instance Method Summary collapse
- #acquire(groups, acquire_amount, allow_partial_response: false, on_error: :log_and_pass) ⇒ Object
-
#initialize(base_client, timeout) ⇒ RateLimitClient
constructor
A new instance of RateLimitClient.
- #pass?(group) ⇒ Boolean
- #upsert(group, policy_name, limit, burst: nil, safety_level: nil) ⇒ Object
Constructor Details
#initialize(base_client, timeout) ⇒ RateLimitClient
Returns a new instance of RateLimitClient.
4 5 6 7 |
# File 'lib/prefab/ratelimit_client.rb', line 4 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
14 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 |
# File 'lib/prefab/ratelimit_client.rb', line 14 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.account_id, 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 => e handle_error(e, on_error, groups) end |
#pass?(group) ⇒ Boolean
9 10 11 12 |
# File 'lib/prefab/ratelimit_client.rb', line 9 def pass?(group) result = acquire([group], 1) return result.passed end |
#upsert(group, policy_name, limit, burst: nil, safety_level: nil) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/prefab/ratelimit_client.rb', line 42 def upsert(group, policy_name, limit, burst: nil, safety_level: nil) burst = limit if burst.nil? limit_defintion = Prefab::LimitDefinition.new( account_id: @base_client.account_id, group: group, policy_name: Object.const_get("Prefab::LimitResponse::LimitPolicyNames::#{policy_name}"), limit: limit, burst: burst ) unless safety_level.nil? limit_defintion.safety_level = safety_level end @base_client.request Prefab::RateLimitService, :upsert_limit_definition, params: limit_defintion end |