Skip to main content

sunday_slate/live/
mod.rs

1use crate::{AppError, AppState};
2use nfl_data::{LiveGame, Snapshot};
3use std::collections::HashMap;
4use time::OffsetDateTime;
5#[cfg(test)]
6use time::macros::datetime;
7mod coordinator;
8pub(crate) mod dev_feed;
9pub mod identity;
10mod snapshot;
11
12use std::collections::BTreeMap;
13use std::sync::{Arc, Mutex};
14
15use nfl_data::{Game, LiveGamePhase, TeamAbbr};
16use tokio::sync::watch;
17
18use crate::live::identity::LiveIdentityIndex;
19use crate::live::snapshot::SnapshotReducer;
20use nfl_data::scoring::WeekStats;
21use nfl_data::slates::SlateId;
22
23pub(crate) use coordinator::run_coordinator;
24pub use snapshot::{
25    LINEUP_REGULATION_MINUTES, LiveGameState, lineup_minutes_remaining, live_game,
26    score_live_lineup, score_live_slot, tank01_game_id,
27};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum Coverage {
31    Complete,
32    Partial,
33    #[default]
34    Unavailable,
35}
36
37impl Coverage {
38    pub fn is_complete(self) -> bool {
39        self == Self::Complete
40    }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct LiveTotal {
45    pub points: Option<f64>,
46    pub coverage: Coverage,
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct LiveSlotStatus {
51    pub total: LiveTotal,
52    pub phase: Option<LiveGamePhase>,
53    pub period: Option<String>,
54    pub clock: Option<String>,
55    pub stale: bool,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum LiveError {
60    Feed,
61    Identity,
62}
63
64#[derive(Debug, Clone)]
65pub struct LiveContestSnapshot {
66    pub contest: SlateId,
67    pub games: Vec<Game>,
68    pub stats: WeekStats,
69    pub game_states: HashMap<String, LiveGameState>,
70    pub identity: Arc<LiveIdentityIndex>,
71    pub identity_outcomes: BTreeMap<String, identity::IdentityMatch>,
72    pub latest_error: Option<LiveError>,
73    pub revision: u64,
74}
75
76impl LiveContestSnapshot {
77    pub fn phase(&self) -> Option<LiveGamePhase> {
78        self.game_states
79            .values()
80            .map(|state| state.phase)
81            .max_by_key(|phase| match phase {
82                LiveGamePhase::Scheduled => 0,
83                LiveGamePhase::Unknown => 1,
84                LiveGamePhase::InProgress => 2,
85                LiveGamePhase::Final => 3,
86            })
87    }
88
89    pub fn score(&self, team: &TeamAbbr) -> Option<i32> {
90        self.game_states.values().find_map(|state| {
91            if state.game.home_team == *team {
92                state.home_score
93            } else if state.game.away_team == *team {
94                state.away_score
95            } else {
96                None
97            }
98        })
99    }
100}
101
102struct ContestRegistration {
103    games: Vec<Game>,
104    identity: Arc<LiveIdentityIndex>,
105    locked_at: Option<OffsetDateTime>,
106}
107
108struct HubState {
109    snapshots: HashMap<SlateId, Arc<LiveContestSnapshot>>,
110    reducers: HashMap<SlateId, SnapshotReducer>,
111    registrations: HashMap<SlateId, ContestRegistration>,
112    senders: HashMap<SlateId, watch::Sender<u64>>,
113    revisions: HashMap<SlateId, u64>,
114}
115
116struct HubInner {
117    enabled: bool,
118    state: Mutex<HubState>,
119    shutdown: watch::Sender<bool>,
120}
121
122#[derive(Clone)]
123pub struct LiveContestHub {
124    inner: Arc<HubInner>,
125}
126
127impl LiveContestHub {
128    pub fn new(enabled: bool) -> Self {
129        let (shutdown, _) = watch::channel(false);
130        Self {
131            inner: Arc::new(HubInner {
132                enabled,
133                state: Mutex::new(HubState {
134                    snapshots: HashMap::new(),
135                    reducers: HashMap::new(),
136                    registrations: HashMap::new(),
137                    senders: HashMap::new(),
138                    revisions: HashMap::new(),
139                }),
140                shutdown,
141            }),
142        }
143    }
144
145    pub fn enabled(&self) -> bool {
146        self.inner.enabled
147    }
148
149    pub fn snapshot(&self, id: SlateId) -> Option<Arc<LiveContestSnapshot>> {
150        self.inner
151            .state
152            .lock()
153            .expect("live hub mutex poisoned")
154            .snapshots
155            .get(&id)
156            .cloned()
157    }
158
159    pub fn subscribe(&self, id: SlateId) -> watch::Receiver<u64> {
160        let mut state = self.inner.state.lock().expect("live hub mutex poisoned");
161        let revision = *state.revisions.entry(id).or_insert(0);
162        state
163            .senders
164            .entry(id)
165            .or_insert_with(|| watch::channel(revision).0)
166            .subscribe()
167    }
168
169    pub(crate) fn shutdown_receiver(&self) -> watch::Receiver<bool> {
170        self.inner.shutdown.subscribe()
171    }
172
173    pub fn shutdown(&self) {
174        self.inner.shutdown.send_replace(true);
175    }
176
177    pub(crate) fn rebase_contest(
178        &self,
179        id: SlateId,
180        games: Vec<Game>,
181        identity: Arc<LiveIdentityIndex>,
182        feeds: &[coordinator::FeedReplay],
183        now: OffsetDateTime,
184        locked: bool,
185    ) {
186        if !self.enabled() {
187            return;
188        }
189        let mut state = self.inner.state.lock().expect("live hub mutex poisoned");
190        let locked_at = state
191            .registrations
192            .get(&id)
193            .and_then(|registration| registration.locked_at)
194            .or_else(|| locked.then_some(now));
195        let unchanged = state.registrations.get(&id).is_some_and(|registration| {
196            registration.games == games && Arc::ptr_eq(&registration.identity, &identity)
197        });
198        if unchanged && feeds.is_empty() {
199            if let Some(registration) = state.registrations.get_mut(&id) {
200                registration.locked_at = locked_at;
201            }
202            let revision = *state.revisions.entry(id).or_insert(0);
203            state
204                .senders
205                .entry(id)
206                .or_insert_with(|| watch::channel(revision).0);
207            return;
208        }
209
210        let mut reducer = SnapshotReducer::new(id, games.clone(), identity.clone(), now);
211        for feed in feeds {
212            for event in feed.events() {
213                reducer.apply(&event, &feed.slate.games);
214            }
215            if feed.is_failed() {
216                reducer.fail(&feed.slate.games);
217            }
218        }
219        let mut snapshot = reducer.snapshot();
220        let changed = state.snapshots.get(&id).is_none_or(|current| {
221            current.games != snapshot.games
222                || current.stats.players != snapshot.stats.players
223                || current.stats.defenses != snapshot.stats.defenses
224                || current.game_states != snapshot.game_states
225                || current.identity_outcomes != snapshot.identity_outcomes
226                || current.latest_error != snapshot.latest_error
227                || !Arc::ptr_eq(&current.identity, &snapshot.identity)
228        });
229        state.registrations.insert(
230            id,
231            ContestRegistration {
232                games,
233                identity,
234                locked_at,
235            },
236        );
237        state.reducers.insert(id, reducer);
238        if !changed {
239            return;
240        }
241        let revision = next_revision(&mut state, id);
242        snapshot.revision = revision;
243        state.snapshots.insert(id, Arc::new(snapshot));
244        state
245            .senders
246            .entry(id)
247            .or_insert_with(|| watch::channel(revision).0)
248            .send_replace(revision);
249    }
250
251    pub(crate) fn publish_event(
252        &self,
253        id: SlateId,
254        event: &tank01_data::PollEvent,
255        feed_games: &[LiveGame],
256    ) {
257        let mut state = self.inner.state.lock().expect("live hub mutex poisoned");
258        let mut snapshot = {
259            let Some(reducer) = state.reducers.get_mut(&id) else {
260                return;
261            };
262            if !reducer.accepts_event(event) {
263                return;
264            }
265            reducer.apply(event, feed_games)
266        };
267        let revision = next_revision(&mut state, id);
268        snapshot.revision = revision;
269        state.snapshots.insert(id, Arc::new(snapshot));
270        if let Some(sender) = state.senders.get(&id) {
271            sender.send_replace(revision);
272        }
273    }
274
275    pub(crate) fn publish_feed_failure(&self, id: SlateId, feed_games: &[LiveGame]) {
276        let mut state = self.inner.state.lock().expect("live hub mutex poisoned");
277        let mut snapshot = {
278            let Some(reducer) = state.reducers.get_mut(&id) else {
279                return;
280            };
281            reducer.fail(feed_games);
282            reducer.snapshot()
283        };
284        let revision = next_revision(&mut state, id);
285        snapshot.revision = revision;
286        state.snapshots.insert(id, Arc::new(snapshot));
287        if let Some(sender) = state.senders.get(&id) {
288            sender.send_replace(revision);
289        }
290    }
291
292    pub(crate) fn notify(&self, id: SlateId) {
293        let mut state = self.inner.state.lock().expect("live hub mutex poisoned");
294        let revision = next_revision(&mut state, id);
295        state
296            .senders
297            .entry(id)
298            .or_insert_with(|| watch::channel(revision).0)
299            .send_replace(revision);
300    }
301}
302
303fn next_revision(state: &mut HubState, id: SlateId) -> u64 {
304    let revision = state.revisions.entry(id).or_insert(0);
305    *revision = revision.saturating_add(1);
306    *revision
307}
308
309#[derive(Debug, Clone)]
310pub enum ContestScores {
311    Upcoming,
312    Official(Arc<Snapshot>),
313    Provisional(Arc<LiveContestSnapshot>),
314    Unavailable,
315}
316
317pub async fn load_contest_scores(
318    state: &AppState,
319    contest: SlateId,
320) -> Result<ContestScores, AppError> {
321    let snapshot = state.nfl.snapshot();
322    let Some(slate) = snapshot.slate(&contest) else {
323        return Ok(ContestScores::Unavailable);
324    };
325    let games = snapshot.games_for_slate(&contest);
326    if !slate.locked(state.now()) {
327        if games.iter().any(|game| game.kickoff.is_none()) {
328            return Ok(ContestScores::Unavailable);
329        }
330        return Ok(ContestScores::Upcoming);
331    }
332
333    if state.config.live_dev_feed
334        && let Some(snapshot) = state.live.snapshot(contest)
335    {
336        return Ok(ContestScores::Provisional(snapshot));
337    }
338
339    if snapshot.stats_available(&contest) {
340        return Ok(ContestScores::Official(snapshot));
341    }
342    Ok(state
343        .live
344        .snapshot(contest)
345        .map(ContestScores::Provisional)
346        .unwrap_or(ContestScores::Unavailable))
347}
348
349pub(crate) async fn stream_eligible(
350    state: &AppState,
351    contest: SlateId,
352    source: &ContestScores,
353) -> Result<bool, AppError> {
354    if !state.live.enabled() || matches!(source, ContestScores::Official(_)) {
355        return Ok(false);
356    }
357    let snapshot = state.nfl.snapshot();
358    let Some(slate) = snapshot.slate(&contest) else {
359        return Ok(false);
360    };
361    Ok(slate.locked(state.now()))
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::tests::factories;
368
369    /// Registrations and revisions are keyed by SlateId: publishing one
370    /// slate's snapshot leaves another slate's subscriber untouched.
371    #[test]
372    fn hub_snapshots_and_revisions_are_isolated_by_slate_id() {
373        let hub = LiveContestHub::new(true);
374        let one = SlateId(20260011);
375        let two = SlateId(20260021);
376        let game = factories::game_at("2026_01_BUF_KC", 1, datetime!(2026-09-13 17:00 UTC));
377        let identity = Arc::new(LiveIdentityIndex::from_sources(&[], &[]));
378
379        let one_revisions = hub.subscribe(one);
380        let two_revisions = hub.subscribe(two);
381        hub.rebase_contest(
382            one,
383            vec![game],
384            identity,
385            &[],
386            datetime!(2026-09-13 18:00 UTC),
387            true,
388        );
389
390        assert!(hub.snapshot(one).is_some(), "the published slate registers");
391        assert!(hub.snapshot(two).is_none(), "the other slate is untouched");
392        assert!(one_revisions.has_changed().unwrap());
393        assert!(
394            !two_revisions.has_changed().unwrap(),
395            "subscriber isolation"
396        );
397
398        hub.notify(one);
399        assert!(one_revisions.has_changed().unwrap());
400        assert!(
401            !two_revisions.has_changed().unwrap(),
402            "a revision for one slate never wakes another"
403        );
404    }
405}