use crate::usage_log;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, ErrorKind};
use std::path::Path;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Group {
pub cost_usd: f64,
pub unpriced: u64,
pub lines: u64,
pub runs: u64,
pub input: u64,
pub cached: u64,
pub output: u64,
pub thinking: u64,
}
impl Group {
fn add(&mut self, entry: &usage_log::Entry) {
match entry.cost_usd {
Some(cost) => self.cost_usd += cost,
None => self.unpriced += 1,
}
self.lines += 1;
if is_run(entry) {
self.runs += 1;
}
self.input += entry.input;
self.cached += entry.cached;
self.output += entry.output;
self.thinking += entry.thinking;
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DayRow {
pub day: String,
#[serde(flatten)]
pub group: Group,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KindRow {
pub kind: String,
#[serde(flatten)]
pub group: Group,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceRow {
pub surface: Option<String>,
pub name: Option<String>,
pub last_ts: u64,
#[serde(flatten)]
pub group: Group,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RepoRow {
pub repo: String,
#[serde(flatten)]
pub group: Group,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelRow {
pub model: String,
#[serde(flatten)]
pub group: Group,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Report {
pub generated_at: u64,
pub since: Option<u64>,
pub log: String,
pub log_exists: bool,
pub unreadable_lines: u64,
pub totals: Group,
pub by_day: Vec<DayRow>,
pub by_kind: Vec<KindRow>,
pub by_surface: Vec<SurfaceRow>,
pub by_repo: Vec<RepoRow>,
pub by_model: Vec<ModelRow>,
}
struct SurfaceAcc {
group: Group,
last_ts: u64,
latest_name: Option<(u64, String)>,
}
pub fn kind_of(entry: &usage_log::Entry) -> &'static str {
if entry.outcome == "model_review" {
"review"
} else if entry.research {
"research"
} else if entry.dispatch.is_some() {
"implementer"
} else {
"conversation"
}
}
fn is_run(entry: &usage_log::Entry) -> bool {
entry.dispatch.is_some() && entry.outcome != "turn" && entry.outcome != "model_review"
}
pub fn utc_day(ts: u64) -> String {
let days = (ts / 86_400) as i64;
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if m <= 2 { y + 1 } else { y };
format!("{year:04}-{m:02}-{d:02}")
}
fn cmp_surface_key(a: Option<&str>, b: Option<&str>) -> Ordering {
match (a, b) {
(Some(a), Some(b)) => a.cmp(b),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
}
pub fn build(log: &Path, since: Option<u64>, now: u64) -> Result<Report, String> {
let log_str = log.to_string_lossy().into_owned();
let file = match File::open(log) {
Ok(file) => file,
Err(err) if err.kind() == ErrorKind::NotFound => {
return Ok(Report {
generated_at: now,
since,
log: log_str,
log_exists: false,
unreadable_lines: 0,
totals: Group::default(),
by_day: Vec::new(),
by_kind: Vec::new(),
by_surface: Vec::new(),
by_repo: Vec::new(),
by_model: Vec::new(),
});
}
Err(err) => {
return Err(format!("failed to open {}: {err}", log.display()));
}
};
let reader = BufReader::new(file);
let mut unreadable_lines = 0u64;
let mut totals = Group::default();
let mut day_map: HashMap<String, Group> = HashMap::new();
let mut kind_map: HashMap<&'static str, Group> = HashMap::new();
let mut surface_map: HashMap<Option<String>, SurfaceAcc> = HashMap::new();
let mut repo_map: HashMap<String, Group> = HashMap::new();
let mut model_map: HashMap<String, Group> = HashMap::new();
for line_res in reader.lines() {
let line = line_res.map_err(|err| format!("failed to read {}: {err}", log.display()))?;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let Ok(entry) = serde_json::from_str::<usage_log::Entry>(trimmed) else {
unreadable_lines += 1;
continue;
};
if let Some(min_ts) = since {
if entry.ts < min_ts {
continue;
}
}
totals.add(&entry);
day_map.entry(utc_day(entry.ts)).or_default().add(&entry);
kind_map.entry(kind_of(&entry)).or_default().add(&entry);
let surface_acc = surface_map
.entry(entry.surface.clone())
.or_insert_with(|| SurfaceAcc {
group: Group::default(),
last_ts: entry.ts,
latest_name: None,
});
surface_acc.group.add(&entry);
if entry.ts > surface_acc.last_ts {
surface_acc.last_ts = entry.ts;
}
if entry.surface.is_some() {
if let Some(name) = entry.surface_name.as_deref() {
let replace = match &surface_acc.latest_name {
None => true,
Some((prev_ts, _)) => entry.ts >= *prev_ts,
};
if replace {
surface_acc.latest_name = Some((entry.ts, name.to_string()));
}
}
}
repo_map.entry(entry.repo.clone()).or_default().add(&entry);
model_map
.entry(entry.model.clone())
.or_default()
.add(&entry);
}
let mut by_day: Vec<DayRow> = day_map
.into_iter()
.map(|(day, group)| DayRow { day, group })
.collect();
by_day.sort_by(|a, b| a.day.cmp(&b.day));
let mut by_kind: Vec<KindRow> = kind_map
.into_iter()
.map(|(kind, group)| KindRow {
kind: kind.to_string(),
group,
})
.collect();
by_kind.sort_by(|a, b| {
b.group
.cost_usd
.total_cmp(&a.group.cost_usd)
.then_with(|| a.kind.cmp(&b.kind))
});
let mut by_surface: Vec<SurfaceRow> = surface_map
.into_iter()
.map(|(surface, acc)| SurfaceRow {
surface,
name: acc.latest_name.map(|(_, name)| name),
last_ts: acc.last_ts,
group: acc.group,
})
.collect();
by_surface.sort_by(|a, b| {
b.group
.cost_usd
.total_cmp(&a.group.cost_usd)
.then_with(|| cmp_surface_key(a.surface.as_deref(), b.surface.as_deref()))
});
let mut by_repo: Vec<RepoRow> = repo_map
.into_iter()
.map(|(repo, group)| RepoRow { repo, group })
.collect();
by_repo.sort_by(|a, b| {
b.group
.cost_usd
.total_cmp(&a.group.cost_usd)
.then_with(|| a.repo.cmp(&b.repo))
});
let mut by_model: Vec<ModelRow> = model_map
.into_iter()
.map(|(model, group)| ModelRow { model, group })
.collect();
by_model.sort_by(|a, b| {
b.group
.cost_usd
.total_cmp(&a.group.cost_usd)
.then_with(|| a.model.cmp(&b.model))
});
Ok(Report {
generated_at: now,
since,
log: log_str,
log_exists: true,
unreadable_lines,
totals,
by_day,
by_kind,
by_surface,
by_repo,
by_model,
})
}