-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.rs
More file actions
375 lines (346 loc) · 13.2 KB
/
Copy pathstore.rs
File metadata and controls
375 lines (346 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
74
75
76
77
78
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
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
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
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
218
219
220
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::path::Path;
use std::sync::{Arc, Mutex};
use rusqlite::{params, Connection};
use crate::usage::models::{
CostEntry, ModelBreakdownEntry, ProviderId, TrendData, TrendPoint, UsageSnapshot,
};
#[derive(Clone)]
pub struct UsageStore {
conn: Arc<Mutex<Connection>>,
}
impl UsageStore {
pub fn open(path: &Path) -> Result<Self, String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let conn = Connection::open(path).map_err(|e| e.to_string())?;
let store = Self {
conn: Arc::new(Mutex::new(conn)),
};
store.init_schema()?;
Ok(store)
}
fn init_schema(&self) -> Result<(), String> {
let conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS snapshots (
provider TEXT PRIMARY KEY,
payload TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS cost_entries (
day TEXT NOT NULL,
provider TEXT NOT NULL,
model TEXT NOT NULL,
input_tokens INTEGER NOT NULL,
output_tokens INTEGER NOT NULL,
cache_read_tokens INTEGER NOT NULL,
cache_write_tokens INTEGER NOT NULL,
estimated_cost_usd REAL NOT NULL,
PRIMARY KEY(day, provider, model)
);
",
)
.map_err(|e| e.to_string())?;
Ok(())
}
pub fn save_snapshot(&self, snapshot: &UsageSnapshot) -> Result<(), String> {
let payload = serde_json::to_string(snapshot).map_err(|e| e.to_string())?;
let fetched = snapshot.fetched_at.timestamp_millis();
let conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
conn.execute(
"INSERT INTO snapshots(provider, payload, fetched_at) VALUES (?1, ?2, ?3)
ON CONFLICT(provider) DO UPDATE SET payload=excluded.payload, fetched_at=excluded.fetched_at",
params![snapshot.provider.as_str(), payload, fetched],
)
.map_err(|e| e.to_string())?;
Ok(())
}
pub fn get_snapshot(&self, provider: ProviderId) -> Result<Option<UsageSnapshot>, String> {
let conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
let mut stmt = conn
.prepare("SELECT payload FROM snapshots WHERE provider = ?1")
.map_err(|e| e.to_string())?;
let mut rows = stmt
.query(params![provider.as_str()])
.map_err(|e| e.to_string())?;
if let Some(row) = rows.next().map_err(|e| e.to_string())? {
let payload: String = row.get(0).map_err(|e| e.to_string())?;
let snapshot: UsageSnapshot =
serde_json::from_str(&payload).map_err(|e| e.to_string())?;
return Ok(Some(snapshot));
}
Ok(None)
}
pub fn get_all_snapshots(&self) -> Result<Vec<UsageSnapshot>, String> {
let conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
let mut stmt = conn
.prepare("SELECT payload FROM snapshots")
.map_err(|e| e.to_string())?;
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
let mut out = Vec::new();
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
let payload: String = row.get(0).map_err(|e| e.to_string())?;
if let Ok(snapshot) = serde_json::from_str::<UsageSnapshot>(&payload) {
out.push(snapshot);
}
}
Ok(out)
}
pub fn save_cost_entries(&self, entries: &[CostEntry]) -> Result<(), String> {
let mut conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
let tx = conn.transaction().map_err(|e| e.to_string())?;
for entry in entries {
tx.execute(
"INSERT INTO cost_entries(day, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, estimated_cost_usd)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(day, provider, model) DO UPDATE SET
input_tokens=excluded.input_tokens,
output_tokens=excluded.output_tokens,
cache_read_tokens=excluded.cache_read_tokens,
cache_write_tokens=excluded.cache_write_tokens,
estimated_cost_usd=excluded.estimated_cost_usd",
params![
entry.date,
entry.provider.as_str(),
entry.model,
entry.input_tokens,
entry.output_tokens,
entry.cache_read_tokens,
entry.cache_write_tokens,
entry.estimated_cost_usd
],
)
.map_err(|e| e.to_string())?;
}
tx.commit().map_err(|e| e.to_string())?;
Ok(())
}
pub fn get_cost_history(
&self,
provider: ProviderId,
days: u32,
) -> Result<Vec<CostEntry>, String> {
let conn = self
.conn
.lock()
.map_err(|_| "store lock poisoned".to_string())?;
let mut stmt = conn
.prepare(
"SELECT day, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, estimated_cost_usd
FROM cost_entries
WHERE provider = ?1
AND day IN (
SELECT day
FROM (
SELECT DISTINCT day
FROM cost_entries
WHERE provider = ?1
ORDER BY day DESC
LIMIT ?2
)
)
ORDER BY day DESC, model ASC",
)
.map_err(|e| e.to_string())?;
let mut rows = stmt
.query(params![provider.as_str(), days.max(1)])
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
out.push(CostEntry {
date: row.get(0).map_err(|e| e.to_string())?,
provider,
model: row.get(1).map_err(|e| e.to_string())?,
input_tokens: row.get(2).map_err(|e| e.to_string())?,
output_tokens: row.get(3).map_err(|e| e.to_string())?,
cache_read_tokens: row.get(4).map_err(|e| e.to_string())?,
cache_write_tokens: row.get(5).map_err(|e| e.to_string())?,
estimated_cost_usd: row.get(6).map_err(|e| e.to_string())?,
});
}
out.reverse();
Ok(out)
}
pub fn get_usage_trends(&self, provider: ProviderId, days: u32) -> Result<TrendData, String> {
let entries = self.get_cost_history(provider, days)?;
let mut by_day = std::collections::BTreeMap::<String, TrendPoint>::new();
let mut total_cost = 0.0f64;
let mut total_tokens = 0u64;
for entry in entries {
let tokens = entry
.input_tokens
.saturating_add(entry.output_tokens)
.saturating_add(entry.cache_read_tokens)
.saturating_add(entry.cache_write_tokens);
total_cost += entry.estimated_cost_usd;
total_tokens = total_tokens.saturating_add(tokens);
let point = by_day
.entry(entry.date.clone())
.or_insert_with(|| TrendPoint {
date: entry.date,
cost_usd: 0.0,
total_tokens: 0,
});
point.cost_usd += entry.estimated_cost_usd;
point.total_tokens = point.total_tokens.saturating_add(tokens);
}
let points = by_day.into_values().collect();
Ok(TrendData {
provider,
days,
points,
total_cost_usd: total_cost,
total_tokens,
})
}
pub fn get_model_breakdown(
&self,
provider: ProviderId,
days: u32,
) -> Result<Vec<ModelBreakdownEntry>, String> {
let effective_days = days.max(1);
let entries = self.get_cost_history(provider, effective_days)?;
let mut by_model = std::collections::BTreeMap::<String, ModelBreakdownEntry>::new();
for entry in entries {
let total_tokens = entry
.input_tokens
.saturating_add(entry.output_tokens)
.saturating_add(entry.cache_read_tokens)
.saturating_add(entry.cache_write_tokens);
let slot = by_model
.entry(entry.model.clone())
.or_insert_with(|| ModelBreakdownEntry {
provider,
model: entry.model.clone(),
days: effective_days,
input_tokens: 0,
output_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
total_tokens: 0,
estimated_cost_usd: 0.0,
});
slot.input_tokens = slot.input_tokens.saturating_add(entry.input_tokens);
slot.output_tokens = slot.output_tokens.saturating_add(entry.output_tokens);
slot.cache_read_tokens = slot
.cache_read_tokens
.saturating_add(entry.cache_read_tokens);
slot.cache_write_tokens = slot
.cache_write_tokens
.saturating_add(entry.cache_write_tokens);
slot.total_tokens = slot.total_tokens.saturating_add(total_tokens);
slot.estimated_cost_usd += entry.estimated_cost_usd;
}
let mut out: Vec<_> = by_model.into_values().collect();
out.sort_by(|a, b| {
b.estimated_cost_usd
.partial_cmp(&a.estimated_cost_usd)
.unwrap_or(std::cmp::Ordering::Equal)
.then(b.total_tokens.cmp(&a.total_tokens))
.then(a.model.cmp(&b.model))
});
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_store(name: &str) -> UsageStore {
let path = std::env::temp_dir().join(format!(
"otm-store-{name}-{}.db",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
));
UsageStore::open(&path).expect("open temp store")
}
fn sample_entry(
day: &str,
model: &str,
input_tokens: u64,
output_tokens: u64,
cost: f64,
) -> CostEntry {
CostEntry {
date: day.to_string(),
provider: ProviderId::Codex,
model: model.to_string(),
input_tokens,
output_tokens,
cache_read_tokens: 0,
cache_write_tokens: 0,
estimated_cost_usd: cost,
}
}
#[test]
fn cost_history_limits_by_distinct_days_not_rows() {
let store = temp_store("distinct-days");
let entries = vec![
sample_entry("2026-03-01", "gpt-5", 10, 5, 1.0),
sample_entry("2026-03-01", "gpt-5-mini", 4, 2, 0.2),
sample_entry("2026-03-02", "gpt-5", 8, 4, 0.8),
];
store
.save_cost_entries(&entries)
.expect("save cost entries");
let history = store
.get_cost_history(ProviderId::Codex, 2)
.expect("load cost history");
assert_eq!(history.len(), 3);
}
#[test]
fn model_breakdown_aggregates_rows_per_model() {
let store = temp_store("breakdown");
let entries = vec![
sample_entry("2026-03-01", "gpt-5", 10, 5, 1.0),
sample_entry("2026-03-02", "gpt-5", 12, 6, 1.2),
sample_entry("2026-03-02", "gpt-5-mini", 4, 2, 0.2),
];
store
.save_cost_entries(&entries)
.expect("save cost entries");
let breakdown = store
.get_model_breakdown(ProviderId::Codex, 30)
.expect("load model breakdown");
assert_eq!(breakdown.len(), 2);
assert_eq!(breakdown[0].model, "gpt-5");
assert_eq!(breakdown[0].input_tokens, 22);
assert_eq!(breakdown[0].output_tokens, 11);
}
#[test]
fn usage_trends_aggregate_multiple_models_into_one_day() {
let store = temp_store("trends");
let entries = vec![
sample_entry("2026-03-01", "gpt-5", 10, 5, 1.0),
sample_entry("2026-03-01", "gpt-5-mini", 4, 2, 0.2),
];
store
.save_cost_entries(&entries)
.expect("save cost entries");
let trend = store
.get_usage_trends(ProviderId::Codex, 30)
.expect("load usage trends");
assert_eq!(trend.points.len(), 1);
assert_eq!(trend.points[0].date, "2026-03-01");
assert_eq!(trend.points[0].total_tokens, 21);
assert!((trend.points[0].cost_usd - 1.2).abs() < f64::EPSILON);
}
}