Farmbot-Web-App/app/lib/throttle_policy.rb

29 lines
829 B
Ruby
Raw Normal View History

2018-05-23 07:53:43 -06:00
# Handles devices that spin out of control and send too many logs to the server.
# Class Hierarchy:
2019-02-19 19:10:08 -07:00
# ThrottlePolicy has => Rules creates => Violation
2018-05-23 07:53:43 -06:00
# Violation has => Rule has => TimePeriod
2018-05-18 10:46:02 -06:00
class ThrottlePolicy
attr_reader :rules
2019-02-19 19:10:08 -07:00
# Dictionary<TimePeriod, Integer>
2018-05-18 10:46:02 -06:00
def initialize(policy_rules)
@rules = policy_rules.map { |rule_set| Rule.new(*rule_set) }
end
def track(unique_id, now = Time.now)
2018-05-23 07:53:43 -06:00
rules.each { |r| r.time_period.record_event(unique_id, now) }
end
# If throttled, returns the timeperiod when device will be unthrottled
# returns nil if not throttled
2018-05-18 13:21:04 -06:00
def is_throttled(unique_id)
rules
.map do |rule|
2018-05-23 07:53:43 -06:00
is_violation = rule.time_period.usage_count_for(unique_id) > rule.limit
2018-05-22 14:36:05 -06:00
is_violation ? Violation.new(rule) : nil
end
.compact
.max
end
2018-05-18 10:46:02 -06:00
end