Skip to main content

simulator_api/
usage.rs

1//! Usage and billing for an API key: the bodies of `GET /usage` and `GET /usage/sessions`.
2//!
3//! Times are UTC, durations are wall time in milliseconds, and prices are US dollars. A session's
4//! compute counts toward the day it ended.
5
6use chrono::{DateTime, Duration, Utc};
7use serde::{Deserialize, Serialize};
8
9use crate::SessionId;
10
11/// Response body of `GET /usage`.
12///
13/// `since` is the start of the UTC day it falls in, so it may precede the
14/// requested value.
15#[derive(Debug, Serialize, Deserialize)]
16pub struct UsageReport {
17    #[expect(missing_docs, reason = "self-explanatory")]
18    pub api_key_name: String,
19    /// Start of the window, exclusive.
20    pub since: DateTime<Utc>,
21    /// End of the window, inclusive.
22    pub until: DateTime<Utc>,
23    sessions: SessionCounts,
24    compute: ComputeTotals,
25    /// One bucket per UTC day in `(since, until]`, ordered and gapless: an idle
26    /// day is present with zero counts, and a session ending on a midnight
27    /// belongs to the bucket that midnight closes. The series sums to
28    /// `sessions` and `compute`; it is empty only from a server predating it.
29    #[serde(default)]
30    pub daily: Vec<UsageBucket>,
31    /// Present only for keys with the `build_bundle` feature.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub bundle_builds: Option<BundleBuildUsage>,
34    /// The rates to price the totals at; see [`UsagePricing::cost`].
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub pricing: Option<UsagePricing>,
37}
38
39impl UsageReport {
40    /// Folds the totals from `daily`, which is the only way to set them.
41    pub fn new(
42        api_key_name: String,
43        since: DateTime<Utc>,
44        until: DateTime<Utc>,
45        daily: Vec<UsageBucket>,
46        bundle_builds: Option<BundleBuildUsage>,
47        pricing: Option<UsagePricing>,
48    ) -> Self {
49        let (sessions, compute) = daily.iter().fold(
50            (SessionCounts::default(), ComputeTotals::default()),
51            |(sessions, compute), bucket| {
52                (
53                    sessions.saturating_add(bucket.sessions),
54                    compute.saturating_add(bucket.compute),
55                )
56            },
57        );
58        Self {
59            api_key_name,
60            since,
61            until,
62            sessions,
63            compute,
64            daily,
65            bundle_builds,
66            pricing,
67        }
68    }
69
70    /// The sum over `daily`, except on a response from a server predating it,
71    /// where it is the total that server reported for the whole window.
72    pub fn sessions(&self) -> SessionCounts {
73        self.sessions
74    }
75
76    /// The sum over `daily`, except on a response from a server predating it,
77    /// where it is the total that server reported for the whole window.
78    pub fn compute(&self) -> ComputeTotals {
79        self.compute
80    }
81}
82
83/// What one whole [`UsageBucket`] spans.
84pub const BUCKET_SPAN: Duration = Duration::days(1);
85
86/// One UTC day of a [`UsageReport`], covering `(start, end]`. `end` is the
87/// following midnight, except for a last bucket that ends at the report's
88/// `until`.
89#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
90pub struct UsageBucket {
91    /// Start of the day, exclusive.
92    pub start: DateTime<Utc>,
93    /// End of the day, inclusive.
94    pub end: DateTime<Utc>,
95    #[expect(missing_docs, reason = "self-explanatory")]
96    pub sessions: SessionCounts,
97    /// Compute used by the sessions that ended that day.
98    pub compute: ComputeTotals,
99}
100
101impl UsageBucket {
102    /// Only the last bucket of a report can be partial.
103    pub fn is_partial(&self) -> bool {
104        self.end.signed_duration_since(self.start) < BUCKET_SPAN
105    }
106
107    /// A day with no activity, kept only to leave the series gapless.
108    pub fn is_empty(&self) -> bool {
109        self.sessions == SessionCounts::default() && self.compute == ComputeTotals::default()
110    }
111}
112
113/// Response body of `GET /usage/sessions`.
114///
115/// Its own endpoint because it is the one part of a usage report that grows
116/// with usage rather than with the window.
117#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
118pub struct SessionUsagePage {
119    /// The window actually served, `since` snapped back to its UTC midnight.
120    /// Pass these back with `next_cursor` so every page resolves the same
121    /// window rather than one drifting with `now`.
122    pub since: DateTime<Utc>,
123    /// End of the window served.
124    pub until: DateTime<Utc>,
125    /// Every session that ended in the window, in no promised order: the pages
126    /// together are the guarantee, not their sequence.
127    pub sessions: Vec<SessionUsage>,
128    /// Opaque continuation token, `None` once the window holds nothing further.
129    /// Pass it back as `cursor` to read the next page.
130    #[serde(default)]
131    pub next_cursor: Option<String>,
132}
133
134/// One session that ran under the key, as its terminal event reported it.
135///
136/// Built from the same fire-and-forget metric points as the rest of the report,
137/// so a point dropped under back-pressure takes its session out of the list.
138#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
139#[expect(missing_docs, reason = "self-explanatory")]
140pub struct SessionUsage {
141    pub session_id: SessionId,
142    /// The name the session was created with, if any.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub session_name: Option<String>,
145    pub started_at: DateTime<Utc>,
146    pub ended_at: DateTime<Utc>,
147    pub executed_slot_count: u64,
148    /// Wall time from start to end, in milliseconds.
149    pub session_duration_ms: u64,
150}
151
152/// The billing rates a report's totals are priced at, in US dollars.
153///
154/// A session is billed per executed slot, unless it averaged more than `max_ms_per_slot` of wall
155/// time per slot; then it is billed per minute of wall time instead.
156#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
157pub struct UsagePricing {
158    /// Dollars per executed slot.
159    pub dollars_per_slot: f64,
160    /// Dollars per minute of wall time, for a session billed by time.
161    pub dollars_per_minute: f64,
162    /// A session slower than this per slot, in milliseconds, is billed by wall time instead.
163    pub max_ms_per_slot: u64,
164}
165
166impl UsagePricing {
167    /// Dollars for `slots` executed over `duration_ms` of wall time.
168    pub fn cost(&self, slots: u64, duration_ms: u64) -> f64 {
169        if slots.saturating_mul(self.max_ms_per_slot) >= duration_ms {
170            slots as f64 * self.dollars_per_slot
171        } else {
172            duration_ms as f64 / 1000.0 / 60.0 * self.dollars_per_minute
173        }
174    }
175}
176
177/// Bundle-build usage for the window.
178#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
179pub struct BundleBuildUsage {
180    /// Custom bundle builds requested in the window.
181    pub requested: u64,
182}
183
184/// Point counts by outcome, not session-deduplicated, so the three need not
185/// balance: a pre-start failure has no `started`, a session moving between
186/// server instances re-emits it. Billing uses the compute totals, which derive only from the
187/// terminal points.
188///
189/// Within a [`UsageBucket`], `started` counts sessions that began that day and
190/// `completed`/`failed` those that ended that day.
191#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
192pub struct SessionCounts {
193    #[expect(missing_docs, reason = "self-explanatory")]
194    pub started: u64,
195    /// Sessions that ended without an error.
196    pub completed: u64,
197    /// Sessions that ended with an error.
198    pub failed: u64,
199}
200
201/// A session contributes wholly to the window — or [`UsageBucket`] — it
202/// ended in, even when it ran across the boundary.
203#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
204pub struct ComputeTotals {
205    #[expect(missing_docs, reason = "self-explanatory")]
206    pub executed_slot_count: u64,
207    /// Session wall time, in milliseconds.
208    pub session_duration_ms: u64,
209}
210
211impl SessionCounts {
212    /// Adds field by field, saturating at `u64::MAX`.
213    #[must_use]
214    pub fn saturating_add(self, other: Self) -> Self {
215        Self {
216            started: self.started.saturating_add(other.started),
217            completed: self.completed.saturating_add(other.completed),
218            failed: self.failed.saturating_add(other.failed),
219        }
220    }
221}
222
223impl ComputeTotals {
224    /// Adds field by field, saturating at `u64::MAX`.
225    #[must_use]
226    pub fn saturating_add(self, other: Self) -> Self {
227        Self {
228            executed_slot_count: self
229                .executed_slot_count
230                .saturating_add(other.executed_slot_count),
231            session_duration_ms: self
232                .session_duration_ms
233                .saturating_add(other.session_duration_ms),
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    fn report(bundle_builds: Option<BundleBuildUsage>) -> UsageReport {
243        UsageReport::new(
244            "k".to_string(),
245            "2026-01-01T00:00:00Z".parse().unwrap(),
246            "2026-01-02T00:00:00Z".parse().unwrap(),
247            vec![UsageBucket {
248                start: "2026-01-01T00:00:00Z".parse().unwrap(),
249                end: "2026-01-02T00:00:00Z".parse().unwrap(),
250                sessions: SessionCounts::default(),
251                compute: ComputeTotals::default(),
252            }],
253            bundle_builds,
254            None,
255        )
256    }
257
258    fn session() -> SessionUsage {
259        SessionUsage {
260            session_id: "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b".parse().unwrap(),
261            session_name: None,
262            started_at: "2026-01-01T09:14:02Z".parse().unwrap(),
263            ended_at: "2026-01-01T09:18:41Z".parse().unwrap(),
264            executed_slot_count: 3_100,
265            session_duration_ms: 279_000,
266        }
267    }
268
269    fn bucket(day: &str, sessions: SessionCounts, compute: ComputeTotals) -> UsageBucket {
270        let start: DateTime<Utc> = format!("2026-01-{day}T00:00:00Z").parse().unwrap();
271        UsageBucket {
272            start,
273            end: start + BUCKET_SPAN,
274            sessions,
275            compute,
276        }
277    }
278
279    #[test]
280    fn new_sums_the_totals_from_the_buckets() {
281        let report = UsageReport::new(
282            "k".to_string(),
283            "2026-01-01T00:00:00Z".parse().unwrap(),
284            "2026-01-03T00:00:00Z".parse().unwrap(),
285            vec![
286                bucket(
287                    "01",
288                    SessionCounts {
289                        started: 1,
290                        completed: 1,
291                        failed: 0,
292                    },
293                    ComputeTotals {
294                        executed_slot_count: 5,
295                        session_duration_ms: 9,
296                    },
297                ),
298                bucket(
299                    "02",
300                    SessionCounts {
301                        started: 2,
302                        completed: 1,
303                        failed: 1,
304                    },
305                    ComputeTotals {
306                        executed_slot_count: 7,
307                        session_duration_ms: 3,
308                    },
309                ),
310            ],
311            None,
312            None,
313        );
314        assert_eq!(
315            report.sessions(),
316            SessionCounts {
317                started: 3,
318                completed: 2,
319                failed: 1
320            }
321        );
322        assert_eq!(
323            report.compute(),
324            ComputeTotals {
325                executed_slot_count: 12,
326                session_duration_ms: 12
327            }
328        );
329    }
330
331    #[test]
332    fn new_totals_of_no_buckets_are_zero() {
333        let report = UsageReport::new(
334            "k".to_string(),
335            "2026-01-01T00:00:00Z".parse().unwrap(),
336            "2026-01-01T00:00:00Z".parse().unwrap(),
337            vec![],
338            None,
339            None,
340        );
341        assert_eq!(report.sessions(), SessionCounts::default());
342        assert_eq!(report.compute(), ComputeTotals::default());
343    }
344
345    #[test]
346    fn usage_report_absent_bundle_builds_round_trips_to_none() {
347        let json = serde_json::to_string(&report(None)).unwrap();
348        assert!(!json.contains("bundle_builds"));
349        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
350        assert_eq!(parsed.bundle_builds, None);
351    }
352
353    #[test]
354    fn usage_report_absent_daily_round_trips_to_empty() {
355        let json = r#"{"api_key_name":"k","since":"2026-01-01T00:00:00Z","until":"2026-01-02T00:00:00Z","sessions":{"started":1,"completed":1,"failed":0},"compute":{"executed_slot_count":5,"session_duration_ms":9}}"#;
356        let parsed: UsageReport = serde_json::from_str(json).unwrap();
357        assert!(parsed.daily.is_empty());
358        // The totals stay on the wire so an empty `daily` does not read as no usage.
359        assert_eq!(
360            parsed.sessions(),
361            SessionCounts {
362                started: 1,
363                completed: 1,
364                failed: 0
365            }
366        );
367        assert_eq!(
368            parsed.compute(),
369            ComputeTotals {
370                executed_slot_count: 5,
371                session_duration_ms: 9
372            }
373        );
374    }
375
376    #[test]
377    fn usage_report_daily_round_trips() {
378        let json = serde_json::to_string(&report(None)).unwrap();
379        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
380        assert_eq!(parsed.daily, report(None).daily);
381    }
382
383    /// The prefixed form is what anything taking a session id accepts.
384    #[test]
385    fn usage_sessions_round_trip_with_prefixed_ids() {
386        let json = serde_json::to_string(&session_page()).unwrap();
387        assert!(json.contains("\"backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b\""));
388        assert!(!json.contains("session_name"));
389        let parsed: SessionUsagePage = serde_json::from_str(&json).unwrap();
390        assert_eq!(parsed, session_page());
391    }
392
393    fn session_page() -> SessionUsagePage {
394        SessionUsagePage {
395            since: "2026-01-01T00:00:00Z".parse().unwrap(),
396            until: "2026-01-02T00:00:00Z".parse().unwrap(),
397            sessions: vec![session()],
398            next_cursor: None,
399        }
400    }
401
402    /// An omitted cursor means "nothing further", not a parse failure.
403    #[test]
404    fn usage_sessions_absent_cursor_round_trips_to_none() {
405        let json =
406            r#"{"since":"2026-01-01T00:00:00Z","until":"2026-01-02T00:00:00Z","sessions":[]}"#;
407        let parsed: SessionUsagePage = serde_json::from_str(json).unwrap();
408        assert_eq!(parsed.next_cursor, None);
409        assert!(parsed.sessions.is_empty());
410    }
411
412    #[test]
413    fn usage_report_present_bundle_builds_round_trips() {
414        let json = serde_json::to_string(&report(Some(BundleBuildUsage { requested: 3 }))).unwrap();
415        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
416        assert_eq!(
417            parsed.bundle_builds,
418            Some(BundleBuildUsage { requested: 3 })
419        );
420    }
421}