Class: ThrottleMachines::RackMiddleware::Track
- Inherits:
-
Object
- Object
- ThrottleMachines::RackMiddleware::Track
- Defined in:
- lib/throttle_machines/rack_middleware/track.rb
Instance Attribute Summary collapse
-
#block ⇒ Object
readonly
Returns the value of attribute block.
-
#limit ⇒ Object
readonly
Returns the value of attribute limit.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#period ⇒ Object
readonly
Returns the value of attribute period.
Instance Method Summary collapse
-
#initialize(name, options = {}, &block) ⇒ Track
constructor
A new instance of Track.
- #matched_by?(request) ⇒ Boolean
Constructor Details
#initialize(name, options = {}, &block) ⇒ Track
Returns a new instance of Track.
8 9 10 11 12 13 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 8 def initialize(name, = {}, &block) @name = name @block = block @limit = [:limit] @period = [:period] end |
Instance Attribute Details
#block ⇒ Object (readonly)
Returns the value of attribute block.
6 7 8 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6 def block @block end |
#limit ⇒ Object (readonly)
Returns the value of attribute limit.
6 7 8 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6 def limit @limit end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
6 7 8 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6 def name @name end |
#period ⇒ Object (readonly)
Returns the value of attribute period.
6 7 8 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6 def period @period end |
Instance Method Details
#matched_by?(request) ⇒ Boolean
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 43 44 45 46 47 48 |
# File 'lib/throttle_machines/rack_middleware/track.rb', line 15 def matched_by?(request) discriminator = @block.call(request) return false unless discriminator # Track is just instrumentation without blocking data = { discriminator: discriminator } # If limit and period are provided, track the count if @limit && @period key = "track:#{@name}:#{discriminator}" limiter = ThrottleMachines.limiter( key, limit: @limit, period: @period, algorithm: :fixed_window ) # Just check, don't consume data[:count] = @limit - limiter.remaining data[:limit] = @limit data[:period] = @period end request.env['rack.attack.matched'] = @name request.env['rack.attack.match_type'] = :track request.env['rack.attack.match_discriminator'] = discriminator request.env['rack.attack.match_data'] = data ThrottleMachines::RackMiddleware.instrument(request) false # Track never blocks end |