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                published_deck_id: deck.and_then(|deck| deck.published_deck_id.clone()),
133                deck_fingerprint: deck
134                    .map(|deck| manabrew_protocol::deck_dto::deck_fingerprint(&deck.deck)),
135            }
136        })
137        .collect();
138    AnalyticsEvent::GameStarted {
139        ts: now_ts(),
140        game_id: started.game_id.clone(),
141        room_id: started.room_id.clone(),
142        format: started.room_info.format.clone(),
143        engine: started.room_info.engine,
144        hosted: started.room_info.hosted,
145        official: started.room_info.official,
146        starting_life: started.starting_life,
147        players,
148    }
149}
150
151pub fn emit_game_ended(
152    handle: &AnalyticsHandle,
153    room: &Room,
154    replay: &GameReplayCache,
155    fallback: GameEndReason,
156) {
157    let reason = if replay.outcome.game_over {
158        GameEndReason::GameOver
159    } else if replay.outcome.fatal_message.is_some() {
160        GameEndReason::EngineFatal
161    } else {
162        fallback
163    };
164    metrics::record_game_ended(reason);
165    let winner = replay
166        .outcome
167        .winner_slot
168        .as_deref()
169        .and_then(|slot| replay.username_for_slot(slot));
170    let conceded = replay
171        .outcome
172        .conceded_slots
173        .iter()
174        .filter_map(|slot| replay.username_for_slot(slot))
175        .collect();
176    handle.emit(AnalyticsEvent::GameEnded {
177        ts: now_ts(),
178        game_id: replay.game_id.clone(),
179        room_id: room.room_id.clone(),
180        reason,
181        duration_s: replay.started_at.elapsed().as_secs_f64(),
182        game_over: replay.outcome.game_over,
183        winner,
184        conceded,
185        fatal_message: replay.outcome.fatal_message.clone(),
186    });
187}
188
189pub fn aggregate_deck_cards(deck: &Deck) -> Vec<CardEntry> {
190    let mut counts: HashMap<(String, String), u32> = HashMap::new();
191    let commanders = deck.commanders.iter().flatten();
192    for card in deck.cards.iter().chain(commanders) {
193        *counts
194            .entry((card.identity.name.clone(), card.identity.set_code.clone()))
195            .or_insert(0) += 1;
196    }
197    let mut cards: Vec<CardEntry> = counts
198        .into_iter()
199        .map(|((name, set_code), count)| CardEntry {
200            name,
201            set_code,
202            count,
203        })
204        .collect();
205    cards.sort_by(|a, b| a.name.cmp(&b.name));
206    cards
207}