60 lines
1.6 KiB
Ruby
60 lines
1.6 KiB
Ruby
# frozen_string_literal: true
|
||
|
||
module Streams
|
||
# Finestra notturna (default 02:00–07:00 Europe/Rome) in cui non devono restare CPX idle.
|
||
module QuietHours
|
||
DEFAULT_RANGE = "02:00-07:00"
|
||
DEFAULT_TZ = "Europe/Rome"
|
||
|
||
module_function
|
||
|
||
def range_config
|
||
ENV.fetch("STREAM_AUTOSCALE_QUIET_HOURS", DEFAULT_RANGE).to_s.strip
|
||
end
|
||
|
||
def time_zone_name
|
||
ENV.fetch("STREAM_AUTOSCALE_QUIET_TZ", DEFAULT_TZ)
|
||
end
|
||
|
||
def configured?
|
||
range_config.present? && range_config != "off" && range_config != "0"
|
||
end
|
||
|
||
def active?(now: Time.current)
|
||
return false unless configured?
|
||
|
||
zone = ActiveSupport::TimeZone[time_zone_name] || Time.find_zone!(time_zone_name)
|
||
local = now.in_time_zone(zone)
|
||
start_min, end_min = parse_range(range_config)
|
||
return false if start_min.nil? || end_min.nil?
|
||
|
||
current = local.hour * 60 + local.min
|
||
if start_min <= end_min
|
||
current >= start_min && current < end_min
|
||
else
|
||
# es. 22:00-06:00
|
||
current >= start_min || current < end_min
|
||
end
|
||
rescue ArgumentError => e
|
||
Rails.logger.warn("[Streams::QuietHours] invalid config: #{e.message}")
|
||
false
|
||
end
|
||
|
||
def parse_range(raw)
|
||
start_s, end_s = raw.split("-", 2).map { |p| p.to_s.strip }
|
||
return [nil, nil] if start_s.blank? || end_s.blank?
|
||
|
||
[parse_hhmm(start_s), parse_hhmm(end_s)]
|
||
end
|
||
|
||
def parse_hhmm(value)
|
||
h, m = value.split(":", 2)
|
||
hours = Integer(h)
|
||
mins = Integer(m || 0)
|
||
raise ArgumentError, "ora fuori range: #{value}" unless hours.between?(0, 23) && mins.between?(0, 59)
|
||
|
||
hours * 60 + mins
|
||
end
|
||
end
|
||
end
|