Skip to main content

mlb_api/requests/game/
mod.rs

1//! The thing you're most likely here for.
2//!
3//! This module itself acts like [`crate::types`] but for misc game-specific types as there are many.
4
5#![allow(unused_imports, reason = "usage of children modules")]
6
7use std::fmt::{Display, Formatter};
8use std::marker::PhantomData;
9use std::ops::{ControlFlow, Sub};
10use std::time::{Duration, Instant};
11use bon::Builder;
12use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Utc};
13use derive_more::{Deref, DerefMut, Display, From, Not};
14use fxhash::FxHashMap;
15use serde::{Deserialize, Deserializer};
16use serde::de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor};
17use serde_with::{serde_as, DisplayFromStr};
18use crate::person::{Ballplayer, JerseyNumber, NamedPerson, PersonId};
19use crate::meta::{DayNight, NamedPosition};
20use crate::request::RequestURLBuilderExt;
21use crate::team::TeamId;
22use crate::team::roster::RosterStatus;
23use crate::{DayHalf, HomeAway, ResourceUsage};
24use crate::meta::WindDirectionId;
25use crate::request;
26
27mod boxscore; // done
28mod changes;
29mod content;
30mod context_metrics;
31mod diff;
32mod linescore; // done
33mod pace; // done
34mod plays; // done
35mod timestamps; // done
36mod uniforms;
37mod win_probability;
38mod live_feed; // done
39
40pub use boxscore::*;
41pub use changes::*;
42pub use content::*;
43pub use context_metrics::*;
44pub use diff::*;
45pub use linescore::*;
46pub use pace::*;
47pub use plays::*;
48pub use timestamps::*;
49pub use uniforms::*;
50pub use win_probability::*;
51pub use live_feed::*;
52
53id!(#[doc = "A [`u32`] representing a baseball game. [Sport](crate::sport)-independent"] GameId { gamePk: u32 });
54
55#[derive(Deserialize)]
56#[serde(rename_all = "camelCase")]
57#[doc(hidden)]
58#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
59struct __GameDateTimeStruct {
60	#[serde(rename = "dateTime", deserialize_with = "crate::deserialize_datetime")]
61	datetime: NaiveDateTime,
62	original_date: NaiveDate,
63	official_date: NaiveDate,
64	#[serde(rename = "dayNight")]
65	sky: DayNight,
66	time: NaiveTime,
67	ampm: DayHalf,
68}
69
70/// Date & Time of the game. Note that the time is typically rounded to the hour and the :07, :05 on the hour is for the first pitch, which is a different timestamp.
71#[derive(Debug, Deserialize, PartialEq, Clone)]
72#[serde(from = "__GameDateTimeStruct")]
73pub struct GameDateTime {
74	datetime: NaiveDateTime,
75	original_date: NaiveDate,
76	official_date: NaiveDate,
77	sky: DayNight,
78}
79
80impl From<__GameDateTimeStruct> for GameDateTime {
81	fn from(value: __GameDateTimeStruct) -> Self {
82		let date = value.datetime.date();
83		let time = value.ampm.into_24_hour_time(value.time);
84		Self {
85			datetime: NaiveDateTime::new(date, time),
86			original_date: value.original_date,
87			official_date: value.official_date,
88			sky: value.sky,
89		}
90	}
91}
92
93/// General weather conditions, temperature, wind, etc.
94#[derive(Debug, Deserialize, PartialEq, Clone)]
95#[serde(try_from = "__WeatherConditionsStruct")]
96pub struct WeatherConditions {
97	pub condition: String,
98	pub temp: uom::si::f64::ThermodynamicTemperature,
99	pub wind_speed: uom::si::f64::Velocity,
100	pub wind_direction: WindDirectionId,
101}
102
103#[serde_as]
104#[derive(Deserialize)]
105#[doc(hidden)]
106#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
107struct __WeatherConditionsStruct {
108	condition: String,
109	#[serde_as(as = "DisplayFromStr")]
110	temp: i32,
111	wind: String,
112}
113
114impl TryFrom<__WeatherConditionsStruct> for WeatherConditions {
115	type Error = &'static str;
116
117	fn try_from(value: __WeatherConditionsStruct) -> Result<Self, Self::Error> {
118		let (speed, direction) = value.wind.split_once(" mph, ").ok_or("invalid wind format")?;
119		let speed = speed.parse::<i32>().map_err(|_| "invalid wind speed")?;
120		Ok(Self {
121			condition: value.condition,
122			temp: uom::si::f64::ThermodynamicTemperature::new::<uom::si::thermodynamic_temperature::degree_fahrenheit>(value.temp as f64),
123			wind_speed: uom::si::f64::Velocity::new::<uom::si::velocity::mile_per_hour>(speed as f64),
124			wind_direction: WindDirectionId::new(direction),
125		})
126	}
127}
128
129/// Misc
130#[derive(Debug, Deserialize, PartialEq, Clone)]
131#[serde(rename_all = "camelCase")]
132#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
133pub struct GameInfo {
134	pub attendance: Option<u32>,
135	#[serde(deserialize_with = "crate::deserialize_datetime")]
136	pub first_pitch: NaiveDateTime,
137	/// Measured in minutes,
138	#[serde(rename = "gameDurationMinutes")]
139	pub game_duration: Option<u32>,
140	/// Durationg of the game delay; measured in minutes.
141	#[serde(rename = "delayDurationMinutes")]
142	pub delay_duration: Option<u32>,
143}
144
145/// Review usage for each team and if the game supports challenges.
146#[derive(Debug, Deserialize, PartialEq, Clone)]
147#[serde(rename_all = "camelCase")]
148#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
149pub struct TeamReviewData {
150	pub has_challenges: bool,
151	#[serde(flatten)]
152	pub teams: HomeAway<ResourceUsage>,
153}
154
155/// Tags about a game, such as a perfect game in progress, no-hitter, etc.
156#[allow(clippy::struct_excessive_bools, reason = "")]
157#[derive(Debug, Deserialize, PartialEq, Clone)]
158#[serde(rename_all = "camelCase")]
159#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
160pub struct GameTags {
161	no_hitter: bool,
162	perfect_game: bool,
163
164	away_team_no_hitter: bool,
165	away_team_perfect_game: bool,
166
167	home_team_no_hitter: bool,
168	home_team_perfect_game: bool,
169}
170
171/// Double-header information.
172#[derive(Debug, Deserialize, PartialEq, Copy, Clone)]
173pub enum DoubleHeaderKind {
174	#[serde(rename = "N")]
175	/// Not a doubleheader
176	Not,
177
178	#[serde(rename = "Y")]
179	/// First game in a double-header
180	FirstGame,
181
182	#[serde(rename = "S")]
183	/// Second game in a double-header.
184	SecondGame,
185}
186
187impl DoubleHeaderKind {
188	#[must_use]
189	pub const fn is_double_header(self) -> bool {
190		matches!(self, Self::FirstGame | Self::SecondGame)
191	}
192}
193
194#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Deref, DerefMut, From)]
195pub struct Inning(usize);
196
197impl Display for Inning {
198	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
199		crate::write_nth(self.0, f)
200	}
201}
202
203/// Half of the inning.
204#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Not)]
205pub enum InningHalf {
206	#[serde(rename = "Top", alias = "top")]
207	Top,
208	#[serde(rename = "Bottom", alias = "bottom")]
209	Bottom,
210}
211
212impl InningHalf {
213	/// A unicode character representing an up or down arrow.
214	#[must_use]
215	pub const fn unicode_char_filled(self) -> char {
216		match self {
217			Self::Top => '▲',
218			Self::Bottom => '▼',
219		}
220	}
221	
222	/// A hollow character representing the inning half
223	#[must_use]
224	pub const fn unicode_char_empty(self) -> char {
225		match self {
226			Self::Top => '△',
227			Self::Bottom => '▽',
228		}
229	}
230}
231
232/// The balls and strikes in a given at bat. Along with the number of outs (this technically can change during the AB due to pickoffs etc)
233#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Display)]
234#[display("{balls}-{strikes} ({outs} out)")]
235pub struct AtBatCount {
236	pub balls: u8,
237	pub strikes: u8,
238	pub outs: u8,
239}
240
241/// The classic "R | H | E" and LOB in a scoreboard.
242#[derive(Debug, Deserialize, PartialEq, Copy, Clone)]
243#[serde(from = "__RHEStruct")]
244#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
245pub struct RHE {
246	pub runs: usize,
247	pub hits: usize,
248	pub errors: usize,
249	pub left_on_base: usize,
250	/// Ex: Home team wins and doesn't need to play Bot 9.
251	pub was_inning_half_played: bool,
252}
253
254#[doc(hidden)]
255#[derive(Deserialize)]
256#[serde(rename_all = "camelCase")]
257struct __RHEStruct {
258	pub runs: Option<usize>,
259    pub hits: usize,
260    pub errors: usize,
261    pub left_on_base: usize,
262
263    // only sometimes present, regardless of whether a game is won
264    #[doc(hidden)]
265    #[serde(rename = "isWinner", default)]
266    pub __is_winner: IgnoredAny,
267}
268
269impl From<__RHEStruct> for RHE {
270	fn from(__RHEStruct { runs, hits, errors, left_on_base, .. }: __RHEStruct) -> Self {
271		Self {
272			runs: runs.unwrap_or(0),
273			hits,
274			errors,
275			left_on_base,
276			was_inning_half_played: runs.is_some(),
277		}
278	}
279}
280
281/// Unparsed miscellaneous data.
282///
283/// Some of these values might be handwritten per game so parsing them would prove rather difficult.
284/// 
285/// ## Examples
286/// | Name          | Value     |
287/// |---------------|-----------|
288/// | First pitch   | 8:10 PM.  |
289/// | Weather       | 68 degrees, Roof Closed |
290/// | Att           | 44,713.   |
291#[derive(Debug, Deserialize, PartialEq, Clone)]
292#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
293pub struct LabelledValue {
294	pub label: String,
295	#[serde(default)]
296	pub value: String,
297}
298
299#[derive(Debug, Deserialize, PartialEq, Clone)]
300#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
301pub struct SectionedLabelledValues {
302	#[serde(rename = "title")]
303	pub section: String,
304	#[serde(rename = "fieldList")]
305	pub values: Vec<LabelledValue>,
306}
307
308/// Various flags about the player in the current game
309#[allow(clippy::struct_excessive_bools, reason = "not what's happening here")]
310#[derive(Debug, Deserialize, PartialEq, Clone)]
311#[serde(rename_all = "camelCase")]
312#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
313pub struct PlayerGameStatusFlags {
314	pub is_current_batter: bool,
315	pub is_current_pitcher: bool,
316	pub is_on_bench: bool,
317	pub is_substitute: bool,
318}
319
320#[derive(Debug, Deserialize, PartialEq, Clone)]
321#[serde(rename_all = "camelCase")]
322#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
323pub struct Official {
324	pub official: NamedPerson,
325	pub official_type: OfficialType,
326}
327
328#[derive(Debug, Deserialize, PartialEq, Copy, Clone)]
329pub enum OfficialType {
330	#[serde(rename = "Home Plate")]
331	HomePlate,
332	#[serde(rename = "First Base")]
333	FirstBase,
334	#[serde(rename = "Second Base")]
335	SecondBase,
336	#[serde(rename = "Third Base")]
337	ThirdBase,
338	#[serde(rename = "Left Field")]
339	LeftField,
340	#[serde(rename = "Right Field")]
341	RightField,
342}
343
344/// A position in the batting order, 1st, 2nd, 3rd, 4th, etc.
345///
346/// Note that this number is split in two, the general batting order position is the `major` while if there is a lineup movement then the player would have an increased `minor` since they replace an existing batting order position.
347///
348/// Example:
349/// Alice bats 1st (major = 1, minor = 0)
350/// Bob pinch hits and bats 1st for Alice (major = 1, minor = 1)
351/// Alice somehow hits again (major = 1, minor = 0)
352/// Charlie pinch runs and takes over from then on (major = 1, minor = 2)
353///
354/// Note: These minors are [`Display`]ed incremented one more than is done internally, so (major = 1, minor = 1) displays as `1st (2)`.
355#[derive(Debug, PartialEq, Copy, Clone)]
356pub struct BattingOrderIndex {
357	pub major: usize,
358	pub minor: usize,
359}
360
361impl<'de> Deserialize<'de> for BattingOrderIndex {
362	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
363	where
364	    D: Deserializer<'de>
365	{
366		let v: usize = String::deserialize(deserializer)?.parse().map_err(D::Error::custom)?;
367		Ok(Self {
368			major: v / 100,
369			minor: v % 100,
370		})
371	}
372}
373
374impl Display for BattingOrderIndex {
375	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
376		crate::write_nth(self.major, f)?;
377		if self.minor > 0 {
378			write!(f, " ({})", self.minor + 1)?;
379		}
380		Ok(())
381	}
382}
383
384/// Decisions of winner & loser (and potentially the save)
385#[derive(Debug, Deserialize, PartialEq, Clone)]
386#[serde(rename_all = "camelCase")]
387#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
388pub struct Decisions {
389	pub winner: Option<NamedPerson>,
390	pub loser: Option<NamedPerson>,
391	pub save: Option<NamedPerson>,
392}
393
394/// Game records in stats like exit velocity, hit distance, etc.
395///
396/// Currently unable to actually get data for these though
397#[derive(Debug, Deserialize, PartialEq, Clone)]
398#[serde(rename_all = "camelCase")]
399#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
400pub struct GameStatLeaders {
401	#[doc(hidden)]
402	#[serde(rename = "hitDistance", default)]
403	pub __distance: IgnoredAny,
404	#[doc(hidden)]
405	#[serde(rename = "hitSpeed", default)]
406	pub __exit_velocity: IgnoredAny,
407	#[doc(hidden)]
408	#[serde(rename = "pitchSpeed", default)]
409	pub __velocity: IgnoredAny,
410}
411
412#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Display)]
413pub enum Base {
414	#[display("1B")]
415	First,
416	#[display("2B")]
417	Second,
418	#[display("3B")]
419	Third,
420	#[display("HP")]
421	Home,
422}
423
424impl<'de> Deserialize<'de> for Base {
425	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
426	where
427		D: Deserializer<'de>
428	{
429		struct BaseVisitor;
430
431		impl Visitor<'_> for BaseVisitor {
432			type Value = Base;
433
434			fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
435				write!(f, "a string or integer representing the base")
436			}
437
438			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
439			where
440				E: Error,
441			{
442				Ok(match v {
443					"1B" | "1" => Base::First,
444					"2B" | "2" => Base::Second,
445					"3B" | "3" => Base::Third,
446					"score" | "HP" | "4B" | "4" => Base::Home,
447					_ => return Err(E::unknown_variant(v, &["1B", "1", "2B" , "2", "3B", "3", "score", "HP", "4B", "4"]))
448				})
449			}
450
451			fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
452			where
453				E: Error,
454			{
455				Ok(match v {
456					1 => Base::First,
457					2 => Base::Second,
458					3 => Base::Third,
459					4 => Base::Home,
460					_ => return Err(E::unknown_variant("[a number]", &["1", "2", "3", "4"]))
461				})
462			}
463		}
464
465		deserializer.deserialize_any(BaseVisitor)
466	}
467}
468
469#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
470pub enum ContactHardness {
471	#[serde(rename = "soft")]
472	Soft,
473	#[serde(rename = "medium")]
474	Medium,
475	#[serde(rename = "hard")]
476	Hard,
477}
478
479pub(crate) fn deserialize_players_cache<'de, T: DeserializeOwned, D: Deserializer<'de>>(deserializer: D) -> Result<FxHashMap<PersonId, T>, D::Error> {
480	struct PlayersCacheVisitor<T2: DeserializeOwned>(PhantomData<T2>);
481
482	impl<'de2, T2: DeserializeOwned> serde::de::Visitor<'de2> for PlayersCacheVisitor<T2> {
483		type Value = FxHashMap<PersonId, T2>;
484
485		fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
486			formatter.write_str("a map")
487		}
488
489		fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
490		where
491			A: MapAccess<'de2>,
492		{
493			let mut values = FxHashMap::default();
494
495			while let Some((key, value)) = map.next_entry()? {
496				let key: String = key;
497				let key = PersonId::new(key.strip_prefix("ID").ok_or_else(|| A::Error::custom("invalid id format"))?.parse::<u32>().map_err(A::Error::custom)?);
498				values.insert(key, value);
499			}
500
501			Ok(values)
502		}
503	}
504
505	deserializer.deserialize_map(PlayersCacheVisitor::<T>(PhantomData))
506}
507
508/// Meant for active & live games, gives a streamable version of the plays in a game.
509///
510/// The [`PlayStream`] is meant to be for consistently polling the MLB API for live play-by-play updates.
511/// The list of events can be seen on [`PlayStreamEvent`]
512/// 
513/// ## Examples
514/// ```no_run
515/// PlayStream::new(/* game id */).run(|event: PlayStreamEvent, meta: &LiveFeedMetadata, data: &LiveFeedData| {
516///	    match event {
517///	        PlayStreamEvent::GameStart => println!("Game Start"),
518///	        PlayStreamEvent::StartPlay(play) => println!("{} vs. {}", play.matchup.batter.full_name, play.matchup.pitcher.full_name),
519///	        PlayStreamEvent::PlayEvent(play_event) => {
520///	            match play_event {
521///	                PlayEvent::Action { details, .. } => println!("{}", details.description),
522///	                PlayEvent::Pitch { details, common, .. } => println!("{} -> {}", details.call, common.count),
523///	                PlayEvent::Stepoff { .. } => println!("Stepoff"),
524///	                PlayEvent::NoPitch { .. } => println!("No Pitch"),
525///	                PlayEvent::Pickoff { .. } => println!("Pickoff"),
526///	            }
527///	        },
528///	        PlayStreamEvent::PlayEventReviewStart(review) => println!("PlayEventReviewStart; {}", review.review_type),
529///	        PlayStreamEvent::PlayEventReviewEnd(review) => println!("PlayEventReviewEnd; {}", review.review_type),
530///	        PlayStreamEvent::PlayReviewStart(review) => println!("PlayReviewStart; {}", review.review_type),
531///	        PlayStreamEvent::PlayReviewEnd(review) => println!("PlayReviewEnd; {}", review.review_type),
532///	        PlayStreamEvent::EndPlay(play) => println!("{}", play.result.completed_play_details.as_ref().expect("Completed play").description),
533///	        PlayStreamEvent::GameEnd(_, _, _, _) => println!("GameEnd"),
534///     }
535/// }).await?;
536/// ```
537#[derive(Debug)]
538pub struct PlayStream {
539	game_id: GameId,
540
541	current_play_idx: usize,
542	in_progress_current_play: bool,
543	current_play_review_idx: usize,
544	in_progress_current_play_review: bool,
545	
546	current_play_event_idx: usize,
547	current_play_event_review_idx: usize,
548	in_progress_current_play_event_review: bool,
549}
550
551impl PlayStream {
552	#[must_use]
553	pub fn new(game_id: impl Into<GameId>) -> Self {
554		Self {
555			game_id: game_id.into(),
556			
557			current_play_idx: 0,
558			in_progress_current_play: false,
559			current_play_review_idx: 0,
560			in_progress_current_play_review: false,
561			
562			current_play_event_idx: 0,
563			current_play_event_review_idx: 0,
564			in_progress_current_play_event_review: false,
565		}
566	}
567}
568
569/// An event in a game, such as the game starting, ending, a [`Play`] (At-Bat) starting, or a [`PlayEvent`] occuring, or a challenge on a play or play event.
570#[derive(Debug, PartialEq, Clone)]
571pub enum PlayStreamEvent<'a> {
572	/// Sent at the beginning of a game
573	GameStart,
574	
575	StartPlay(&'a Play),
576	PlayReviewStart(&'a ReviewData),
577	PlayReviewEnd(&'a ReviewData),
578	EndPlay(&'a Play),
579	
580	PlayEvent(&'a PlayEvent),
581	PlayEventReviewStart(&'a ReviewData),
582	PlayEventReviewEnd(&'a ReviewData),
583	
584	GameEnd(&'a Decisions, &'a Linescore, &'a Boxscore, &'a GameStatLeaders),
585}
586
587impl PlayStream {
588	/// Runs through plays until the game is over.
589	///
590	/// # Errors
591	/// See [`request::Error`]
592	pub async fn run<F: FnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData) -> Result<ControlFlow<()>, request::Error>>(self, f: F) -> Result<(), request::Error> {
593		self.run_custom_error::<request::Error, F>(f).await
594	}
595
596	/// Variant of the ``run`` function that allows for custom error types.
597	///
598	/// # Errors
599	/// See [`request::Error`]
600	pub async fn run_custom_error<E: From<request::Error>, F: FnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData) -> Result<ControlFlow<()>, E>>(mut self, mut f: F) -> Result<(), E> {
601		macro_rules! flow_try {
602			($($t:tt)*) => {
603				match ($($t)*)? {
604					ControlFlow::Continue(()) => {},
605					ControlFlow::Break(()) => return Ok(()),
606				}
607			};
608		}
609		
610		let mut feed = LiveFeedRequest::builder().id(self.game_id).build_and_get().await?;
611		
612		flow_try!(f(PlayStreamEvent::GameStart, &feed.meta, &feed.data));
613		
614		loop {
615		    let since_last_request = Instant::now();
616		    
617			let LiveFeedResponse { meta, data, live, .. } = &feed;
618			let LiveFeedLiveData { linescore, boxscore, decisions, leaders, plays } = live;
619			let mut plays = plays.iter().skip(self.current_play_idx);
620
621			if let Some(current_play) = plays.next() {
622				if !self.in_progress_current_play {
623					flow_try!(f(PlayStreamEvent::StartPlay(current_play), meta, data));
624				}
625
626				let mut play_events = current_play.play_events.iter().skip(self.current_play_event_idx);
627				if let Some(current_play_event) = play_events.next() {
628					flow_try!(f(PlayStreamEvent::PlayEvent(current_play_event), meta, data));
629
630					let mut reviews = current_play_event.reviews.iter().skip(self.current_play_event_review_idx);
631					if let Some(current_review) = reviews.next() {
632						if !self.in_progress_current_play_event_review {
633							flow_try!(f(PlayStreamEvent::PlayEventReviewStart(current_review), meta, data));
634						}
635						if !current_review.is_in_progress {
636							flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(current_review), meta, data));
637						}
638					}
639					for review in reviews {
640						flow_try!(f(PlayStreamEvent::PlayEventReviewStart(review), meta, data));
641						if !review.is_in_progress {
642							flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(review), meta, data));
643						}
644					}
645				}
646
647				for play_event in play_events {
648					flow_try!(f(PlayStreamEvent::PlayEvent(play_event), meta, data));
649					for review in &play_event.reviews {
650						flow_try!(f(PlayStreamEvent::PlayReviewStart(review), meta, data));
651						if !review.is_in_progress {
652							flow_try!(f(PlayStreamEvent::PlayReviewEnd(review), meta, data));
653						}
654					}
655				}
656
657				let mut reviews = current_play.reviews.iter().skip(self.current_play_review_idx);
658				if let Some(current_review) = reviews.next() {
659					if !self.in_progress_current_play_review {
660						flow_try!(f(PlayStreamEvent::PlayReviewStart(current_review), meta, data));
661					}
662
663					if !current_review.is_in_progress {
664						flow_try!(f(PlayStreamEvent::PlayReviewEnd(current_review), meta, data));
665					}
666				}
667				
668				for review in reviews {
669					flow_try!(f(PlayStreamEvent::PlayReviewStart(review), meta, data));
670					if !review.is_in_progress {
671						flow_try!(f(PlayStreamEvent::PlayReviewEnd(review), meta, data));
672					}
673				}
674
675				if current_play.about.is_complete {
676					flow_try!(f(PlayStreamEvent::EndPlay(current_play), meta, data));
677				}
678			}
679
680			for play in plays {
681				flow_try!(f(PlayStreamEvent::StartPlay(play), meta, data));
682				for play_event in &play.play_events {
683					flow_try!(f(PlayStreamEvent::PlayEvent(play_event), meta, data));
684					for review in &play_event.reviews {
685						flow_try!(f(PlayStreamEvent::PlayEventReviewStart(review), meta, data));
686						if !review.is_in_progress {
687							flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(review), meta, data));
688						}
689					}
690				}
691				if play.about.is_complete {
692					flow_try!(f(PlayStreamEvent::EndPlay(play), meta, data));
693				}
694			}
695			
696			if data.status.abstract_game_code.is_finished() && let Some(decisions) = decisions {
697				let _ = f(PlayStreamEvent::GameEnd(decisions, linescore, boxscore, leaders), meta, data)?;
698				return Ok(())
699			}
700
701			let latest_play = live.plays.last();
702
703			self.in_progress_current_play = latest_play.is_some_and(|play| !play.about.is_complete);
704			self.current_play_idx = if self.in_progress_current_play { live.plays.len() - 1 } else { live.plays.len() };
705
706			let current_play = live.plays.get(self.current_play_idx);
707			let current_play_event = current_play.and_then(|play| play.play_events.last());
708			let current_play_review = current_play.and_then(|play| play.reviews.last());
709			let current_play_event_review = current_play_event.and_then(|play_event| play_event.reviews.last());
710			
711			self.in_progress_current_play_review = current_play_review.is_some_and(|review| review.is_in_progress);
712			self.current_play_review_idx = current_play.map_or(0, |play| if self.in_progress_current_play_review { play.reviews.len() - 1 } else { play.reviews.len() });
713
714			self.current_play_event_idx = current_play.map_or(0, |play| play.play_events.len());
715
716			self.in_progress_current_play_event_review = current_play_event_review.is_some_and(|review| review.is_in_progress);
717			self.current_play_event_review_idx = current_play_event.map_or(0, |play_event| if self.in_progress_current_play_event_review { play_event.reviews.len() - 1 } else { play_event.reviews.len() });
718
719			let total_sleep_time = Duration::from_secs(meta.recommended_poll_rate as _);
720			drop(feed);
721			let remaining_sleep_time = total_sleep_time.saturating_sub(since_last_request.elapsed());
722			tokio::time::sleep(remaining_sleep_time).await;
723			
724		    feed = LiveFeedRequest::builder().id(self.game_id).build_and_get().await?;
725		}
726	}
727}
728
729#[cfg(test)]
730mod tests {
731    use std::ops::ControlFlow;
732    use crate::{cache::RequestableEntrypoint, game::{PlayEvent, PlayStream, PlayStreamEvent}};
733
734	#[tokio::test]
735	async fn test_play_stream() {
736		PlayStream::new(822_834).run(|event, _meta, _data| {
737			match event {
738				PlayStreamEvent::GameStart => println!("GameStart"),
739				PlayStreamEvent::StartPlay(play) => println!("PlayStart; {} vs. {}", play.matchup.batter.full_name, play.matchup.pitcher.full_name),
740				PlayStreamEvent::PlayEvent(play_event) => {
741					print!("PlayEvent; ");
742					match play_event {
743						PlayEvent::Action { details, .. } => println!("{}", details.description),
744						PlayEvent::Pitch { details, common, .. } => println!("{} -> {}", details.call, common.count),
745						PlayEvent::Stepoff { .. } => println!("Stepoff"),
746						PlayEvent::NoPitch { .. } => println!("No Pitch"),
747						PlayEvent::Pickoff { .. } => println!("Pickoff"),
748					}
749				},
750				PlayStreamEvent::PlayEventReviewStart(review) => println!("PlayEventReviewStart; {}", review.review_type),
751				PlayStreamEvent::PlayEventReviewEnd(review) => println!("PlayEventReviewEnd; {}", review.review_type),
752				PlayStreamEvent::PlayReviewStart(review) => println!("PlayReviewStart; {}", review.review_type),
753				PlayStreamEvent::PlayReviewEnd(review) => println!("PlayReviewEnd; {}", review.review_type),
754				PlayStreamEvent::EndPlay(play) => println!("PlayEnd; {}", play.result.completed_play_details.as_ref().expect("Completed play").description),
755				PlayStreamEvent::GameEnd(_, _, _, _) => println!("GameEnd"),
756			}
757			Ok(ControlFlow::Continue(()))
758		}).await.unwrap();
759	}
760}