Class: Clacky::Billing::BillingStore

Inherits:
Object
  • Object
show all
Defined in:
lib/clacky/billing/billing_store.rb

Overview

Persistent storage for billing records using JSONL files Records are stored in monthly files: ~/.clacky/billing/YYYY-MM.jsonl

Constant Summary collapse

BILLING_DIR =
File.join(Dir.home, ".clacky", "billing")

Instance Method Summary collapse

Constructor Details

#initialize(billing_dir: nil) ⇒ BillingStore

Returns a new instance of BillingStore.



15
16
17
18
# File 'lib/clacky/billing/billing_store.rb', line 15

def initialize(billing_dir: nil)
  @billing_dir = billing_dir || BILLING_DIR
  ensure_billing_dir
end

Instance Method Details

#append(record) ⇒ String

Append a billing record to the current month’s file

Parameters:

Returns:

  • (String)

    The record ID



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/clacky/billing/billing_store.rb', line 23

def append(record)
  record.id ||= SecureRandom.uuid
  record.timestamp ||= Time.now

  month_file = current_month_file
  File.open(month_file, "a") do |f|
    f.puts(JSON.generate(record.to_h))
  end
  FileUtils.chmod(0o600, month_file)

  record.id
end

#cleanup(before:) ⇒ Integer

Delete old billing records

Parameters:

  • before (Time)

    Delete records before this time

Returns:

  • (Integer)

    Number of files deleted



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/clacky/billing/billing_store.rb', line 251

def cleanup(before:)
  deleted = 0
  billing_files.each do |file|
    # Parse month from filename (YYYY-MM.jsonl)
    basename = File.basename(file, ".jsonl")
    file_month = Time.parse("#{basename}-01") rescue nil
    next unless file_month

    # Delete if the entire month is before the cutoff
    if file_month < before - (31 * 24 * 60 * 60)
      File.delete(file)
      deleted += 1
    end
  end
  deleted
end

#clear(scope: :today) ⇒ Integer

Clear billing records

Parameters:

  • scope (Symbol) (defaults to: :today)

    :today or :all

Returns:

  • (Integer)

    Number of records/files deleted



271
272
273
274
275
276
277
278
279
280
# File 'lib/clacky/billing/billing_store.rb', line 271

def clear(scope: :today)
  case scope
  when :today
    clear_today
  when :all
    clear_all
  else
    0
  end
end

#daily_breakdown(days: 30, model: nil) ⇒ Array<Hash>

Get daily cost breakdown for the last N days # @param days [Integer] Number of days to include

Parameters:

  • model (String, nil) (defaults to: nil)

    Filter by model name

Returns:

  • (Array<Hash>)

    Daily summaries with date and cost



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/clacky/billing/billing_store.rb', line 226

def daily_breakdown(days: 30, model: nil)
  from_time = Time.now - (days * 24 * 60 * 60)
  records = query(from: from_time, model: model)

  by_day = records.group_by { |r| r.timestamp.strftime("%Y-%m-%d") }

  (0...days).map do |i|
    date = (Time.now - (i * 24 * 60 * 60)).strftime("%Y-%m-%d")
    day_records = by_day[date] || []
    {
      date: date,
      cost: day_records.sum { |r| r.cost_usd || 0 }.round(6),
      tokens: day_records.sum { |r| r.total_tokens },
      prompt_tokens: day_records.sum { |r| r.prompt_tokens || 0 },
      completion_tokens: day_records.sum { |r| r.completion_tokens || 0 },
      cache_read_tokens: day_records.sum { |r| r.cache_read_tokens || 0 },
      cache_write_tokens: day_records.sum { |r| r.cache_write_tokens || 0 },
      requests: day_records.size
    }
  end.reverse
end

#load_session_namesObject

Load session names from session manager (including trashed sessions) Returns a hash mapping session_id to session name



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/clacky/billing/billing_store.rb', line 196

def load_session_names
  names = {}
  begin
    # Load from active sessions
    manager = Clacky::SessionManager.new
    manager.all_sessions.each do |session|
      id = session[:session_id]
      name = session[:name]
      names[id] = name if id && name && !name.to_s.empty?
    end

    # Also load from trashed sessions
    trash_dir = File.join(Dir.home, ".clacky", "trash", "sessions-trash")
    if Dir.exist?(trash_dir)
      Dir.glob(File.join(trash_dir, "*.json")).each do |filepath|
        session = JSON.parse(File.read(filepath), symbolize_names: true) rescue next
        id = session[:session_id]
        name = session[:name]
        names[id] = name if id && name && !name.to_s.empty?
      end
    end
  rescue => e
    # Silently fail if session manager is not available
  end
  names
end

#query(from: nil, to: nil, model: nil, session_id: nil, limit: nil) ⇒ Array<BillingRecord>

Query billing records with optional filters

Parameters:

  • from (Time, nil) (defaults to: nil)

    Start time (inclusive)

  • to (Time, nil) (defaults to: nil)

    End time (inclusive)

  • model (String, nil) (defaults to: nil)

    Filter by model name

  • session_id (String, nil) (defaults to: nil)

    Filter by session ID

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of records to return

Returns:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/clacky/billing/billing_store.rb', line 43

def query(from: nil, to: nil, model: nil, session_id: nil, limit: nil)
  records = []

  billing_files.each do |file|
    File.foreach(file) do |line|
      next if line.strip.empty?

      begin
        hash = JSON.parse(line, symbolize_names: true)
        record = BillingRecord.from_h(hash)

        # Apply filters
        next if from && record.timestamp < from
        next if to && record.timestamp > to
        next if model && record.model != model
        next if session_id && record.session_id != session_id

        records << record
      rescue JSON::ParserError
        # Skip malformed lines
        next
      end
    end
  end

  # Sort by timestamp descending (newest first)
  records.sort_by! { |r| r.timestamp }.reverse!

  # Apply limit
  limit ? records.first(limit) : records
end

#session_summary(period: :month, model: nil, limit: 50) ⇒ Array<Hash>

Get session-level summary statistics

Parameters:

  • period (Symbol) (defaults to: :month)

    :day, :week, :month, :year, or :all

  • model (String, nil) (defaults to: nil)

    Filter by model name

  • limit (Integer) (defaults to: 50)

    Maximum number of sessions to return

Returns:

  • (Array<Hash>)

    Session summaries sorted by cost descending



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/clacky/billing/billing_store.rb', line 123

def session_summary(period: :month, model: nil, limit: 50)
  from_time = period_start(period)
  records = query(from: from_time, model: model)

  # Load session names from session manager
  session_names = load_session_names

  # Group by session_id
  by_session = records.group_by { |r| r.session_id || "unknown" }

  active_sessions = []
  deleted_records = []

  by_session.each do |session_id, rs|
    total_cost = rs.sum { |r| r.cost_usd || 0 }
    total_prompt = rs.sum { |r| r.prompt_tokens || 0 }
    total_completion = rs.sum { |r| r.completion_tokens || 0 }
    total_cache_read = rs.sum { |r| r.cache_read_tokens || 0 }
    total_cache_write = rs.sum { |r| r.cache_write_tokens || 0 }
    first_record = rs.min_by { |r| r.timestamp }
    last_record = rs.max_by { |r| r.timestamp }

    entry = {
      session_id: session_id,
      session_name: session_names[session_id],
      total_cost: total_cost.round(6),
      total_tokens: total_prompt + total_completion,
      prompt_tokens: total_prompt,
      completion_tokens: total_completion,
      cache_read_tokens: total_cache_read,
      cache_write_tokens: total_cache_write,
      requests: rs.size,
      first_request: first_record&.timestamp&.iso8601,
      last_request: last_record&.timestamp&.iso8601,
      models: rs.map(&:model).uniq
    }

    if session_names[session_id]
      active_sessions << entry
    else
      deleted_records << entry
    end
  end

  # Merge all deleted sessions into a single row
  if deleted_records.any?
    merged = {
      session_id: "_deleted_",
      session_name: nil,
      is_deleted: true,
      total_cost: deleted_records.sum { |r| r[:total_cost] }.round(6),
      total_tokens: deleted_records.sum { |r| r[:total_tokens] },
      prompt_tokens: deleted_records.sum { |r| r[:prompt_tokens] },
      completion_tokens: deleted_records.sum { |r| r[:completion_tokens] },
      cache_read_tokens: deleted_records.sum { |r| r[:cache_read_tokens] },
      cache_write_tokens: deleted_records.sum { |r| r[:cache_write_tokens] },
      requests: deleted_records.sum { |r| r[:requests] },
      first_request: deleted_records.map { |r| r[:first_request] }.compact.min,
      last_request: deleted_records.map { |r| r[:last_request] }.compact.max,
      models: deleted_records.flat_map { |r| r[:models] }.uniq
    }
    active_sessions << merged
  end

  # Sort by total cost descending
  active_sessions.sort_by! { |s| -s[:total_cost] }

  # Apply limit
  limit ? active_sessions.first(limit) : active_sessions
end

#summary(period: :month, model: nil) ⇒ Hash

Get summary statistics for a time period

Parameters:

  • period (Symbol) (defaults to: :month)

    :day, :week, :month, :year, or :all

  • model (String, nil) (defaults to: nil)

    Filter by model name

Returns:

  • (Hash)

    Summary with total_cost, total_tokens, by_model, etc.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/clacky/billing/billing_store.rb', line 79

def summary(period: :month, model: nil)
  from_time = period_start(period)
  records = query(from: from_time, model: model)

  total_cost = records.sum { |r| r.cost_usd || 0 }
  total_prompt = records.sum { |r| r.prompt_tokens || 0 }
  total_completion = records.sum { |r| r.completion_tokens || 0 }
  total_cache_read = records.sum { |r| r.cache_read_tokens || 0 }
  total_cache_write = records.sum { |r| r.cache_write_tokens || 0 }

  by_model = records.group_by(&:model).transform_values do |rs|
    {
      cost: rs.sum { |r| r.cost_usd || 0 },
      prompt_tokens: rs.sum { |r| r.prompt_tokens || 0 },
      completion_tokens: rs.sum { |r| r.completion_tokens || 0 },
      requests: rs.size
    }
  end

  by_day = records.group_by { |r| r.timestamp.strftime("%Y-%m-%d") }.transform_values do |rs|
    rs.sum { |r| r.cost_usd || 0 }
  end

  {
    period: period,
    from: from_time&.iso8601,
    to: Time.now.iso8601,
    total_cost: total_cost.round(6),
    total_tokens: total_prompt + total_completion,
    prompt_tokens: total_prompt,
    completion_tokens: total_completion,
    cache_read_tokens: total_cache_read,
    cache_write_tokens: total_cache_write,
    by_model: by_model,
    by_day: by_day,
    record_count: records.size
  }
end