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")
OPENCLACKY_MODEL_KINDS =

Preset keys that hold the openclacky model lineup (chat + media sidecars).

%w[models image_models video_models audio_models stt_models video_understanding_models].freeze

Instance Method Summary collapse

Constructor Details

#initialize(billing_dir: nil) ⇒ BillingStore

Returns a new instance of BillingStore.



37
38
39
40
# File 'lib/clacky/billing/billing_store.rb', line 37

def initialize(billing_dir: nil)
  @billing_dir = billing_dir || ENV["CLACKY_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



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/clacky/billing/billing_store.rb', line 45

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



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/clacky/billing/billing_store.rb', line 277

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



297
298
299
300
301
302
303
304
305
306
# File 'lib/clacky/billing/billing_store.rb', line 297

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

#daily_breakdown(days: 30, model: nil, exclude_openclacky: false) ⇒ 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

  • exclude_openclacky (Boolean) (defaults to: false)

    Skip openclacky-provider records

Returns:

  • (Array<Hash>)

    Daily summaries with date and cost



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/clacky/billing/billing_store.rb', line 252

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

  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



221
222
223
224
225
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 221

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

#openclacky_modelsObject

All openclacky model aliases, collected from the provider preset so the list never drifts from providers.rb as models are added or removed.



21
22
23
24
25
26
27
# File 'lib/clacky/billing/billing_store.rb', line 21

def openclacky_models
  @openclacky_models ||= begin
    preset = Clacky::Providers.get("openclacky")
    return [] unless preset
    OPENCLACKY_MODEL_KINDS.flat_map { |kind| preset[kind] || [] }.uniq
  end
end

#openclacky_record?(record) ⇒ Boolean

True when a record belongs to the openclacky provider. New records carry an explicit provider id; legacy records (written before the field existed) are detected by matching the full openclacky model list.

Returns:

  • (Boolean)


32
33
34
35
# File 'lib/clacky/billing/billing_store.rb', line 32

def openclacky_record?(record)
  return true if record.provider == "openclacky"
  openclacky_models.include?(record.model.to_s)
end

#query(from: nil, to: nil, model: nil, session_id: nil, exclude_openclacky: false, 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

  • exclude_openclacky (Boolean) (defaults to: false)

    Skip openclacky-provider records

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

    Maximum number of records to return

Returns:



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/clacky/billing/billing_store.rb', line 66

def query(from: nil, to: nil, model: nil, session_id: nil, exclude_openclacky: false, 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
        next if exclude_openclacky && openclacky_record?(record)

        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



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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/clacky/billing/billing_store.rb', line 148

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, exclude_openclacky: false) ⇒ 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

  • exclude_openclacky (Boolean) (defaults to: false)

    Skip openclacky-provider records

Returns:

  • (Hash)

    Summary with total_cost, total_tokens, by_model, etc.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/clacky/billing/billing_store.rb', line 104

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

  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