1use crate::arkuse::api::Usage;
17use crate::arkuse::ark::Catalog;
18use crate::arkuse::db::Row;
19
20pub const FIVE_HOUR_SECS: i64 = 5 * 3600;
21pub const DAY_SECS: i64 = 86_400;
22pub const WEEKLY_SECS: i64 = 7 * 86_400;
23pub const LOOKBACK_SECS: i64 = 120 * 86_400;
25
26#[derive(Debug, Clone, Default)]
27pub struct Totals {
28 pub afp: f64,
31 pub requests: u64,
32 pub input: u64,
33 pub output: u64,
34 pub cache_read: u64,
35 pub cache_write: u64,
36 pub oldest_ms: Option<i64>,
39}
40
41impl Totals {
42 pub fn add(&mut self, row: &Row, afp: Option<f64>) {
46 self.afp += afp.unwrap_or(0.0);
47 self.requests += 1;
48 self.input += row.input;
49 self.output += row.output;
50 self.cache_read += row.cache_read;
51 self.cache_write += row.cache_write;
52 self.oldest_ms = Some(self.oldest_ms.map_or(row.at_ms, |at| at.min(row.at_ms)));
53 }
54
55 pub fn tokens(&self) -> u64 {
56 self.input + self.output + self.cache_read
57 }
58}
59
60#[derive(Debug, Clone)]
61pub struct ModelUsage {
62 pub id: String,
63 pub provider: String,
64 pub coef: f64,
66 pub month: Totals,
67 pub five_hour: Totals,
68 pub weekly: Totals,
69}
70
71#[derive(Debug, Clone)]
72pub struct Report {
73 pub period_label: String,
74 pub now_ms: i64,
75 pub since_ms: i64,
76 pub period_end_ms: Option<i64>,
77 pub month_inferred: bool,
78 pub account: Option<Usage>,
80 pub account_error: Option<String>,
83 pub tier: String,
86 pub profile: Option<String>,
88 pub offset_secs: i64,
91 pub five_hour: Totals,
92 pub weekly: Totals,
93 pub month: Totals,
94 pub daily: Option<Totals>,
97 pub models: Vec<ModelUsage>,
99}
100
101impl Report {
102 pub fn afp_per_request(&self) -> Option<f64> {
106 let account = self.account.as_ref()?;
107 let requests = self.five_hour.requests;
108 (requests > 0).then(|| account.five_hour.used / requests as f64)
109 }
110
111 pub fn reconcile(&self) -> Option<f64> {
116 let account = self.account.as_ref()?;
117 if account.five_hour.used <= 0.0 || self.five_hour.afp <= 0.0 {
118 return None;
119 }
120 Some((self.five_hour.afp - account.five_hour.used) / account.five_hour.used * 100.0)
121 }
122
123 pub fn burn_per_day(&self) -> Option<f64> {
126 let account = self.account.as_ref()?;
127 (account.five_hour.used > 0.0).then(|| account.five_hour.used / 5.0 * 24.0)
128 }
129
130 pub fn window_quota(&self, catalog: &Catalog, share: f64) -> Option<f64> {
135 catalog.plan(&self.tier).map(|plan| plan.afp * share)
136 }
137
138 pub fn rolling_reset(&self, totals: &Totals, dur_secs: i64) -> Option<i64> {
142 totals.oldest_ms.map(|at| at + dur_secs * 1000)
143 }
144}
145
146fn day_of_month(epoch_secs: i64) -> u32 {
149 civil(epoch_secs).2 as u32
150}
151
152pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
153 let y = if m <= 2 { y - 1 } else { y };
154 let era = y.div_euclid(400);
155 let yoe = y - era * 400;
156 let mp = if m > 2 { m - 3 } else { m + 9 };
157 let doy = (153 * mp + 2) / 5 + d - 1;
158 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
159 era * 146_097 + doe - 719_468
160}
161
162fn civil(epoch_secs: i64) -> (i64, i64, i64) {
163 let days = epoch_secs.div_euclid(DAY_SECS);
164 let z = days + 719_468;
165 let era = z.div_euclid(146_097);
166 let doe = z.rem_euclid(146_097);
167 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
168 let y = yoe + era * 400;
169 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
170 let mp = (5 * doy + 2) / 153;
171 let d = doy - (153 * mp + 2) / 5 + 1;
172 let m = if mp < 10 { mp + 3 } else { mp - 9 };
173 (if m <= 2 { y + 1 } else { y }, m, d)
174}
175
176pub fn now_ms() -> i64 {
178 std::time::SystemTime::now()
179 .duration_since(std::time::UNIX_EPOCH)
180 .map(|d| d.as_millis() as i64)
181 .unwrap_or(0)
182}
183
184pub fn calendar_month_start(now_ms: i64) -> i64 {
187 let (year, month, _) = civil(now_ms / 1000);
188 days_from_civil(year, month, 1) * 86_400_000
189}
190
191pub fn next_month(ms: i64) -> i64 {
195 let (year, month, day) = civil(ms / 1000);
196 let (ny, nm) = if month == 12 {
197 (year + 1, 1)
198 } else {
199 (year, month + 1)
200 };
201 days_from_civil(ny, nm, day.min(28)) * 86_400_000
202}
203
204pub fn month_start_before(reset_ms: i64, offset_secs: i64) -> i64 {
212 let local = reset_ms + offset_secs * 1000;
213 let (year, month, day) = civil(local.div_euclid(1000));
214 let (py, pm) = if month == 1 {
215 (year - 1, 12)
216 } else {
217 (year, month - 1)
218 };
219 days_from_civil(py, pm, day.min(28)) * 86_400_000 - offset_secs * 1000
220}
221
222pub fn before_day_end(at_ms: i64, day: &str) -> bool {
225 let mut parts = day.split('-');
226 let (Some(y), Some(m), Some(d)) = (parts.next(), parts.next(), parts.next()) else {
227 return false;
228 };
229 let (Ok(y), Ok(m), Ok(d)) = (y.parse::<i64>(), m.parse::<i64>(), d.parse::<i64>()) else {
230 return false;
231 };
232 let end = (days_from_civil(y, m, d) + 1) * 86_400_000;
233 at_ms < end
234}
235
236pub fn month_start(rows: &[Row], now_ms: i64) -> (i64, bool) {
239 let now_secs = now_ms / 1000;
240 let (year, month, _) = civil(now_secs);
241 if let Some(ms) = rows.iter().map(|r| r.at_ms).min() {
242 let wanted = day_of_month(ms / 1000).min(28) as i64;
243 let candidate = days_from_civil(year, month, wanted) * DAY_SECS;
244 if candidate <= now_secs {
245 return (candidate * 1000, true);
246 }
247 let (py, pm) = if month == 1 {
248 (year - 1, 12)
249 } else {
250 (year, month - 1)
251 };
252 return (days_from_civil(py, pm, wanted) * DAY_SECS * 1000, true);
253 }
254 (days_from_civil(year, month, 1) * DAY_SECS * 1000, false)
255}
256
257pub fn build(
259 rows: &[Row],
260 catalog: &Catalog,
261 plan_id: &str,
262 now_ms: i64,
263 since_override: Option<i64>,
264 account: Option<&Usage>,
265) -> Report {
266 let (inferred_start, month_inferred) = month_start(rows, now_ms);
267 let since_ms = since_override.unwrap_or(inferred_start);
268 let (five_start, five_end) = match account.and_then(|a| a.five_hour.reset_ms()) {
273 Some(reset) => (reset - FIVE_HOUR_SECS * 1000, reset),
274 None => (now_ms - FIVE_HOUR_SECS * 1000, i64::MAX),
275 };
276 let (week_start, week_end) = match account.and_then(|a| a.weekly.reset_ms()) {
277 Some(reset) => (reset - WEEKLY_SECS * 1000, reset),
278 None => (now_ms - WEEKLY_SECS * 1000, i64::MAX),
279 };
280 let day_bounds = account
283 .and_then(|a| a.daily.as_ref())
284 .and_then(|m| m.reset_ms())
285 .map(|reset| (reset - DAY_SECS * 1000, reset));
286
287 let mut report = Report {
288 period_label: "calendar month".into(),
289 now_ms,
290 since_ms,
291 period_end_ms: None,
292 month_inferred: since_override.is_none() && month_inferred,
293 account: None,
294 account_error: None,
295 tier: plan_id.to_string(),
296 profile: account.map(|a| a.profile.clone()),
297 offset_secs: account.map_or(0, |a| a.monthly.offset_secs()),
298 five_hour: Totals::default(),
299 weekly: Totals::default(),
300 month: Totals::default(),
301 daily: day_bounds.map(|_| Totals::default()),
302 models: Vec::new(),
303 };
304 let mut by_model: std::collections::BTreeMap<String, ModelUsage> = Default::default();
305
306 for row in rows {
307 let in_month = row.at_ms >= since_ms;
308 let in_week = row.at_ms >= week_start && row.at_ms < week_end;
309 let in_five = row.at_ms >= five_start && row.at_ms < five_end;
310 let in_day = day_bounds.is_some_and(|(start, end)| row.at_ms >= start && row.at_ms < end);
311 if !in_month && !in_week && !in_five && !in_day {
312 continue;
313 }
314 let afp = catalog.afp(&row.model, row.at_ms, row.input, row.cache_read, row.output);
315 if in_month {
316 report.month.add(row, afp);
317 }
318 if in_day {
319 report
320 .daily
321 .get_or_insert_with(Totals::default)
322 .add(row, afp);
323 }
324 if in_week {
325 report.weekly.add(row, afp);
326 }
327 if in_five {
328 report.five_hour.add(row, afp);
329 }
330 let coef = catalog
331 .models
332 .iter()
333 .find(|m| m.id == row.model)
334 .map(|m| crate::arkuse::ark::effective_coef(m, row.at_ms))
335 .unwrap_or(0.0);
336 let entry = by_model
337 .entry(row.model.clone())
338 .or_insert_with(|| ModelUsage {
339 id: row.model.clone(),
340 provider: row.provider.clone(),
341 coef,
342 month: Totals::default(),
343 five_hour: Totals::default(),
344 weekly: Totals::default(),
345 });
346 if in_month {
347 entry.month.add(row, afp);
348 }
349 if in_week {
350 entry.weekly.add(row, afp);
351 }
352 if in_five {
353 entry.five_hour.add(row, afp);
354 }
355 }
356
357 report.models = by_model.into_values().collect();
358 report.models.sort_by(|a, b| {
359 b.month
360 .afp
361 .partial_cmp(&a.month.afp)
362 .unwrap_or(std::cmp::Ordering::Equal)
363 .then_with(|| a.id.cmp(&b.id))
364 });
365 report
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371 use crate::arkuse::db::Row;
372
373 fn row(at_s: i64, model: &str) -> Row {
374 Row {
375 at_ms: at_s * 1000,
376 provider: "agent-plan".into(),
377 model: model.into(),
378 input: 10_000,
379 ..Default::default()
380 }
381 }
382
383 fn meter(percent: f64, used: f64, resets_at: &str) -> crate::arkuse::api::Meter {
384 crate::arkuse::api::Meter::from_parts("ok", percent, used, 0.0, Some(resets_at), None)
385 }
386
387 #[test]
388 fn civil_helpers_round_trip() {
389 let secs = days_from_civil(2026, 9, 27) * 86_400;
390 assert_eq!(civil(secs), (2026, 9, 27));
391 assert_eq!(day_of_month(secs), 27);
392 }
393
394 #[test]
398 fn month_start_follows_the_servers_anniversary_and_offset() {
399 let reset = (days_from_civil(2026, 11, 19) * 86_400 + 23 * 3600 + 59 * 60 + 59) * 1000
401 - 8 * 3600 * 1000;
402 let start = month_start_before(reset, 8 * 3600);
403 let local = (start + 8 * 3600 * 1000) / 1000;
404 assert_eq!(civil(local), (2026, 10, 19), "00:00 on the 19th, +08:00");
405 assert_eq!(local.rem_euclid(DAY_SECS), 0);
406 }
407
408 #[test]
409 fn promo_dates_end_at_the_days_close() {
410 let day = days_from_civil(2026, 12, 30) * 86_400_000;
411 assert!(before_day_end(day + 3_600_000, "2026-12-30"));
412 assert!(!before_day_end(day + 86_400_000, "2026-12-30"));
413 }
414
415 #[test]
416 fn the_meters_bounds_cut_the_windows_when_they_answered() {
417 let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600;
419 let account = crate::arkuse::api::Usage {
420 five_hour: meter(6.0, 600.0, "2026-10-19T23:00:00+08:00"),
422 daily: None,
423 weekly: meter(3.0, 1_050.0, "2026-10-26T00:00:00+08:00"),
425 monthly: meter(51.0, 51_000.0, "2026-11-19T23:59:59+08:00"),
426 tier: Some("medium".into()),
427 profile: "agent-plan_cn-beijing_medium".into(),
428 };
429 let rows = vec![
430 row(now - 8 * 86_400, "deepseek-v4.1-flash"),
432 row(now - 6 * 3600, "deepseek-v4.1-flash"),
434 row(now - 60, "deepseek-v4.1-flash"),
436 ];
437 let catalog = crate::arkuse::ark::catalog();
438 let month_start = days_from_civil(2026, 10, 1) * 86_400;
439 let report = build(
440 &rows,
441 &catalog,
442 "medium",
443 now * 1000,
444 Some(month_start * 1000),
445 Some(&account),
446 );
447 assert_eq!(report.five_hour.requests, 1, "only the in-block row");
448 assert_eq!(report.weekly.requests, 2, "the block plus six hours back");
449 assert_eq!(report.month.requests, 3, "all of them inside October");
450 assert!(report.five_hour.afp > 0.0);
451 }
452
453 #[test]
454 fn a_rolling_window_borrows_its_boundary_from_its_oldest_row() {
455 let now = days_from_civil(2026, 10, 19) * 86_400;
459 let rows = vec![
460 row(now - 4 * 3600, "deepseek-v4.1-flash"),
461 row(now - 60, "deepseek-v4.1-flash"),
462 ];
463 let catalog = crate::arkuse::ark::catalog();
464 let report = build(&rows, &catalog, "medium", now * 1000, None, None);
465 assert_eq!(report.five_hour.requests, 2);
466 assert_eq!(report.five_hour.oldest_ms, Some((now - 4 * 3600) * 1000));
467 assert_eq!(
468 report.rolling_reset(&report.five_hour, FIVE_HOUR_SECS),
469 Some((now + 3600) * 1000),
470 "four hours of the block already spent"
471 );
472 assert_eq!(
473 report.window_quota(&catalog, catalog.windows.five_hour),
474 Some(10_000.0),
475 "medium's published 5-hour split"
476 );
477 assert_eq!(
478 report.rolling_reset(&Totals::default(), FIVE_HOUR_SECS),
479 None
480 );
481 }
482
483 #[test]
484 fn a_daily_meter_gets_its_own_cut_and_a_text_plan_has_none() {
485 let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600;
487 let account = crate::arkuse::api::Usage {
488 five_hour: meter(6.0, 600.0, "2026-10-19T23:00:00+08:00"),
489 daily: Some(meter(1.0, 100.0, "2026-10-19T15:00:00+08:00")),
491 weekly: meter(3.0, 1_050.0, "2026-10-26T00:00:00+08:00"),
492 monthly: meter(51.0, 51_000.0, "2026-11-19T23:59:59+08:00"),
493 tier: Some("medium".into()),
494 profile: "agent-plan_cn-beijing_medium".into(),
495 };
496 let rows = vec![
497 row(now - 10 * 3600, "deepseek-v4.1-flash"), row(now - 3600, "deepseek-v4.1-flash"), ];
500 let catalog = crate::arkuse::ark::catalog();
501 let report = build(&rows, &catalog, "medium", now * 1000, None, Some(&account));
502 assert_eq!(report.daily.expect("media plan exposes a day").requests, 1);
503 let mut text_only = account;
505 text_only.daily = None;
506 let report = build(
507 &rows,
508 &catalog,
509 "medium",
510 now * 1000,
511 None,
512 Some(&text_only),
513 );
514 assert!(report.daily.is_none());
515 }
516
517 #[test]
518 fn models_sort_by_month_afp() {
519 let now = days_from_civil(2026, 9, 27) * 86_400;
520 let rows = vec![
521 row(now - 60, "glm-5.3-flash"),
522 row(now - 60, "deepseek-v4.1-flash"),
523 ];
524 let catalog = crate::arkuse::ark::catalog();
525 let report = build(&rows, &catalog, "medium", now * 1000, None, None);
526 assert_eq!(report.models[0].id, "deepseek-v4.1-flash", "2.5 > 0.5");
527 }
528
529 #[test]
530 fn an_unknown_model_counts_a_request_but_no_afp() {
531 let now = days_from_civil(2026, 9, 27) * 86_400;
532 let rows = vec![row(now - 60, "not-a-model")];
533 let catalog = crate::arkuse::ark::catalog();
534 let report = build(&rows, &catalog, "medium", now * 1000, None, None);
535 assert_eq!(report.month.requests, 1);
536 assert_eq!(report.month.afp, 0.0);
537 }
538}