1use serde::{Deserialize, Serialize};
19use ts_rs::TS;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
22#[serde(rename_all = "camelCase")]
23#[ts(export, export_to = "telemetry.ts")]
24pub struct EnginePlayStats {
25 pub report_id: String,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
36 #[ts(optional)]
37 pub game_id: Option<String>,
38 pub engine: String,
41 pub client_version: String,
42 pub platform: String,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 #[ts(optional)]
45 pub format: Option<String>,
46 pub seats: u32,
47 pub multiplayer: bool,
48 pub duration_s: u32,
49 pub end_reason: String,
50 pub turnaround: EngineTurnaround,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
60 #[ts(optional)]
61 pub reply_wait: Option<EngineTurnaround>,
62 #[serde(default, skip_serializing_if = "Option::is_none")]
63 #[ts(optional)]
64 pub client_work: Option<EngineTurnaround>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
67 #[ts(optional)]
68 pub engine_think: Option<EngineTurnaround>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
74 #[ts(optional)]
75 pub engine_think_same_turn: Option<EngineTurnaround>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 #[ts(optional)]
78 pub engine_think_cross_turn: Option<EngineTurnaround>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
84 #[ts(optional)]
85 pub engine_think_bot: Option<EngineTurnaround>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 #[ts(optional)]
88 pub engine_think_rules: Option<EngineTurnaround>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 #[ts(optional)]
91 pub checkpoints: Option<EngineCheckpointStats>,
92 #[serde(default)]
96 pub think_samples_hidden: u32,
97 #[serde(default)]
98 pub by_type: Vec<EngineTypeTurnaround>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
102#[serde(rename_all = "camelCase")]
103#[ts(export, export_to = "telemetry.ts")]
104pub struct EngineTurnaround {
105 pub n: u32,
106 pub p50: u32,
107 pub p90: u32,
108 pub max: u32,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
112#[serde(rename_all = "camelCase")]
113#[ts(export, export_to = "telemetry.ts")]
114pub struct EngineTypeTurnaround {
115 #[serde(rename = "type")]
116 pub prompt_type: String,
117 pub n: u32,
118 pub p50: u32,
119 pub max: u32,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
123#[serde(rename_all = "camelCase")]
124#[ts(export, export_to = "telemetry.ts")]
125pub struct EngineCheckpointTiming {
126 pub n: u32,
127 #[ts(type = "number")]
128 pub sum_us: u64,
129 #[ts(type = "number")]
130 pub p50_us: u64,
131 #[ts(type = "number")]
132 pub p95_us: u64,
133 #[ts(type = "number")]
134 pub p99_us: u64,
135 #[ts(type = "number")]
136 pub max_us: u64,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
140#[serde(rename_all = "camelCase")]
141#[ts(export, export_to = "telemetry.ts")]
142pub struct EngineCheckpointStats {
143 pub copy: EngineCheckpointTiming,
144 pub bookkeeping: EngineCheckpointTiming,
145 pub total: EngineCheckpointTiming,
146 pub decision: EngineCheckpointTiming,
147 pub hidden: u32,
148 pub dropped: u32,
149}
150
151impl EngineCheckpointTiming {
152 fn is_plausible(&self) -> bool {
153 self.n <= 4000
154 && self.p50_us <= self.p95_us
155 && self.p95_us <= self.p99_us
156 && self.p99_us <= self.max_us
157 && self.max_us <= self.sum_us
158 && self.sum_us <= 86_400_000_000
159 && (self.n > 0 || self.sum_us == 0)
160 }
161}
162
163impl EngineCheckpointStats {
164 fn is_plausible(&self) -> bool {
165 [&self.copy, &self.bookkeeping, &self.total, &self.decision]
166 .iter()
167 .all(|timing| timing.is_plausible())
168 && self.copy.n == self.bookkeeping.n
169 && self.copy.n == self.total.n
170 && self.total.sum_us == self.copy.sum_us + self.bookkeeping.sum_us
171 }
172}
173
174impl EnginePlayStats {
175 pub fn is_plausible(&self) -> bool {
179 let text = |value: &str, max: usize| !value.is_empty() && value.len() <= max;
180 uuid_shaped(&self.report_id)
181 && text(&self.engine, 40)
182 && text(&self.client_version, 40)
183 && text(&self.platform, 20)
184 && text(&self.end_reason, 20)
185 && self.format.as_ref().is_none_or(|f| f.len() <= 40)
186 && (1..=8).contains(&self.seats)
187 && self.by_type.len() <= 32
188 && self.turnaround.n > 0
189 && self
190 .checkpoints
191 .as_ref()
192 .is_none_or(EngineCheckpointStats::is_plausible)
193 }
194
195 pub fn linked_game_id(&self) -> Option<&str> {
200 self.game_id.as_deref().filter(|id| uuid_shaped(id))
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
207#[serde(rename_all = "camelCase")]
208#[ts(export, export_to = "telemetry.ts")]
209pub struct OfflinePlayGame {
210 pub report_id: String,
213 pub started_at: String,
214 pub ended_at: String,
215 pub duration_s: u32,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 #[ts(optional)]
218 pub format: Option<String>,
219 pub engine: String,
220 pub starting_life: i32,
221 pub end_reason: String,
222 pub game_over: bool,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 #[ts(optional)]
225 pub engine_error: Option<String>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 #[ts(optional)]
228 pub winner: Option<String>,
229 #[serde(default)]
230 pub conceded: Vec<String>,
231 pub client_version: String,
232 pub platform: String,
233 pub players: Vec<OfflinePlaySeat>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
235 #[ts(optional)]
236 pub rematch_of: Option<String>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
240#[serde(rename_all = "camelCase")]
241#[ts(export, export_to = "telemetry.ts")]
242pub struct OfflinePlaySeat {
243 pub username: String,
245 pub is_bot: bool,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 #[ts(optional)]
248 pub deck_name: Option<String>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
250 #[ts(optional)]
251 pub commander: Option<String>,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
253 #[ts(optional)]
254 pub published_deck_id: Option<String>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 #[ts(optional)]
257 pub deck_fingerprint: Option<String>,
258 #[serde(default)]
259 pub sideboard_count: u32,
260 #[serde(default)]
261 pub cards: Vec<OfflinePlayCard>,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
265#[serde(rename_all = "camelCase")]
266#[ts(export, export_to = "telemetry.ts")]
267pub struct OfflinePlayCard {
268 pub name: String,
269 pub set_code: String,
270 pub count: u32,
271}
272
273const MAX_CARDS_PER_SEAT: usize = 400;
274
275impl OfflinePlayGame {
276 pub fn is_plausible(&self) -> bool {
279 let text = |value: &str, max: usize| !value.is_empty() && value.len() <= max;
280 uuid_shaped(&self.report_id)
281 && text(&self.started_at, 40)
282 && text(&self.ended_at, 40)
283 && text(&self.engine, 40)
284 && text(&self.client_version, 40)
285 && text(&self.platform, 20)
286 && text(&self.end_reason, 30)
287 && self.format.as_ref().is_none_or(|f| f.len() <= 40)
288 && self.winner.as_ref().is_none_or(|w| w.len() <= 80)
289 && self.conceded.len() <= 8
290 && self.conceded.iter().all(|name| text(name, 80))
291 && (1..=8).contains(&self.players.len())
292 && self.players.iter().all(OfflinePlaySeat::is_plausible)
293 && self.rematch_of.as_deref().is_none_or(uuid_shaped)
294 }
295}
296
297impl OfflinePlaySeat {
298 fn is_plausible(&self) -> bool {
299 let opt =
300 |value: &Option<String>, max: usize| value.as_ref().is_none_or(|v| v.len() <= max);
301 !self.username.is_empty()
302 && self.username.len() <= 80
303 && opt(&self.deck_name, 120)
304 && opt(&self.commander, 120)
305 && opt(&self.published_deck_id, 200)
306 && self
308 .deck_fingerprint
309 .as_ref()
310 .is_none_or(|value| value.len() == 64 && value.bytes().all(is_lower_hex))
311 && self.cards.len() <= MAX_CARDS_PER_SEAT
312 && self.cards.iter().all(OfflinePlayCard::is_plausible)
313 }
314}
315
316impl OfflinePlayCard {
317 fn is_plausible(&self) -> bool {
318 !self.name.is_empty()
319 && self.name.len() <= 200
320 && self.set_code.len() <= 20
321 && (1..=1000).contains(&self.count)
322 }
323}
324
325fn is_lower_hex(byte: u8) -> bool {
326 byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
327}
328
329fn uuid_shaped(value: &str) -> bool {
330 value.len() == 36
331 && value.bytes().enumerate().all(|(index, byte)| match index {
332 8 | 13 | 18 | 23 => byte == b'-',
333 _ => byte.is_ascii_hexdigit(),
334 })
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 fn sample() -> EnginePlayStats {
342 EnginePlayStats {
343 report_id: "11111111-2222-3333-4444-555555555555".to_string(),
344 game_id: Some("66666666-7777-8888-9999-aaaaaaaaaaaa".to_string()),
345 engine: "forge-wasm".to_string(),
346 client_version: "3.18.5".to_string(),
347 platform: "web".to_string(),
348 format: Some("standard".to_string()),
349 seats: 2,
350 multiplayer: false,
351 duration_s: 400,
352 end_reason: "gameOver".to_string(),
353 turnaround: EngineTurnaround {
354 n: 180,
355 p50: 46,
356 p90: 78,
357 max: 320,
358 },
359 reply_wait: None,
360 client_work: None,
361 engine_think: None,
362 engine_think_same_turn: None,
363 engine_think_cross_turn: None,
364 engine_think_bot: None,
365 engine_think_rules: None,
366 checkpoints: None,
367 think_samples_hidden: 0,
368 by_type: vec![],
369 }
370 }
371
372 #[test]
373 fn accepts_a_real_report() {
374 assert!(sample().is_plausible());
375 assert_eq!(
376 sample().linked_game_id(),
377 Some("66666666-7777-8888-9999-aaaaaaaaaaaa")
378 );
379 }
380
381 #[test]
385 fn a_bad_game_id_costs_the_link_not_the_report() {
386 let mut report = sample();
387 report.game_id = Some("not-a-uuid".to_string());
388 assert!(report.is_plausible());
389 assert_eq!(report.linked_game_id(), None);
390
391 report.game_id = None;
392 assert!(report.is_plausible());
393 assert_eq!(report.linked_game_id(), None);
394 }
395
396 #[test]
397 fn rejects_the_shapes_a_hostile_client_sends() {
398 let cases: Vec<(&str, Box<dyn Fn(&mut EnginePlayStats)>)> = vec![
399 (
400 "not a uuid",
401 Box::new(|s: &mut EnginePlayStats| s.report_id = "nope".to_string()),
402 ),
403 (
404 "empty engine",
405 Box::new(|s: &mut EnginePlayStats| s.engine = String::new()),
406 ),
407 (
408 "huge engine",
409 Box::new(|s: &mut EnginePlayStats| s.engine = "x".repeat(41)),
410 ),
411 ("no seats", Box::new(|s: &mut EnginePlayStats| s.seats = 0)),
412 (
413 "too many seats",
414 Box::new(|s: &mut EnginePlayStats| s.seats = 9),
415 ),
416 (
417 "no decisions",
418 Box::new(|s: &mut EnginePlayStats| s.turnaround.n = 0),
419 ),
420 ];
421 for (name, break_it) in cases {
422 let mut report = sample();
423 break_it(&mut report);
424 assert!(!report.is_plausible(), "{name} should have been rejected");
425 }
426 }
427}