Skip to main content

tank01_data/
poll.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    sync::Arc,
4    time::Duration,
5};
6
7use ::time::Date;
8use nfl_model::{
9    LiveGame, LiveGamePhase, LiveGameSnapshot, LiveScoreProvider, LiveScoreboard, LiveSlate,
10    ProviderOutcome, ProviderResponse,
11};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use tokio::{
15    sync::{Mutex, mpsc},
16    task::JoinSet,
17    time::{self, MissedTickBehavior},
18};
19
20use crate::normalize;
21
22pub(crate) const POLL_INTERVAL_SECONDS: u64 = 20;
23pub(crate) const FINAL_FOLLOWUP_INTERVAL_SECONDS: u64 = 300;
24pub(crate) const PLAY_BY_PLAY_INTERVAL: u64 = 5;
25pub(crate) const EVERY_FIFTH_PLAY_BY_PLAY: bool = PLAY_BY_PLAY_INTERVAL == 5;
26const POLL_INTERVAL: Duration = Duration::from_secs(POLL_INTERVAL_SECONDS);
27const FINAL_FOLLOWUP_INTERVAL: Duration = Duration::from_secs(FINAL_FOLLOWUP_INTERVAL_SECONDS);
28pub(crate) const FINAL_FOLLOWUPS: u32 = 3;
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct PollRequest {
32    pub endpoint: String,
33    pub query: BTreeMap<String, String>,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum CompletionReason {
39    FinalFollowupsComplete,
40}
41
42#[allow(clippy::large_enum_variant)]
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub enum PollEvent {
45    Scoreboard {
46        sequence: u64,
47        request: PollRequest,
48        response: ProviderResponse<LiveScoreboard>,
49    },
50    BoxScore {
51        sequence: u64,
52        game: LiveGame,
53        request: PollRequest,
54        play_by_play: bool,
55        changed: bool,
56        response: ProviderResponse<LiveGameSnapshot>,
57    },
58    RunFinished {
59        sequence: u64,
60        reason: CompletionReason,
61    },
62}
63
64#[derive(Debug, thiserror::Error)]
65pub enum PollerError {
66    #[error("invalid live slate: {0}")]
67    InvalidSlate(String),
68    #[error("poll event sink is closed")]
69    SinkClosed,
70    #[error("poll task failed to join: {0}")]
71    TaskJoin(String),
72}
73
74#[derive(Clone)]
75struct EventSink {
76    sender: mpsc::Sender<PollEvent>,
77    next_sequence: Arc<Mutex<u64>>,
78}
79
80impl EventSink {
81    fn new(sender: mpsc::Sender<PollEvent>) -> Self {
82        Self {
83            sender,
84            next_sequence: Arc::new(Mutex::new(1)),
85        }
86    }
87
88    fn is_closed(&self) -> bool {
89        self.sender.is_closed()
90    }
91
92    async fn closed(&self) {
93        self.sender.closed().await;
94    }
95
96    async fn send(&self, event: PollEvent) -> Result<(), PollerError> {
97        if self.sender.is_closed() {
98            return Err(PollerError::SinkClosed);
99        }
100        let mut next_sequence = self.next_sequence.lock().await;
101        if self.sender.is_closed() {
102            return Err(PollerError::SinkClosed);
103        }
104        let sequence = *next_sequence;
105        *next_sequence += 1;
106        self.sender
107            .send(with_sequence(event, sequence))
108            .await
109            .map_err(|_| PollerError::SinkClosed)
110    }
111}
112
113fn with_sequence(event: PollEvent, sequence: u64) -> PollEvent {
114    match event {
115        PollEvent::Scoreboard {
116            request, response, ..
117        } => PollEvent::Scoreboard {
118            sequence,
119            request,
120            response,
121        },
122        PollEvent::BoxScore {
123            game,
124            request,
125            play_by_play,
126            changed,
127            response,
128            ..
129        } => PollEvent::BoxScore {
130            sequence,
131            game,
132            request,
133            play_by_play,
134            changed,
135            response,
136        },
137        PollEvent::RunFinished { reason, .. } => PollEvent::RunFinished { sequence, reason },
138    }
139}
140
141pub struct SlatePoller<P> {
142    provider: Arc<P>,
143    slate: LiveSlate,
144    sink: EventSink,
145}
146
147impl<P> SlatePoller<P>
148where
149    P: LiveScoreProvider + 'static,
150{
151    pub fn new(
152        provider: P,
153        slate: LiveSlate,
154        sender: mpsc::Sender<PollEvent>,
155    ) -> Result<Self, PollerError> {
156        validate_slate(&slate)?;
157        Ok(Self {
158            provider: Arc::new(provider),
159            slate,
160            sink: EventSink::new(sender),
161        })
162    }
163
164    pub async fn run(self) -> Result<(), PollerError> {
165        let Self {
166            provider,
167            slate,
168            sink,
169        } = self;
170        if sink.is_closed() {
171            return Err(PollerError::SinkClosed);
172        }
173        let mut runners = JoinSet::new();
174        let mut update_senders = Vec::with_capacity(slate.games.len());
175        for game in slate.games.iter().cloned() {
176            let (updates, receiver) = mpsc::unbounded_channel();
177            update_senders.push(updates);
178            let provider = Arc::clone(&provider);
179            let sink = sink.clone();
180            runners.spawn(run_game(provider, game, receiver, sink));
181        }
182
183        let mut scoreboard_interval = time::interval(POLL_INTERVAL);
184        scoreboard_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
185        let _ = scoreboard_interval.tick().await;
186
187        let initial = scoreboard_request(&provider, &sink, slate.date).await?;
188        emit_scoreboard(&sink, slate.date, initial, &slate.games, &update_senders).await?;
189
190        loop {
191            if runners.is_empty() {
192                sink.send(PollEvent::RunFinished {
193                    sequence: 0,
194                    reason: CompletionReason::FinalFollowupsComplete,
195                })
196                .await?;
197                return Ok(());
198            }
199            tokio::select! {
200                biased;
201                joined = runners.join_next() => {
202                    match joined {
203                        Some(Ok(Ok(()))) => {}
204                        Some(Ok(Err(error))) => {
205                            return Err(error);
206                        }
207                        Some(Err(error)) => {
208                            return Err(PollerError::TaskJoin(error.to_string()));
209                        }
210                        None => unreachable!("empty runner set handled above"),
211                    }
212                }
213                _ = scoreboard_interval.tick() => {
214                    if sink.is_closed() {
215                        return Err(PollerError::SinkClosed);
216                    }
217                    let response = scoreboard_request(&provider, &sink, slate.date).await?;
218                    emit_scoreboard(
219                        &sink,
220                        slate.date,
221                        response,
222                        &slate.games,
223                        &update_senders,
224                    )
225                    .await?;
226                }
227            }
228        }
229    }
230}
231
232async fn scoreboard_request<P>(
233    provider: &Arc<P>,
234    sink: &EventSink,
235    date: Date,
236) -> Result<ProviderResponse<LiveScoreboard>, PollerError>
237where
238    P: LiveScoreProvider + 'static,
239{
240    if sink.is_closed() {
241        return Err(PollerError::SinkClosed);
242    }
243    tokio::select! {
244        _ = sink.closed() => Err(PollerError::SinkClosed),
245        response = provider.scoreboard(date) => Ok(response),
246    }
247}
248
249async fn box_score_request<P>(
250    provider: &Arc<P>,
251    sink: &EventSink,
252    game: &LiveGame,
253    play_by_play: bool,
254) -> Result<ProviderResponse<LiveGameSnapshot>, PollerError>
255where
256    P: LiveScoreProvider + 'static,
257{
258    if sink.is_closed() {
259        return Err(PollerError::SinkClosed);
260    }
261    tokio::select! {
262        _ = sink.closed() => Err(PollerError::SinkClosed),
263        response = provider.box_score(game, play_by_play) => Ok(response),
264    }
265}
266
267async fn emit_scoreboard(
268    sink: &EventSink,
269    date: Date,
270    response: ProviderResponse<LiveScoreboard>,
271    games: &[LiveGame],
272    update_senders: &[mpsc::UnboundedSender<ScoreboardUpdate>],
273) -> Result<(), PollerError> {
274    let request = PollRequest {
275        endpoint: "getNFLScoresOnly".into(),
276        query: BTreeMap::from([(String::from("gameDate"), normalize::compact_date(date))]),
277    };
278    let updates = scoreboard_updates(&response, games);
279    sink.send(PollEvent::Scoreboard {
280        sequence: 0,
281        request,
282        response,
283    })
284    .await?;
285    for (index, update) in updates {
286        let _ = update_senders[index].send(update);
287    }
288    Ok(())
289}
290pub(crate) fn box_score_query(game: &LiveGame, play_by_play: bool) -> BTreeMap<String, String> {
291    let mut query = BTreeMap::from([(String::from("gameID"), game.tank01_game_id.clone())]);
292    if play_by_play {
293        query.insert(String::from("playByPlay"), String::from("true"));
294    }
295    query
296}
297
298fn scoreboard_updates(
299    response: &ProviderResponse<LiveScoreboard>,
300    games: &[LiveGame],
301) -> Vec<(usize, ScoreboardUpdate)> {
302    let ProviderOutcome::Value(scoreboard) = &response.outcome else {
303        return Vec::new();
304    };
305    let mut by_tank01_game_id = BTreeMap::new();
306    for game in &scoreboard.games {
307        by_tank01_game_id.insert(game.tank01_game_id.as_str(), game.phase);
308    }
309    games
310        .iter()
311        .enumerate()
312        .filter_map(|(index, game)| {
313            by_tank01_game_id
314                .get(game.tank01_game_id.as_str())
315                .copied()
316                .map(|phase| (index, ScoreboardUpdate { phase }))
317        })
318        .collect()
319}
320
321#[derive(Debug, Clone, Copy)]
322struct ScoreboardUpdate {
323    phase: LiveGamePhase,
324}
325
326async fn run_game<P>(
327    provider: Arc<P>,
328    game: LiveGame,
329    mut updates: mpsc::UnboundedReceiver<ScoreboardUpdate>,
330    sink: EventSink,
331) -> Result<(), PollerError>
332where
333    P: LiveScoreProvider + 'static,
334{
335    let mut attempts = 0u64;
336    let mut last_projection: Option<Value> = None;
337    let mut active = false;
338    let mut poll_interval: Option<time::Interval> = None;
339
340    loop {
341        if sink.is_closed() {
342            return Err(PollerError::SinkClosed);
343        }
344        if let Some(interval) = &mut poll_interval {
345            tokio::select! {
346                update = updates.recv() => {
347                    match update {
348                        Some(update) if update.phase == LiveGamePhase::InProgress => {
349                            active = true;
350                        }
351                        Some(update) if update.phase == LiveGamePhase::Final => {
352                            request_box(
353                                &provider,
354                                &game,
355                                &sink,
356                                &mut attempts,
357                                &mut last_projection,
358                                false,
359                            )
360                            .await?;
361                            run_final_followups(
362                                &provider,
363                                &game,
364                                &sink,
365                                &mut attempts,
366                                &mut last_projection,
367                            )
368                            .await?;
369                            return Ok(());
370                        }
371                        Some(_) => {}
372                        None => return Err(PollerError::SinkClosed),
373                    }
374                }
375                _ = interval.tick(), if active => {
376                    let result = request_box(
377                        &provider,
378                        &game,
379                        &sink,
380                        &mut attempts,
381                        &mut last_projection,
382                        false,
383                    )
384                    .await?;
385                    if result.successful_final {
386                        run_final_followups(
387                            &provider,
388                            &game,
389                            &sink,
390                            &mut attempts,
391                            &mut last_projection,
392                        )
393                        .await?;
394                        return Ok(());
395                    }
396                }
397            }
398        } else {
399            match updates.recv().await {
400                Some(update) if update.phase == LiveGamePhase::InProgress => {
401                    active = true;
402                    let mut interval =
403                        time::interval_at(time::Instant::now() + POLL_INTERVAL, POLL_INTERVAL);
404                    interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
405                    let result = request_box(
406                        &provider,
407                        &game,
408                        &sink,
409                        &mut attempts,
410                        &mut last_projection,
411                        false,
412                    )
413                    .await?;
414                    if result.successful_final {
415                        run_final_followups(
416                            &provider,
417                            &game,
418                            &sink,
419                            &mut attempts,
420                            &mut last_projection,
421                        )
422                        .await?;
423                        return Ok(());
424                    }
425                    poll_interval = Some(interval);
426                }
427                Some(update) if update.phase == LiveGamePhase::Final => {
428                    request_box(
429                        &provider,
430                        &game,
431                        &sink,
432                        &mut attempts,
433                        &mut last_projection,
434                        false,
435                    )
436                    .await?;
437                    run_final_followups(
438                        &provider,
439                        &game,
440                        &sink,
441                        &mut attempts,
442                        &mut last_projection,
443                    )
444                    .await?;
445                    return Ok(());
446                }
447                Some(_) => {}
448                None => return Err(PollerError::SinkClosed),
449            }
450        }
451    }
452}
453
454struct BoxRequestResult {
455    successful_final: bool,
456}
457
458async fn request_box<P>(
459    provider: &Arc<P>,
460    game: &LiveGame,
461    sink: &EventSink,
462    attempts: &mut u64,
463    last_projection: &mut Option<Value>,
464    forced_play_by_play: bool,
465) -> Result<BoxRequestResult, PollerError>
466where
467    P: LiveScoreProvider + 'static,
468{
469    if sink.is_closed() {
470        return Err(PollerError::SinkClosed);
471    }
472    *attempts += 1;
473    let play_by_play = forced_play_by_play || (*attempts).is_multiple_of(PLAY_BY_PLAY_INTERVAL);
474    let response = box_score_request(provider, sink, game, play_by_play).await?;
475    let successful_final = matches!(
476        &response.outcome,
477        ProviderOutcome::Value(snapshot) if snapshot.phase == LiveGamePhase::Final
478    );
479    let (changed, next_projection) = match &response.outcome {
480        ProviderOutcome::Value(snapshot) => {
481            let projection = normalize::response_projection(&response, snapshot);
482            let changed = last_projection.as_ref() != Some(&projection);
483            (changed, Some(projection))
484        }
485        ProviderOutcome::Pregame { .. } | ProviderOutcome::Error(_) => (false, None),
486    };
487    let request = PollRequest {
488        endpoint: "getNFLBoxScore".into(),
489        query: box_score_query(game, play_by_play),
490    };
491    sink.send(PollEvent::BoxScore {
492        sequence: 0,
493        game: game.clone(),
494        request,
495        play_by_play,
496        changed,
497        response,
498    })
499    .await?;
500    if let Some(projection) = next_projection {
501        *last_projection = Some(projection);
502    }
503    Ok(BoxRequestResult { successful_final })
504}
505
506async fn run_final_followups<P>(
507    provider: &Arc<P>,
508    game: &LiveGame,
509    sink: &EventSink,
510    attempts: &mut u64,
511    last_projection: &mut Option<Value>,
512) -> Result<(), PollerError>
513where
514    P: LiveScoreProvider + 'static,
515{
516    for _ in 0..FINAL_FOLLOWUPS {
517        wait_or_sink_closed(sink, FINAL_FOLLOWUP_INTERVAL).await?;
518        request_box(provider, game, sink, attempts, last_projection, true).await?;
519    }
520    Ok(())
521}
522
523async fn wait_or_sink_closed(sink: &EventSink, duration: Duration) -> Result<(), PollerError> {
524    tokio::select! {
525        _ = time::sleep(duration) => Ok(()),
526        _ = sink.closed() => Err(PollerError::SinkClosed),
527    }
528}
529
530fn validate_slate(slate: &LiveSlate) -> Result<(), PollerError> {
531    if slate.games.is_empty() {
532        return Err(PollerError::InvalidSlate("slate has no games".into()));
533    }
534    let mut gsis_ids = BTreeSet::new();
535    let mut tank01_game_ids = BTreeSet::new();
536    let mut safe_names = BTreeMap::new();
537    for game in &slate.games {
538        if game.game_id.is_empty() {
539            return Err(PollerError::InvalidSlate(
540                "game has an empty GSIS game id".into(),
541            ));
542        }
543        if game.tank01_game_id.is_empty() {
544            return Err(PollerError::InvalidSlate(
545                "game has an empty Tank01 game id".into(),
546            ));
547        }
548        if !gsis_ids.insert(&game.game_id) {
549            return Err(PollerError::InvalidSlate(format!(
550                "duplicate GSIS game id {:?}",
551                game.game_id
552            )));
553        }
554        if !tank01_game_ids.insert(&game.tank01_game_id) {
555            return Err(PollerError::InvalidSlate(format!(
556                "duplicate Tank01 game id {:?}",
557                game.tank01_game_id
558            )));
559        }
560        let safe_name = safe_tank01_game_id(&game.tank01_game_id)?;
561        if let Some(previous) = safe_names.insert(safe_name.clone(), game.tank01_game_id.clone()) {
562            return Err(PollerError::InvalidSlate(format!(
563                "Tank01 game ids {:?} and {:?} collide as {safe_name:?}",
564                previous, game.tank01_game_id
565            )));
566        }
567    }
568    Ok(())
569}
570
571pub(crate) fn safe_tank01_game_id(tank01_game_id: &str) -> Result<String, PollerError> {
572    let safe = tank01_game_id.replace('@', "_at_");
573    if safe.is_empty()
574        || !safe
575            .chars()
576            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
577    {
578        return Err(PollerError::InvalidSlate(format!(
579            "Tank01 game id {tank01_game_id:?} cannot be used as a safe file name"
580        )));
581    }
582    Ok(safe)
583}
584
585#[cfg(test)]
586mod tests {
587    use std::sync::{
588        Arc,
589        atomic::{AtomicUsize, Ordering},
590    };
591
592    use super::*;
593    use ::time::{
594        OffsetDateTime,
595        macros::{date, datetime},
596    };
597    use nfl_model::{
598        EspnPlayerId, LiveGamePhase, LiveGameSnapshot, LivePlayerStats, LiveProviderError,
599        LiveScoreboardGame, LiveTeamStats, RawBody, Season, TeamAbbr, Week,
600    };
601    use serde_json::json;
602
603    fn game(id: &str, tank01_game_id: &str, home: &str, away: &str) -> LiveGame {
604        LiveGame {
605            game_id: id.into(),
606            tank01_game_id: tank01_game_id.into(),
607            season_week: nfl_model::SeasonWeek {
608                season: Season(2026),
609                week: Week(1),
610            },
611            kickoff: Some(datetime!(2026-09-10 20:35:00 -04:00)),
612            home_team: home.parse().unwrap(),
613            away_team: away.parse().unwrap(),
614        }
615    }
616
617    fn response<T>(outcome: ProviderOutcome<T>, raw_body: Option<RawBody>) -> ProviderResponse<T> {
618        let now = OffsetDateTime::now_utc();
619        ProviderResponse {
620            requested_at: now,
621            received_at: now,
622            elapsed_ms: 1,
623            http_status: Some(200),
624            headers: BTreeMap::new(),
625            raw_body,
626            outcome,
627        }
628    }
629
630    #[test]
631    fn validates_nonempty_unique_and_safe_game_ids() {
632        let (sender, _receiver) = mpsc::channel(1);
633        let provider = FakeProvider::default();
634        let slate = LiveSlate {
635            date: date!(2026 - 09 - 10),
636            games: vec![game("", "A", "LAR", "SF")],
637        };
638        assert!(matches!(
639            SlatePoller::new(provider, slate, sender),
640            Err(PollerError::InvalidSlate(_))
641        ));
642        assert_eq!(
643            safe_tank01_game_id("20260910_SF@LAR").unwrap(),
644            "20260910_SF_at_LAR"
645        );
646        assert!(safe_tank01_game_id("bad/path").is_err());
647    }
648
649    #[derive(Default)]
650    struct FakeProvider {
651        calls: AtomicUsize,
652    }
653
654    impl LiveScoreProvider for FakeProvider {
655        async fn scoreboard(&self, _date: Date) -> ProviderResponse<LiveScoreboard> {
656            self.calls.fetch_add(1, Ordering::SeqCst);
657            response(
658                ProviderOutcome::Value(LiveScoreboard { games: vec![] }),
659                Some(RawBody::Json(json!({"games": []}))),
660            )
661        }
662
663        async fn box_score(
664            &self,
665            game: &LiveGame,
666            _play_by_play: bool,
667        ) -> ProviderResponse<LiveGameSnapshot> {
668            response(
669                ProviderOutcome::Value(LiveGameSnapshot {
670                    game: game.clone(),
671                    observed_at: OffsetDateTime::now_utc(),
672                    phase: LiveGamePhase::InProgress,
673                    period: Some("1".into()),
674                    clock: Some("10:00".into()),
675                    home_score: Some(0),
676                    away_score: Some(0),
677                    players: Some(vec![LivePlayerStats {
678                        espn_id: Some(EspnPlayerId("1".into())),
679                        name: Some("Player".into()),
680                        team: Some(game.home_team),
681                        position: Some("QB".into()),
682                        opponent: Some(game.away_team),
683                        completions: 0,
684                        attempts: 0,
685                        passing_tds: 0,
686                        passing_interceptions: 0,
687                        rushing_attempts: 0,
688                        rushing_tds: 0,
689                        targets: 0,
690                        receptions: 0,
691                        receiving_tds: 0,
692                        fumbles_lost: 0,
693                        two_point_conversions: 0,
694                        special_teams_tds: 0,
695                        fumble_recovery_tds: 0,
696                        passing_yards: 0,
697                        rushing_yards: 0,
698                        receiving_yards: 0,
699                    }]),
700                    defenses: Some(vec![LiveTeamStats {
701                        team: game.home_team,
702                        opponent: game.away_team,
703                        sacks: 0,
704                        interceptions: 0,
705                        fumble_recoveries: 0,
706                        safeties: 0,
707                        touchdowns: 0,
708                        blocked_kicks: 0,
709                        conversion_returns: 0,
710                        points_allowed: Some(0),
711                        dst_present: true,
712                        team_stats_present: true,
713                    }]),
714                }),
715                Some(RawBody::Json(
716                    json!({"playerStats": {"1": {"rushingYards": 0}}}),
717                )),
718            )
719        }
720    }
721    #[derive(Debug, Clone)]
722    struct RecordedCall {
723        tank01_game_id: String,
724        attempt: u64,
725        play_by_play: bool,
726    }
727
728    #[derive(Clone, Default)]
729    struct LifecycleState {
730        calls: Arc<Mutex<Vec<RecordedCall>>>,
731        in_flight: Arc<AtomicUsize>,
732        max_in_flight: Arc<AtomicUsize>,
733        scoreboards: Arc<AtomicUsize>,
734    }
735
736    impl LifecycleState {
737        async fn record(&self, tank01_game_id: &str, play_by_play: bool) -> u64 {
738            let mut calls = self.calls.lock().await;
739            let attempt = calls
740                .iter()
741                .filter(|call| call.tank01_game_id == tank01_game_id)
742                .count() as u64
743                + 1;
744            calls.push(RecordedCall {
745                tank01_game_id: tank01_game_id.into(),
746                attempt,
747                play_by_play,
748            });
749            attempt
750        }
751
752        fn enter(&self) {
753            let current = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
754            self.max_in_flight.fetch_max(current, Ordering::SeqCst);
755        }
756
757        fn leave(&self) {
758            self.in_flight.fetch_sub(1, Ordering::SeqCst);
759        }
760    }
761
762    #[derive(Clone, Default)]
763    struct LifecycleProvider {
764        state: LifecycleState,
765    }
766
767    impl LiveScoreProvider for LifecycleProvider {
768        async fn scoreboard(&self, _date: Date) -> ProviderResponse<LiveScoreboard> {
769            let scoreboard_number = self.state.scoreboards.fetch_add(1, Ordering::SeqCst) + 1;
770            self.state.enter();
771            tokio::task::yield_now().await;
772            self.state.leave();
773            response(
774                ProviderOutcome::Value(LiveScoreboard {
775                    games: vec![
776                        LiveScoreboardGame {
777                            tank01_game_id: "20260910_SF@LAR".into(),
778                            phase: LiveGamePhase::InProgress,
779                            period: Some("1".into()),
780                            clock: Some("10:00".into()),
781                            home_team: TeamAbbr::LA,
782                            away_team: TeamAbbr::SF,
783                            home_score: Some(0),
784                            away_score: Some(0),
785                        },
786                        LiveScoreboardGame {
787                            tank01_game_id: "20260910_NE@NYJ".into(),
788                            phase: LiveGamePhase::InProgress,
789                            period: Some("1".into()),
790                            clock: Some("10:00".into()),
791                            home_team: TeamAbbr::NYJ,
792                            away_team: TeamAbbr::NE,
793                            home_score: Some(0),
794                            away_score: Some(0),
795                        },
796                        LiveScoreboardGame {
797                            tank01_game_id: "20260910_DAL@NYG".into(),
798                            phase: if scoreboard_number == 1 {
799                                LiveGamePhase::Scheduled
800                            } else {
801                                LiveGamePhase::Final
802                            },
803                            period: None,
804                            clock: None,
805                            home_team: TeamAbbr::NYG,
806                            away_team: TeamAbbr::DAL,
807                            home_score: None,
808                            away_score: None,
809                        },
810                    ],
811                }),
812                Some(RawBody::Json(json!({"games": []}))),
813            )
814        }
815
816        async fn box_score(
817            &self,
818            game: &LiveGame,
819            play_by_play: bool,
820        ) -> ProviderResponse<LiveGameSnapshot> {
821            let attempt = self.state.record(&game.tank01_game_id, play_by_play).await;
822            self.state.enter();
823            tokio::task::yield_now().await;
824            self.state.leave();
825            if attempt == 5 {
826                return response(
827                    ProviderOutcome::Error(LiveProviderError::Transport {
828                        message: "simulated PBP failure".into(),
829                    }),
830                    None,
831                );
832            }
833            let phase = if game.tank01_game_id == "20260910_DAL@NYG" || attempt >= 7 {
834                LiveGamePhase::Final
835            } else {
836                LiveGamePhase::InProgress
837            };
838            response(
839                ProviderOutcome::Value(LiveGameSnapshot {
840                    game: game.clone(),
841                    observed_at: OffsetDateTime::now_utc(),
842                    phase,
843                    period: Some("1".into()),
844                    clock: Some("10:00".into()),
845                    home_score: Some(7),
846                    away_score: Some(3),
847                    players: None,
848                    defenses: None,
849                }),
850                Some(RawBody::Json(json!({
851                    "gameID": game.tank01_game_id,
852                    "gameStatusCode": if phase == LiveGamePhase::Final { "3" } else { "1" },
853                    "attempt": attempt,
854                }))),
855            )
856        }
857    }
858
859    #[tokio::test]
860    async fn stops_before_provider_requests_when_sink_is_closed() {
861        let provider = FakeProvider::default();
862        let slate = LiveSlate {
863            date: date!(2026 - 09 - 10),
864            games: vec![game("A", "20260910_SF@LAR", "LAR", "SF")],
865        };
866        let (sender, receiver) = mpsc::channel(1);
867        drop(receiver);
868
869        let poller = SlatePoller::new(provider, slate, sender).unwrap();
870        assert!(matches!(poller.run().await, Err(PollerError::SinkClosed)));
871    }
872
873    #[tokio::test(start_paused = true)]
874    async fn runs_active_games_concurrently_through_final_followups() {
875        let provider = LifecycleProvider::default();
876        let state = provider.state.clone();
877        let slate = LiveSlate {
878            date: date!(2026 - 09 - 10),
879            games: vec![
880                game("A", "20260910_SF@LAR", "LAR", "SF"),
881                game("B", "20260910_NE@NYJ", "NYJ", "NE"),
882                game("C", "20260910_DAL@NYG", "NYG", "DAL"),
883            ],
884        };
885        let (sender, mut receiver) = mpsc::channel(512);
886        let poller = SlatePoller::new(provider, slate, sender).unwrap();
887        let mut run = Box::pin(poller.run());
888        let mut run_result = None;
889        for _ in 0..100 {
890            tokio::select! {
891                result = &mut run => {
892                    run_result = Some(result);
893                    break;
894                }
895                _ = tokio::task::yield_now() => {}
896            }
897            time::advance(POLL_INTERVAL).await;
898        }
899        if run_result.is_none() {
900            for _ in 0..10 {
901                tokio::select! {
902                    result = &mut run => {
903                        run_result = Some(result);
904                        break;
905                    }
906                    _ = tokio::task::yield_now() => {}
907                }
908            }
909        }
910        assert!(
911            run_result.is_some(),
912            "poller did not finish in virtual time: {:?}",
913            state.calls.lock().await
914        );
915        assert!(matches!(run_result.unwrap(), Ok(())));
916
917        let mut events = Vec::new();
918        while let Some(event) = receiver.recv().await {
919            events.push(event);
920        }
921
922        assert!(matches!(
923            events.first(),
924            Some(PollEvent::Scoreboard { sequence: 1, .. })
925        ));
926        assert!(matches!(
927            events.last(),
928            Some(PollEvent::RunFinished {
929                reason: CompletionReason::FinalFollowupsComplete,
930                ..
931            })
932        ));
933        for (index, event) in events.iter().enumerate() {
934            let sequence = match event {
935                PollEvent::Scoreboard { sequence, .. }
936                | PollEvent::BoxScore { sequence, .. }
937                | PollEvent::RunFinished { sequence, .. } => *sequence,
938            };
939            assert_eq!(sequence, index as u64 + 1);
940        }
941
942        let calls = state.calls.lock().await.clone();
943        assert!(state.max_in_flight.load(Ordering::SeqCst) >= 2);
944        let scoreboard_phases = events
945            .iter()
946            .filter_map(|event| match event {
947                PollEvent::Scoreboard { response, .. } => match &response.outcome {
948                    ProviderOutcome::Value(scoreboard) => scoreboard
949                        .games
950                        .iter()
951                        .find(|game| game.tank01_game_id == "20260910_DAL@NYG")
952                        .map(|game| game.phase),
953                    _ => None,
954                },
955                _ => None,
956            })
957            .collect::<Vec<_>>();
958        assert_eq!(scoreboard_phases[0], LiveGamePhase::Scheduled);
959        assert_eq!(scoreboard_phases[1], LiveGamePhase::Final);
960        let second_scoreboard_position = events
961            .iter()
962            .enumerate()
963            .filter(|(_, event)| matches!(event, PollEvent::Scoreboard { .. }))
964            .nth(1)
965            .map(|(index, _)| index)
966            .unwrap();
967        let scheduled_game_box_position = events
968            .iter()
969            .position(|event| {
970                matches!(
971                    event,
972                    PollEvent::BoxScore { game, .. }
973                        if game.tank01_game_id == "20260910_DAL@NYG"
974                )
975            })
976            .unwrap();
977        assert!(scheduled_game_box_position > second_scoreboard_position);
978        let scheduled_game_calls = calls
979            .iter()
980            .filter(|call| call.tank01_game_id == "20260910_DAL@NYG")
981            .collect::<Vec<_>>();
982        assert_eq!(scheduled_game_calls.len(), 4);
983        assert_eq!(
984            scheduled_game_calls
985                .iter()
986                .map(|call| call.play_by_play)
987                .collect::<Vec<_>>(),
988            vec![false, true, true, true]
989        );
990        for tank01_game_id in ["20260910_SF@LAR", "20260910_NE@NYJ"] {
991            let game_calls = calls
992                .iter()
993                .filter(|call| call.tank01_game_id == tank01_game_id)
994                .collect::<Vec<_>>();
995            assert_eq!(game_calls.len(), 10);
996            assert_eq!(
997                game_calls
998                    .iter()
999                    .filter(|call| call.play_by_play)
1000                    .map(|call| call.attempt)
1001                    .collect::<Vec<_>>(),
1002                vec![5, 8, 9, 10]
1003            );
1004        }
1005        assert_eq!(
1006            events
1007                .iter()
1008                .filter(|event| matches!(
1009                    event,
1010                    PollEvent::BoxScore { game, .. }
1011                        if game.tank01_game_id == "20260910_SF@LAR"
1012                ))
1013                .count(),
1014            10
1015        );
1016        assert_eq!(
1017            events
1018                .iter()
1019                .filter(|event| matches!(
1020                    event,
1021                    PollEvent::BoxScore { game, .. }
1022                        if game.tank01_game_id == "20260910_NE@NYJ"
1023                ))
1024                .count(),
1025            10
1026        );
1027        assert_eq!(
1028            events
1029                .iter()
1030                .filter(|event| matches!(
1031                    event,
1032                    PollEvent::BoxScore {
1033                        response: ProviderResponse {
1034                            outcome: ProviderOutcome::Error(LiveProviderError::Transport { .. }),
1035                            ..
1036                        },
1037                        play_by_play: true,
1038                        ..
1039                    }
1040                ))
1041                .count(),
1042            2
1043        );
1044        assert_eq!(
1045            events
1046                .iter()
1047                .filter(|event| matches!(
1048                    event,
1049                    PollEvent::BoxScore {
1050                        play_by_play: false,
1051                        response: ProviderResponse {
1052                            outcome: ProviderOutcome::Value(snapshot),
1053                            ..
1054                        },
1055                        ..
1056                    } if snapshot.phase == LiveGamePhase::Final
1057                ))
1058                .count(),
1059            3
1060        );
1061    }
1062}