ubicloud/lib/free_quota.rb
Jeremy Evans cf41900951 Avoid use of Time.now in FreeQuota
Use Sequel::CURRENT_TIMESTAMP instead. To get the start of the
month, use the date_trunc PostgreSQL function.

For this to work correctly requires the latest Sequel commit,
so update to that.
2025-08-29 05:36:50 +09:00

46 lines
1.3 KiB
Ruby

# frozen_string_literal: true
require "yaml"
class FreeQuota
# :nocov:
def self.freeze
free_quotas
super
end
# :nocov:
def self.free_quotas
@free_quotas ||= begin
quotas = YAML.load_file("config/free_quotas.yml")
quotas.each_with_object({}) do |item, hash|
item["billing_rate_ids"] = BillingRate.from_resource_type(item["resource_type"]).map { it["id"] }
hash[item["name"]] = item
end
end
@free_quotas
end
def self.remaining_free_quota(name, project_id)
free_quota = free_quotas[name]
used_amount = BillingRecord
.where(project_id:, billing_rate_id: free_quota["billing_rate_ids"])
.where(Sequel.pg_range(:span).overlaps(begin_of_month_till_now))
.sum(:amount) || 0
[0, free_quota["value"] - used_amount].max
end
def self.get_exhausted_projects(name)
free_quota = free_quotas[name]
BillingRecord
.where(billing_rate_id: free_quota["billing_rate_ids"])
.where(Sequel.pg_range(:span).overlaps(begin_of_month_till_now))
.group(:project_id)
.having { sum(:amount) >= free_quota["value"] }
.select(:project_id)
end
def self.begin_of_month_till_now
Sequel::Postgres::PGRange.new(Sequel.function(:date_trunc, "month", Sequel::CURRENT_TIMESTAMP), Sequel::CURRENT_TIMESTAMP, db_type: :tstzrange)
end
end