This commit is contained in:
Mahad Kalam 2026-02-10 00:29:59 +00:00
parent fecf4f79ba
commit c96da270d3

View file

@ -253,12 +253,15 @@ module Heartbeatable
timeout = heartbeat_timeout_duration.to_i
scope = with_valid_timestamps.where.not(time: nil)
# We calculate independent diffs for each dimension (partitioned) to replicate
# the "group(...).duration_seconds" behavior which counts parallel/overlapping time.
sql = <<~SQL.squish
SELECT project, language, editor, operating_system, category, time,
CASE
WHEN LAG(time) OVER (ORDER BY time) IS NULL THEN 0
ELSE LEAST(time - LAG(time) OVER (ORDER BY time), #{timeout})
END as diff
LEAST(COALESCE(time - LAG(time) OVER (PARTITION BY project ORDER BY time), 0), #{timeout}) as diff_project,
LEAST(COALESCE(time - LAG(time) OVER (PARTITION BY language ORDER BY time), 0), #{timeout}) as diff_language,
LEAST(COALESCE(time - LAG(time) OVER (PARTITION BY editor ORDER BY time), 0), #{timeout}) as diff_editor,
LEAST(COALESCE(time - LAG(time) OVER (PARTITION BY operating_system ORDER BY time), 0), #{timeout}) as diff_os,
LEAST(COALESCE(time - LAG(time) OVER (PARTITION BY category ORDER BY time), 0), #{timeout}) as diff_category
FROM (#{scope.to_sql}) AS hb
SQL
@ -282,21 +285,26 @@ module Heartbeatable
end
rows.each do |row|
diff = row["diff"].to_i
next if diff <= 0
d_project = row["diff_project"].to_i
d_language = row["diff_language"].to_i
d_editor = row["diff_editor"].to_i
d_os = row["diff_os"].to_i
d_category = row["diff_category"].to_i
total_time += diff
by_project[row["project"]] += diff
by_language[row["language"]] += diff
by_editor[row["editor"]] += diff
by_operating_system[row["operating_system"]] += diff
by_category[row["category"]] += diff
if d_project > 0
by_project[row["project"]] += d_project
total_time += d_project
end
by_language[row["language"]] += d_language if d_language > 0
by_editor[row["editor"]] += d_editor if d_editor > 0
by_operating_system[row["operating_system"]] += d_os if d_os > 0
by_category[row["category"]] += d_category if d_category > 0
if week_lookup.any?
if week_lookup.any? && d_project > 0
t = row["time"].to_f
week_lookup.each do |label, ws, we|
if t >= ws && t <= we
weekly_projects[label][row["project"]] += diff
weekly_projects[label][row["project"]] += d_project
break
end
end