Skip to main content

arcane_sdk/
session.rs

1//! Game session tracking: playtime, and FPS sampled in short windows.
2//!
3//! [`crate::ArcaneClient::init`] opens a session for the whole run of the game.
4//! One background thread named `arcane-session` owns it: it wakes about once a
5//! minute, sends a heartbeat carrying the cumulative playtime, and goes back to
6//! sleep on a condition variable. Nothing else in the SDK polls or spins.
7//!
8//! FPS is sampled, never counted continuously. While the player has performance
9//! sharing enabled in the Arcane desktop app, the thread opens a 30-second
10//! window at T+60 s and then every 5 minutes. During a window
11//! [`crate::ArcaneClient::frame`] is a relaxed atomic increment; outside one it
12//! is a single relaxed load. A window with no frames produces no sample.
13//!
14//! A session that never reaches the desktop app stays `Pending` and keeps
15//! retrying. It surfaces no error of its own: the last one is kept in the
16//! session state, where `{client:?}` shows it.
17//!
18//! The same thread carries lobby event polling, but only once the game has
19//! called [`crate::ArcaneClient::p2p`]: it then asks the desktop app for events
20//! on every tick, every 5 seconds while a lobby is open. Heartbeats keep their
21//! own 60-second schedule either way. See [`LobbyPollingState`].
22//!
23//! Playtime is measured with [`Instant`], so it is immune to wall-clock changes.
24//! If the desktop app is never reachable, the session's playtime is lost — the
25//! SDK keeps no buffer on disk.
26
27use std::fmt;
28use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
29use std::sync::{Arc, Condvar, Mutex, MutexGuard};
30use std::thread;
31use std::time::{Duration, Instant};
32
33use serde::{Deserialize, Serialize};
34use serde_json::json;
35
36use crate::desktop::{post_json, DesktopCall, GAMES_PATH_PREFIX};
37use crate::device::now_unix;
38use crate::error::SdkError;
39use crate::p2p::{poll_once, LobbyPollingState, P2pState};
40
41const TICK: Duration = Duration::from_secs(60);
42const FIRST_WINDOW_AT: Duration = Duration::from_secs(60);
43const WINDOW_PERIOD: Duration = Duration::from_secs(300);
44const WINDOW_LEN: Duration = Duration::from_secs(30);
45const MIN_WAIT: Duration = Duration::from_millis(50);
46const CALL_TIMEOUT: Duration = Duration::from_secs(5);
47const END_TIMEOUT: Duration = Duration::from_secs(2);
48const MAX_PENDING_SAMPLES: usize = 16;
49const THREAD_STACK_BYTES: usize = 64 * 1024;
50
51pub(crate) const SESSION_TICK_ENV: &str = "ARCANE_SESSION_TICK_MS";
52
53fn tick_period() -> Duration {
54    std::env::var(SESSION_TICK_ENV)
55        .ok()
56        .and_then(|raw| raw.trim().parse::<u64>().ok())
57        .filter(|ms| *ms > 0)
58        .map(|ms| Duration::from_millis(ms).max(MIN_WAIT))
59        .unwrap_or(TICK)
60}
61
62/// Whether the SDK is tracking this play session.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum TrackingState {
65    /// The Arcane desktop app acknowledged the session. Playtime and FPS samples
66    /// are being reported.
67    Active,
68    /// A local session is open and playtime is accumulating, but the desktop app
69    /// has not acknowledged it yet. The SDK retries every 60 seconds.
70    Pending,
71    /// Nothing is tracked: `ARCANE_OFFLINE_ONLY` is set, or DRM is disabled for
72    /// the title and no Arcane account is known, so there is nobody to attribute
73    /// playtime to.
74    Disabled,
75}
76
77impl TrackingState {
78    /// Stable wire string: `"active"`, `"pending"`, `"disabled"`.
79    pub fn as_str(&self) -> &'static str {
80        match self {
81            Self::Active => "active",
82            Self::Pending => "pending",
83            Self::Disabled => "disabled",
84        }
85    }
86}
87
88impl fmt::Display for TrackingState {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(self.as_str())
91    }
92}
93
94/// What the session looks like right now — for logs, overlays and QA screens.
95///
96/// Read it with [`crate::ArcaneClient::session`]. It is a copy: nothing here
97/// keeps the session alive or blocks the background thread.
98#[derive(Debug, Clone)]
99pub struct SessionSnapshot {
100    /// Session id issued by the Arcane desktop app, once it acknowledged the
101    /// session.
102    pub session_id: Option<String>,
103    /// Whether the session is tracked, waiting for the desktop app, or off.
104    pub tracking: TrackingState,
105    /// Playtime since `init`, in seconds, measured with a monotonic clock.
106    pub played_seconds: u64,
107    /// Whether the player has performance sharing enabled in Arcane desktop.
108    /// FPS windows only open while this is `true`.
109    pub fps_sampling: bool,
110    /// How many FPS samples this session has produced.
111    pub samples_taken: u32,
112    /// Average frame rate of the most recent sample.
113    pub last_fps_avg: Option<f32>,
114    /// Whether the session thread is polling Arcane for lobby events, and why
115    /// not when it is not.
116    pub lobby_events: LobbyPollingState,
117}
118
119impl SessionSnapshot {
120    pub(crate) fn to_json(&self) -> String {
121        json!({
122            "session_id": self.session_id,
123            "tracking": self.tracking.as_str(),
124            "played_seconds": self.played_seconds,
125            "fps_sampling": self.fps_sampling,
126            "samples_taken": self.samples_taken,
127            "last_fps_avg": self.last_fps_avg,
128            "lobby_events": self.lobby_events.as_str(),
129        })
130        .to_string()
131    }
132}
133
134#[derive(Debug, Clone, Serialize)]
135struct FpsSample {
136    sample_id: String,
137    taken_at: i64,
138    fps_avg: f32,
139    window_seconds: u32,
140    frames: u64,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    resolution: Option<String>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    graphics_preset: Option<String>,
145}
146
147#[derive(Debug, Deserialize)]
148struct StartResponse {
149    session_id: String,
150    #[serde(default)]
151    fps_sampling: bool,
152}
153
154#[derive(Debug, Deserialize)]
155struct HeartbeatResponse {
156    #[serde(default)]
157    fps_sampling: bool,
158}
159
160#[derive(Debug)]
161struct State {
162    stop: bool,
163    tracking: TrackingState,
164    session_id: Option<String>,
165    fps_sampling: bool,
166    samples_taken: u32,
167    last_fps_avg: Option<f32>,
168    pending: Vec<FpsSample>,
169    resolution: Option<String>,
170    graphics_preset: Option<String>,
171    next_window_at: Duration,
172    window_open_at: Option<Duration>,
173    last_error: Option<SdkError>,
174}
175
176#[derive(Debug)]
177pub(crate) struct SessionInner {
178    game_id: String,
179    window_open: AtomicBool,
180    frames: AtomicU64,
181    started: Instant,
182    state: Mutex<State>,
183    wake: Condvar,
184    p2p: Arc<P2pState>,
185}
186
187impl SessionInner {
188    fn new(game_id: &str, p2p: Arc<P2pState>) -> Self {
189        Self {
190            game_id: game_id.to_string(),
191            p2p,
192            window_open: AtomicBool::new(false),
193            frames: AtomicU64::new(0),
194            started: Instant::now(),
195            state: Mutex::new(State {
196                stop: false,
197                tracking: TrackingState::Disabled,
198                session_id: None,
199                fps_sampling: false,
200                samples_taken: 0,
201                last_fps_avg: None,
202                pending: Vec::new(),
203                resolution: None,
204                graphics_preset: None,
205                next_window_at: FIRST_WINDOW_AT,
206                window_open_at: None,
207                last_error: None,
208            }),
209            wake: Condvar::new(),
210        }
211    }
212
213    fn lock(&self) -> MutexGuard<'_, State> {
214        self.state.lock().unwrap_or_else(|e| e.into_inner())
215    }
216
217    fn frame(&self) {
218        if self.window_open.load(Ordering::Relaxed) {
219            self.frames.fetch_add(1, Ordering::Relaxed);
220        }
221    }
222
223    fn set_graphics(&self, resolution: &str, preset: &str) {
224        let mut state = self.lock();
225        state.resolution = non_empty(resolution);
226        state.graphics_preset = non_empty(preset);
227    }
228
229    fn seconds_at(&self, elapsed: Duration) -> u64 {
230        elapsed.as_secs()
231    }
232
233    fn snapshot(&self) -> SessionSnapshot {
234        let polling = self.p2p.polling();
235        let state = self.lock();
236        // No session thread runs while tracking is off, so nothing polls
237        // whatever the game armed.
238        let lobby_events = match state.tracking {
239            TrackingState::Disabled => LobbyPollingState::Off,
240            _ => polling,
241        };
242        let played_seconds = match state.tracking {
243            TrackingState::Disabled => 0,
244            _ => self.seconds_at(self.started.elapsed()),
245        };
246        SessionSnapshot {
247            session_id: state.session_id.clone(),
248            tracking: state.tracking,
249            played_seconds,
250            fps_sampling: state.fps_sampling,
251            samples_taken: state.samples_taken,
252            last_fps_avg: state.last_fps_avg,
253            lobby_events,
254        }
255    }
256
257    fn poll_window(&self, elapsed: Duration) {
258        let mut state = self.lock();
259        if !state.fps_sampling {
260            self.close_window(&mut state, None);
261            return;
262        }
263        match state.window_open_at {
264            Some(open_at) => {
265                if elapsed >= open_at + WINDOW_LEN {
266                    self.close_window(&mut state, Some(elapsed));
267                }
268            }
269            None => {
270                if elapsed >= state.next_window_at {
271                    state.window_open_at = Some(elapsed);
272                    self.frames.store(0, Ordering::Relaxed);
273                    self.window_open.store(true, Ordering::Relaxed);
274                }
275            }
276        }
277    }
278
279    fn close_window(&self, state: &mut State, closed_at: Option<Duration>) {
280        let Some(open_at) = state.window_open_at.take() else {
281            return;
282        };
283        self.window_open.store(false, Ordering::Relaxed);
284        let frames = self.frames.swap(0, Ordering::Relaxed);
285        state.next_window_at = open_at + WINDOW_PERIOD;
286
287        let Some(closed_at) = closed_at else {
288            return;
289        };
290        let window_seconds = closed_at.saturating_sub(open_at).as_secs_f64().round() as u32;
291        if frames == 0 || window_seconds == 0 {
292            return;
293        }
294
295        let sample = FpsSample {
296            sample_id: uuid::Uuid::new_v4().to_string(),
297            taken_at: now_unix(),
298            fps_avg: frames as f32 / window_seconds as f32,
299            window_seconds,
300            frames,
301            resolution: state.resolution.clone(),
302            graphics_preset: state.graphics_preset.clone(),
303        };
304        state.last_fps_avg = Some(sample.fps_avg);
305        state.samples_taken = state.samples_taken.saturating_add(1);
306        if state.pending.len() >= MAX_PENDING_SAMPLES {
307            state.pending.remove(0);
308        }
309        state.pending.push(sample);
310    }
311
312    fn set_fps_sampling(&self, enabled: bool) {
313        let mut state = self.lock();
314        state.fps_sampling = enabled;
315        if !enabled {
316            self.close_window(&mut state, None);
317        }
318    }
319
320    fn next_window_deadline(&self, state: &State) -> Option<Duration> {
321        if !state.fps_sampling {
322            return None;
323        }
324        match state.window_open_at {
325            Some(open_at) => Some(open_at + WINDOW_LEN),
326            None => Some(state.next_window_at),
327        }
328    }
329
330    fn acknowledge(&self, sent: &[FpsSample]) {
331        if sent.is_empty() {
332            return;
333        }
334        let mut state = self.lock();
335        state
336            .pending
337            .retain(|kept| !sent.iter().any(|s| s.sample_id == kept.sample_id));
338    }
339
340    fn tick(&self) {
341        let (session_id, pending) = {
342            let state = self.lock();
343            (state.session_id.clone(), state.pending.clone())
344        };
345
346        let Some(session_id) = session_id else {
347            self.try_start();
348            return;
349        };
350
351        let seconds = self.seconds_at(self.started.elapsed());
352        match self.post_heartbeat(&session_id, seconds, &pending) {
353            Ok(response) => {
354                self.acknowledge(&pending);
355                self.set_fps_sampling(response.fps_sampling);
356                let mut state = self.lock();
357                state.tracking = TrackingState::Active;
358                state.last_error = None;
359            }
360            Err(call) => {
361                let expired = call.desktop_error() == Some("unknown_session");
362                self.record_error(call);
363                if expired {
364                    {
365                        let mut state = self.lock();
366                        state.session_id = None;
367                        state.tracking = TrackingState::Pending;
368                    }
369                    self.try_start();
370                }
371            }
372        }
373    }
374
375    fn try_start(&self) {
376        let response = match self.post_start() {
377            Ok(response) => response,
378            Err(call) => {
379                self.record_error(call);
380                return;
381            }
382        };
383        {
384            let mut state = self.lock();
385            state.session_id = Some(response.session_id);
386            state.tracking = TrackingState::Active;
387            state.last_error = None;
388        }
389        self.set_fps_sampling(response.fps_sampling);
390    }
391
392    fn poll_lobby_events(&self) {
393        if let Some(err) = poll_once(&self.game_id, &self.p2p) {
394            self.lock().last_error = Some(err);
395        }
396    }
397
398    fn record_error(&self, call: DesktopCall) {
399        let error = call.into_sdk_error();
400        self.lock().last_error = Some(error);
401    }
402
403    fn post_start(&self) -> Result<StartResponse, DesktopCall> {
404        post_json(&self.path("start"), None, CALL_TIMEOUT)
405    }
406
407    fn post_heartbeat(
408        &self,
409        session_id: &str,
410        seconds: u64,
411        samples: &[FpsSample],
412    ) -> Result<HeartbeatResponse, DesktopCall> {
413        let body = json!({
414            "session_id": session_id,
415            "seconds": seconds,
416            "samples": samples,
417        });
418        post_json(&self.path("heartbeat"), Some(body), CALL_TIMEOUT)
419    }
420
421    fn post_end(&self, session_id: &str, seconds: u64, samples: &[FpsSample]) {
422        let body = json!({
423            "session_id": session_id,
424            "seconds": seconds,
425            "samples": samples,
426        });
427        let _: Result<serde_json::Value, DesktopCall> =
428            post_json(&self.path("end"), Some(body), END_TIMEOUT);
429    }
430
431    fn path(&self, action: &str) -> String {
432        format!(
433            "{GAMES_PATH_PREFIX}/{}/session/{action}",
434            self.game_id.as_str()
435        )
436    }
437
438    fn end(&self) {
439        let (session_id, pending) = {
440            let mut state = self.lock();
441            (state.session_id.take(), std::mem::take(&mut state.pending))
442        };
443        let Some(session_id) = session_id else {
444            return;
445        };
446        let seconds = self.seconds_at(self.started.elapsed());
447        self.post_end(&session_id, seconds, &pending);
448    }
449
450    pub(crate) fn wake_now(&self) {
451        let _state = self.lock();
452        self.wake.notify_all();
453    }
454
455    fn request_stop(&self) {
456        {
457            let mut state = self.lock();
458            state.stop = true;
459        }
460        self.wake.notify_all();
461    }
462
463    fn stopped(&self) -> bool {
464        self.lock().stop
465    }
466
467    fn wait(&self, timeout: Duration) -> bool {
468        let state = self.lock();
469        let (state, _) = self
470            .wake
471            .wait_timeout(state, timeout)
472            .unwrap_or_else(|e| e.into_inner());
473        state.stop
474    }
475}
476
477fn run(inner: Arc<SessionInner>) {
478    let tick = tick_period();
479    let mut next_tick = Duration::ZERO;
480    let mut next_poll = Duration::ZERO;
481    loop {
482        if inner.stopped() {
483            return;
484        }
485
486        inner.poll_window(inner.started.elapsed());
487
488        if inner.started.elapsed() >= next_tick {
489            inner.tick();
490            next_tick = inner.started.elapsed() + tick;
491        }
492
493        if inner.p2p.armed() && inner.started.elapsed() >= next_poll {
494            inner.poll_lobby_events();
495            next_poll = inner.started.elapsed() + inner.p2p.poll_period(tick);
496        }
497
498        if inner.stopped() {
499            return;
500        }
501
502        let elapsed = inner.started.elapsed();
503        let deadline = {
504            let state = inner.lock();
505            let mut deadline = inner
506                .next_window_deadline(&state)
507                .map_or(next_tick, |window| window.min(next_tick));
508            if inner.p2p.armed() {
509                deadline = deadline.min(next_poll);
510            }
511            deadline
512        };
513        if inner.wait(deadline.saturating_sub(elapsed).max(MIN_WAIT)) {
514            return;
515        }
516    }
517}
518
519fn non_empty(value: &str) -> Option<String> {
520    let trimmed = value.trim();
521    if trimmed.is_empty() {
522        None
523    } else {
524        Some(trimmed.to_string())
525    }
526}
527
528#[derive(Debug)]
529pub(crate) struct Session {
530    inner: Arc<SessionInner>,
531    ended: AtomicBool,
532}
533
534impl Session {
535    pub(crate) fn dormant(game_id: &str, p2p: Arc<P2pState>) -> Self {
536        Self {
537            inner: Arc::new(SessionInner::new(game_id, p2p)),
538            ended: AtomicBool::new(false),
539        }
540    }
541
542    pub(crate) fn begin(&self, tracking: TrackingState) {
543        if tracking == TrackingState::Disabled {
544            return;
545        }
546        self.inner.lock().tracking = tracking;
547        self.inner.p2p.set_waker(Arc::downgrade(&self.inner));
548
549        let worker = Arc::clone(&self.inner);
550        let spawned = thread::Builder::new()
551            .name("arcane-session".to_string())
552            .stack_size(THREAD_STACK_BYTES)
553            .spawn(move || run(worker));
554
555        if spawned.is_err() {
556            self.inner.lock().tracking = TrackingState::Disabled;
557        }
558    }
559
560    pub(crate) fn frame(&self) {
561        self.inner.frame();
562    }
563
564    pub(crate) fn set_graphics(&self, resolution: &str, preset: &str) {
565        self.inner.set_graphics(resolution, preset);
566    }
567
568    pub(crate) fn snapshot(&self) -> SessionSnapshot {
569        self.inner.snapshot()
570    }
571
572    pub(crate) fn end(&self) {
573        if self.ended.swap(true, Ordering::SeqCst) {
574            return;
575        }
576        self.inner.request_stop();
577        self.inner.end();
578    }
579}
580
581impl Drop for Session {
582    fn drop(&mut self) {
583        self.end();
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    fn session() -> SessionInner {
592        SessionInner::new(
593            "7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34",
594            Arc::new(P2pState::new()),
595        )
596    }
597
598    fn sampling_session() -> SessionInner {
599        let inner = session();
600        inner.set_fps_sampling(true);
601        inner
602    }
603
604    fn render(inner: &SessionInner, frames: u64) {
605        for _ in 0..frames {
606            inner.frame();
607        }
608    }
609
610    #[test]
611    fn a_window_produces_one_sample_averaged_over_its_length() {
612        let inner = sampling_session();
613
614        inner.poll_window(FIRST_WINDOW_AT);
615        assert!(inner.window_open.load(Ordering::Relaxed));
616        render(&inner, 1794);
617        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
618
619        let state = inner.lock();
620        assert_eq!(state.pending.len(), 1);
621        let sample = &state.pending[0];
622        assert_eq!(sample.frames, 1794);
623        assert_eq!(sample.window_seconds, 30);
624        assert!((sample.fps_avg - 59.8).abs() < 0.01);
625        assert_eq!(state.samples_taken, 1);
626        assert_eq!(state.last_fps_avg, Some(sample.fps_avg));
627        assert!(!inner.window_open.load(Ordering::Relaxed));
628    }
629
630    #[test]
631    fn the_next_window_opens_five_minutes_after_the_last_one() {
632        let inner = sampling_session();
633        assert_eq!(inner.lock().next_window_at, FIRST_WINDOW_AT);
634
635        inner.poll_window(FIRST_WINDOW_AT);
636        render(&inner, 60);
637        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
638        assert_eq!(inner.lock().next_window_at, FIRST_WINDOW_AT + WINDOW_PERIOD);
639
640        inner.poll_window(FIRST_WINDOW_AT + WINDOW_PERIOD - Duration::from_secs(1));
641        assert!(!inner.window_open.load(Ordering::Relaxed));
642
643        inner.poll_window(FIRST_WINDOW_AT + WINDOW_PERIOD);
644        assert!(inner.window_open.load(Ordering::Relaxed));
645    }
646
647    #[test]
648    fn a_window_without_frames_produces_no_sample() {
649        let inner = sampling_session();
650
651        inner.poll_window(FIRST_WINDOW_AT);
652        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
653
654        let state = inner.lock();
655        assert!(state.pending.is_empty());
656        assert_eq!(state.samples_taken, 0);
657        assert_eq!(state.last_fps_avg, None);
658    }
659
660    #[test]
661    fn no_window_opens_and_frames_are_not_counted_while_sampling_is_off() {
662        let inner = session();
663
664        inner.poll_window(FIRST_WINDOW_AT);
665        assert!(!inner.window_open.load(Ordering::Relaxed));
666        render(&inner, 500);
667        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
668
669        assert_eq!(inner.frames.load(Ordering::Relaxed), 0);
670        assert!(inner.lock().pending.is_empty());
671    }
672
673    #[test]
674    fn turning_sampling_off_closes_the_open_window_without_a_sample() {
675        let inner = sampling_session();
676
677        inner.poll_window(FIRST_WINDOW_AT);
678        render(&inner, 900);
679        inner.set_fps_sampling(false);
680
681        assert!(!inner.window_open.load(Ordering::Relaxed));
682        let state = inner.lock();
683        assert!(state.pending.is_empty());
684        assert_eq!(state.samples_taken, 0);
685        assert!(state.window_open_at.is_none());
686    }
687
688    #[test]
689    fn an_unacknowledged_sample_is_resent_with_the_same_id() {
690        let inner = sampling_session();
691        inner.poll_window(FIRST_WINDOW_AT);
692        render(&inner, 1500);
693        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
694
695        let first: Vec<FpsSample> = inner.lock().pending.clone();
696        let retry: Vec<FpsSample> = inner.lock().pending.clone();
697        assert_eq!(first.len(), 1);
698        assert_eq!(first[0].sample_id, retry[0].sample_id);
699
700        inner.acknowledge(&retry);
701        assert!(inner.lock().pending.is_empty());
702    }
703
704    #[test]
705    fn acknowledging_one_sample_keeps_the_ones_that_were_not_sent() {
706        let inner = sampling_session();
707        inner.poll_window(FIRST_WINDOW_AT);
708        render(&inner, 60);
709        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
710        let sent: Vec<FpsSample> = inner.lock().pending.clone();
711
712        inner.poll_window(FIRST_WINDOW_AT + WINDOW_PERIOD);
713        render(&inner, 30);
714        inner.poll_window(FIRST_WINDOW_AT + WINDOW_PERIOD + WINDOW_LEN);
715        inner.acknowledge(&sent);
716
717        let state = inner.lock();
718        assert_eq!(state.pending.len(), 1);
719        assert_ne!(state.pending[0].sample_id, sent[0].sample_id);
720        assert_eq!(state.samples_taken, 2);
721    }
722
723    #[test]
724    fn the_tick_period_defaults_to_sixty_seconds() {
725        assert_eq!(tick_period(), TICK);
726        assert_eq!(TICK, Duration::from_secs(60));
727        assert_eq!(FIRST_WINDOW_AT, Duration::from_secs(60));
728        assert_eq!(WINDOW_PERIOD, Duration::from_secs(300));
729        assert_eq!(WINDOW_LEN, Duration::from_secs(30));
730    }
731
732    #[test]
733    fn cumulative_seconds_come_from_the_monotonic_clock() {
734        let inner = session();
735        let seconds: Vec<u64> = [0, 59, 60, 90, 3600]
736            .iter()
737            .map(|s| inner.seconds_at(Duration::from_secs(*s)))
738            .collect();
739
740        assert_eq!(seconds, vec![0, 59, 60, 90, 3600]);
741        assert!(seconds.windows(2).all(|pair| pair[1] >= pair[0]));
742    }
743
744    #[test]
745    fn a_sample_carries_the_current_graphics_settings() {
746        let inner = sampling_session();
747        inner.set_graphics("2560x1440", "high");
748
749        inner.poll_window(FIRST_WINDOW_AT);
750        render(&inner, 120);
751        inner.poll_window(FIRST_WINDOW_AT + WINDOW_LEN);
752
753        let state = inner.lock();
754        assert_eq!(state.pending[0].resolution.as_deref(), Some("2560x1440"));
755        assert_eq!(state.pending[0].graphics_preset.as_deref(), Some("high"));
756    }
757
758    #[test]
759    fn the_snapshot_carries_the_lobby_polling_state() {
760        let p2p = Arc::new(P2pState::new());
761        let inner = SessionInner::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", Arc::clone(&p2p));
762        inner.lock().tracking = TrackingState::Pending;
763        assert_eq!(inner.snapshot().lobby_events, LobbyPollingState::Off);
764
765        crate::p2p::P2p::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", &p2p);
766        assert_eq!(inner.snapshot().lobby_events, LobbyPollingState::Active);
767    }
768
769    #[test]
770    fn a_disabled_session_polls_nothing_however_armed_it_is() {
771        let p2p = Arc::new(P2pState::new());
772        let inner = SessionInner::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", Arc::clone(&p2p));
773        crate::p2p::P2p::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", &p2p);
774
775        assert_eq!(inner.lock().tracking, TrackingState::Disabled);
776        assert_eq!(
777            inner.snapshot().lobby_events,
778            LobbyPollingState::Off,
779            "no session thread runs, so nothing is polling"
780        );
781    }
782
783    #[test]
784    fn a_disabled_session_reports_no_playtime() {
785        let inner = session();
786        let snapshot = inner.snapshot();
787
788        assert_eq!(snapshot.tracking, TrackingState::Disabled);
789        assert_eq!(snapshot.played_seconds, 0);
790        assert_eq!(snapshot.session_id, None);
791        assert!(!snapshot.fps_sampling);
792    }
793
794    #[test]
795    fn the_snapshot_json_carries_every_field() {
796        let inner = session();
797        inner.lock().tracking = TrackingState::Pending;
798        let parsed: serde_json::Value =
799            serde_json::from_str(&inner.snapshot().to_json()).expect("json");
800
801        assert_eq!(parsed["tracking"], "pending");
802        assert_eq!(parsed["session_id"], serde_json::Value::Null);
803        assert_eq!(parsed["samples_taken"], 0);
804        assert_eq!(parsed["fps_sampling"], false);
805        assert_eq!(parsed["last_fps_avg"], serde_json::Value::Null);
806        assert_eq!(parsed["lobby_events"], "off");
807        assert!(parsed["played_seconds"].is_u64());
808    }
809}