Class: ThrottleMachines::RackMiddleware::Track

Inherits:
Object
  • Object
show all
Defined in:
lib/throttle_machines/rack_middleware/track.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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, options = {}, &block)
  @name = name
  @block = block
  @limit = options[:limit]
  @period = options[:period]
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



6
7
8
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6

def block
  @block
end

#limitObject (readonly)

Returns the value of attribute limit.



6
7
8
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6

def limit
  @limit
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/throttle_machines/rack_middleware/track.rb', line 6

def name
  @name
end

#periodObject (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

Returns:

  • (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