Skip to main content

manabrew_server/analytics/
mod.rs

1mod capture;
2mod event;
3mod writer;
4
5use std::collections::HashMap;
6use std::path::PathBuf;
7
8use serde_json::Value;
9use tokio::sync::mpsc;
10
11pub use event::{AnalyticsEvent, CardEntry, GameEndReason, SeatInfo};
12
13use crate::config::ServerConfig;
14use crate::lobby::StartedGame;
15use crate::metrics;
16use crate::replay::GameReplayCache;
17use crate::room::Room;
18use manabrew_protocol::deck_dto::Deck;
19
20const CHANNEL_CAPACITY: usize = 8192;
21
22#[derive(Clone)]
23pub struct AnalyticsHandle {
24    events: Option<mpsc::Sender<AnalyticsEvent>>,
25    capture: Option<std::sync::mpsc::SyncSender<capture::CaptureMessage>>,
26}
27
28impl AnalyticsHandle {
29    pub fn disabled() -> Self {
30        AnalyticsHandle {
31            events: None,
32            capture: None,
33        }
34    }
35
36    pub fn from_config(config: &ServerConfig) -> Self {
37        let events = config.events_dir.clone().map(|dir| {
38            let (tx, rx) = mpsc::channel(CHANNEL_CAPACITY);
39            writer::spawn(rx, PathBuf::from(dir));
40            tx
41        });
42        let capture = config.capture_dir.clone().map(|dir| {
43            let (tx, rx) = std::sync::mpsc::sync_channel(CHANNEL_CAPACITY);
44            capture::spawn(rx, PathBuf::from(dir), config.capture_max_bytes());
45            tx
46        });
47        AnalyticsHandle { events, capture }
48    }
49
50    pub fn events_enabled(&self) -> bool {
51        self.events.is_some()
52    }
53
54    pub fn capture_enabled(&self) -> bool {
55        self.capture.is_some()
56    }
57
58    pub fn emit(&self, event: AnalyticsEvent) {
59        match &event {
60            AnalyticsEvent::GameStarted { game_id, .. } => {
61                self.send_capture(capture::CaptureMessage::Open {
62                    game_id: game_id.clone(),
63                    header: json_line(&event),
64                });
65            }
66            AnalyticsEvent::GameEnded { game_id, .. } => {
67                self.send_capture(capture::CaptureMessage::Close {
68                    game_id: game_id.clone(),
69                    footer: json_line(&event),
70                });
71            }
72            _ => {}
73        }
74        if let Some(tx) = &self.events {
75            if tx.try_send(event).is_err() {
76                metrics::record_analytics_dropped();
77            }
78        }
79    }
80
81    pub fn capture_envelope(&self, game_id: &str, from_player: &str, envelope: &Value) {
82        if self.capture.is_none() {
83            return;
84        }
85        let line = json_line(&event::CaptureLine {
86            ts: now_ts(),
87            from: from_player,
88            envelope,
89        });
90        self.send_capture(capture::CaptureMessage::Line {
91            game_id: game_id.to_string(),
92            line,
93        });
94    }
95
96    fn send_capture(&self, message: capture::CaptureMessage) {
97        if let Some(tx) = &self.capture {
98            if tx.try_send(message).is_err() {
99                metrics::record_analytics_dropped();
100            }
101        }
102    }
103}
104
105pub fn now_ts() -> String {
106    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
107}
108
109fn json_line<T: serde::Serialize>(value: &T) -> String {
110    serde_json::to_string(value).unwrap_or_default()
111}
112
113pub fn game_started_event(started: &StartedGame) -> AnalyticsEvent {
114    let players = started
115        .player_order
116        .iter()
117        .map(|username| {
118            let deck = started
119                .player_decks
120                .iter()
121                .find(|deck| &deck.username == username);
122            let is_bot = started
123                .room_info
124                .players
125                .iter()
126                .any(|player| &player.username == username && player.is_bot);
127            SeatInfo {
128                username: username.clone(),
129                is_bot,
130                deck_name: deck.map(|deck| deck.deck_name.clone()),
131                commander: deck.and_then(|deck| deck.commander_name.clone()),
132            }
133        })
134        .collect();
135    AnalyticsEvent::GameStarted {
136        ts: now_ts(),
137        game_id: started.game_id.clone(),
138        room_id: started.room_id.clone(),
139        format: started.room_info.format.clone(),
140        engine: started.room_info.engine,
141        hosted: started.room_info.hosted,
142        official: started.room_info.official,
143        starting_life: started.starting_life,
144        players,
145    }
146}
147
148pub fn emit_game_ended(
149    handle: &AnalyticsHandle,
150    room: &Room,
151    replay: &GameReplayCache,
152    fallback: GameEndReason,
153) {
154    let reason = if replay.outcome.game_over {
155        GameEndReason::GameOver
156    } else if replay.outcome.fatal_message.is_some() {
157        GameEndReason::EngineFatal
158    } else {
159        fallback
160    };
161    metrics::record_game_ended(reason);
162    let winner = replay
163        .outcome
164        .winner_slot
165        .as_deref()
166        .and_then(|slot| replay.username_for_slot(slot));
167    let conceded = replay
168        .outcome
169        .conceded_slots
170        .iter()
171        .filter_map(|slot| replay.username_for_slot(slot))
172        .collect();
173    handle.emit(AnalyticsEvent::GameEnded {
174        ts: now_ts(),
175        game_id: replay.game_id.clone(),
176        room_id: room.room_id.clone(),
177        reason,
178        duration_s: replay.started_at.elapsed().as_secs_f64(),
179        game_over: replay.outcome.game_over,
180        winner,
181        conceded,
182        fatal_message: replay.outcome.fatal_message.clone(),
183    });
184}
185
186pub fn aggregate_deck_cards(deck: &Deck) -> Vec<CardEntry> {
187    let mut counts: HashMap<(String, String), u32> = HashMap::new();
188    let commanders = deck.commanders.iter().flatten();
189    for card in deck.cards.iter().chain(commanders) {
190        *counts
191            .entry((card.identity.name.clone(), card.identity.set_code.clone()))
192            .or_insert(0) += 1;
193    }
194    let mut cards: Vec<CardEntry> = counts
195        .into_iter()
196        .map(|((name, set_code), count)| CardEntry {
197            name,
198            set_code,
199            count,
200        })
201        .collect();
202    cards.sort_by(|a, b| a.name.cmp(&b.name));
203    cards
204}