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    #[allow(missing_docs)]
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    #[allow(missing_docs)]
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#[allow(missing_docs)]
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    #[allow(missing_docs)]
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    #[allow(missing_docs)]
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    pub fn saturating_add(self, other: Self) -> Self {
214        Self {
215            started: self.started.saturating_add(other.started),
216            completed: self.completed.saturating_add(other.completed),
217            failed: self.failed.saturating_add(other.failed),
218        }
219    }
220}
221
222impl ComputeTotals {
223    /// Adds field by field, saturating at `u64::MAX`.
224    pub fn saturating_add(self, other: Self) -> Self {
225        Self {
226            executed_slot_count: self
227                .executed_slot_count
228                .saturating_add(other.executed_slot_count),
229            session_duration_ms: self
230                .session_duration_ms
231                .saturating_add(other.session_duration_ms),
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn report(bundle_builds: Option<BundleBuildUsage>) -> UsageReport {
241        UsageReport::new(
242            "k".to_string(),
243            "2026-01-01T00:00:00Z".parse().unwrap(),
244            "2026-01-02T00:00:00Z".parse().unwrap(),
245            vec![UsageBucket {
246                start: "2026-01-01T00:00:00Z".parse().unwrap(),
247                end: "2026-01-02T00:00:00Z".parse().unwrap(),
248                sessions: SessionCounts::default(),
249                compute: ComputeTotals::default(),
250            }],
251            bundle_builds,
252            None,
253        )
254    }
255
256    fn session() -> SessionUsage {
257        SessionUsage {
258            session_id: "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b".parse().unwrap(),
259            session_name: None,
260            started_at: "2026-01-01T09:14:02Z".parse().unwrap(),
261            ended_at: "2026-01-01T09:18:41Z".parse().unwrap(),
262            executed_slot_count: 3_100,
263            session_duration_ms: 279_000,
264        }
265    }
266
267    fn bucket(day: &str, sessions: SessionCounts, compute: ComputeTotals) -> UsageBucket {
268        let start: DateTime<Utc> = format!("2026-01-{day}T00:00:00Z").parse().unwrap();
269        UsageBucket {
270            start,
271            end: start + BUCKET_SPAN,
272            sessions,
273            compute,
274        }
275    }
276
277    #[test]
278    fn new_sums_the_totals_from_the_buckets() {
279        let report = UsageReport::new(
280            "k".to_string(),
281            "2026-01-01T00:00:00Z".parse().unwrap(),
282            "2026-01-03T00:00:00Z".parse().unwrap(),
283            vec![
284                bucket(
285                    "01",
286                    SessionCounts {
287                        started: 1,
288                        completed: 1,
289                        failed: 0,
290                    },
291                    ComputeTotals {
292                        executed_slot_count: 5,
293                        session_duration_ms: 9,
294                    },
295                ),
296                bucket(
297                    "02",
298                    SessionCounts {
299                        started: 2,
300                        completed: 1,
301                        failed: 1,
302                    },
303                    ComputeTotals {
304                        executed_slot_count: 7,
305                        session_duration_ms: 3,
306                    },
307                ),
308            ],
309            None,
310            None,
311        );
312        assert_eq!(
313            report.sessions(),
314            SessionCounts {
315                started: 3,
316                completed: 2,
317                failed: 1
318            }
319        );
320        assert_eq!(
321            report.compute(),
322            ComputeTotals {
323                executed_slot_count: 12,
324                session_duration_ms: 12
325            }
326        );
327    }
328
329    #[test]
330    fn new_totals_of_no_buckets_are_zero() {
331        let report = UsageReport::new(
332            "k".to_string(),
333            "2026-01-01T00:00:00Z".parse().unwrap(),
334            "2026-01-01T00:00:00Z".parse().unwrap(),
335            vec![],
336            None,
337            None,
338        );
339        assert_eq!(report.sessions(), SessionCounts::default());
340        assert_eq!(report.compute(), ComputeTotals::default());
341    }
342
343    #[test]
344    fn usage_report_absent_bundle_builds_round_trips_to_none() {
345        let json = serde_json::to_string(&report(None)).unwrap();
346        assert!(!json.contains("bundle_builds"));
347        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
348        assert_eq!(parsed.bundle_builds, None);
349    }
350
351    #[test]
352    fn usage_report_absent_daily_round_trips_to_empty() {
353        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}}"#;
354        let parsed: UsageReport = serde_json::from_str(json).unwrap();
355        assert!(parsed.daily.is_empty());
356        // The totals stay on the wire so an empty `daily` does not read as no usage.
357        assert_eq!(
358            parsed.sessions(),
359            SessionCounts {
360                started: 1,
361                completed: 1,
362                failed: 0
363            }
364        );
365        assert_eq!(
366            parsed.compute(),
367            ComputeTotals {
368                executed_slot_count: 5,
369                session_duration_ms: 9
370            }
371        );
372    }
373
374    #[test]
375    fn usage_report_daily_round_trips() {
376        let json = serde_json::to_string(&report(None)).unwrap();
377        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
378        assert_eq!(parsed.daily, report(None).daily);
379    }
380
381    /// The prefixed form is what anything taking a session id accepts.
382    #[test]
383    fn usage_sessions_round_trip_with_prefixed_ids() {
384        let json = serde_json::to_string(&session_page()).unwrap();
385        assert!(json.contains("\"backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b\""));
386        assert!(!json.contains("session_name"));
387        let parsed: SessionUsagePage = serde_json::from_str(&json).unwrap();
388        assert_eq!(parsed, session_page());
389    }
390
391    fn session_page() -> SessionUsagePage {
392        SessionUsagePage {
393            since: "2026-01-01T00:00:00Z".parse().unwrap(),
394            until: "2026-01-02T00:00:00Z".parse().unwrap(),
395            sessions: vec![session()],
396            next_cursor: None,
397        }
398    }
399
400    /// An omitted cursor means "nothing further", not a parse failure.
401    #[test]
402    fn usage_sessions_absent_cursor_round_trips_to_none() {
403        let json =
404            r#"{"since":"2026-01-01T00:00:00Z","until":"2026-01-02T00:00:00Z","sessions":[]}"#;
405        let parsed: SessionUsagePage = serde_json::from_str(json).unwrap();
406        assert_eq!(parsed.next_cursor, None);
407        assert!(parsed.sessions.is_empty());
408    }
409
410    #[test]
411    fn usage_report_present_bundle_builds_round_trips() {
412        let json = serde_json::to_string(&report(Some(BundleBuildUsage { requested: 3 }))).unwrap();
413        let parsed: UsageReport = serde_json::from_str(&json).unwrap();
414        assert_eq!(
415            parsed.bundle_builds,
416            Some(BundleBuildUsage { requested: 3 })
417        );
418    }
419}