Class: LlmCostTracker::Storage::ActiveRecordRollups

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_cost_tracker/storage/active_record_rollups.rb

Class Method Summary collapse

Class Method Details

.decrement!(call_rows) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/llm_cost_tracker/storage/active_record_rollups.rb', line 44

def decrement!(call_rows)
  return unless period_totals_enabled?

  totals = period_decrement_totals(call_rows)
  return if totals.empty?

  apply_decrements(totals)
end

.increment!(event) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/llm_cost_tracker/storage/active_record_rollups.rb', line 17

def increment!(event)
  return unless event.cost&.total_cost
  return unless period_totals_enabled?

  model = period_total_model
  model.upsert_all(
    period_rows(event),
    on_duplicate: ActiveRecordRollupUpsertSql.call(model),
    record_timestamps: true,
    unique_by: unique_by(model, %i[period period_start])
  )
end

.increment_many!(events) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/llm_cost_tracker/storage/active_record_rollups.rb', line 30

def increment_many!(events)
  events = Array(events).select { |event| event.cost&.total_cost }
  return if events.empty?
  return unless period_totals_enabled?

  model = period_total_model
  model.upsert_all(
    ActiveRecordRollupBatch.rows(events),
    on_duplicate: ActiveRecordRollupUpsertSql.call(model),
    record_timestamps: true,
    unique_by: unique_by(model, %i[period period_start])
  )
end

.period_totals(periods, time: Time.now.utc) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/llm_cost_tracker/storage/active_record_rollups.rb', line 53

def period_totals(periods, time: Time.now.utc)
  periods = ActiveRecordPeriods.valid_keys(periods)
  return {} if periods.empty?

  if period_totals_enabled?
    rollup_period_totals(periods, time)
  else
    periods.to_h { |period| [period, fallback_period_total(period, time)] }
  end
end

.reset!Object



13
14
15
# File 'lib/llm_cost_tracker/storage/active_record_rollups.rb', line 13

def reset!
  remove_instance_variable(:@period_totals_enabled) if instance_variable_defined?(:@period_totals_enabled)
end