5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-29 23:56:22 +00:00
panel/app/jobs/concerns/recursive_rollup.rb

61 lines
1.8 KiB
Ruby
Raw Normal View History

2022-04-23 23:32:20 +00:00
# frozen_string_literal: true
# Implementa rollups recursivos
2022-04-23 23:32:20 +00:00
module RecursiveRollup
extend ActiveSupport::Concern
included do
private
# Genera un rollup recursivo en base al período anterior y aplica una
# operación.
#
# @param :name [String]
# @param :interval_previous [String]
# @param :interval [String]
# @param :operation [Symbol]
# @param :dimensions [Hash]
# @param :beginning [Time]
# @return [Rollup]
def recursive_rollup(name:, interval_previous:, interval:, dimensions:, beginning:, operation: :sum)
Rollup.where(name: name, interval: interval_previous, dimensions: dimensions)
.where('time >= ?', beginning.try(:"beginning_of_#{interval}"))
.group(*dimensions_to_jsonb_query(dimensions))
.rollup(name, interval: interval, update: true) do |rollup|
2022-04-23 23:32:20 +00:00
rollup.try(operation, :value)
end
end
2022-04-30 17:39:31 +00:00
# Reducir las estadísticas calculadas aplicando un rollup sobre el
# intervalo más amplio.
#
# @param :name [String]
# @param :operation [Symbol]
# @param :dimensions [Hash]
# @return [nil]
def reduce_rollup(name:, dimensions:, operation: :sum)
2022-04-30 17:39:31 +00:00
Stat::INTERVALS.reduce do |previous, current|
recursive_rollup(name: name,
interval_previous: previous,
interval: current,
dimensions: dimensions,
beginning: beginning_of_interval,
2022-04-30 17:39:31 +00:00
operation: operation)
# Devolver el intervalo actual
current
end
nil
end
2022-04-23 23:32:20 +00:00
# @param :dimensions [Hash]
# @return [Array]
def dimensions_to_jsonb_query(dimensions)
dimensions.keys.map do |key|
"dimensions->'#{key}'"
end
end
end
end