Skip to main content

nfl_data/snapshot/
mod.rs

1use crate::salaried_players::{self, SalariedPlayer, SalariedPlayersBySlot};
2use crate::slates::{self, Slate, SlateId};
3use crate::store::player_link;
4use crate::{NflData, NflDataError};
5use nfl_model::{
6    DfsPositionSlotType, Game, InjuryDesignation, NflPlayerId, PlayerOrDefenseId, TeamAbbr,
7};
8use std::collections::hash_map::Entry;
9use std::collections::{BTreeMap, HashMap, HashSet};
10
11#[cfg(test)]
12mod tests;
13
14/// One slate's salaried players: the position buckets plus direct lookups by
15/// gsis id and by team.
16#[derive(Debug, Default)]
17struct SalariedPlayers {
18    by_slot: SalariedPlayersBySlot,
19    players: HashMap<NflPlayerId, SalariedPlayer>,
20    defenses: HashMap<TeamAbbr, SalariedPlayer>,
21}
22
23impl SalariedPlayers {
24    /// Index the position buckets. Every row lands in exactly one `Position`
25    /// bucket, so the flex duplicates are skipped.
26    fn new(by_slot: SalariedPlayersBySlot) -> Self {
27        let mut players = HashMap::new();
28        let mut defenses = HashMap::new();
29        for (slot_type, rows) in &by_slot {
30            if matches!(slot_type, DfsPositionSlotType::Flex) {
31                continue;
32            }
33            for row in rows {
34                match &row.id {
35                    Some(id) => {
36                        players.insert(id.clone(), row.clone());
37                    }
38                    None => {
39                        defenses.insert(row.team, row.clone());
40                    }
41                }
42            }
43        }
44        Self {
45            by_slot,
46            players,
47            defenses,
48        }
49    }
50}
51
52async fn annotate_injuries(
53    nfl: &NflData,
54    built: &mut HashMap<SlateId, SalariedPlayersBySlot>,
55    current_week_slate_ids: &[SlateId],
56) -> Result<(), NflDataError> {
57    let Some(report) = nfl
58        .injury_report()
59        .filter(|report| !report.entries.is_empty())
60    else {
61        return Ok(());
62    };
63    let eligible_rows = current_week_slate_ids.iter().any(|slate_id| {
64        built
65            .get(slate_id)
66            .is_some_and(|by_slot| by_slot.values().flatten().any(|row| row.id.is_some()))
67    });
68    if !eligible_rows {
69        return Ok(());
70    }
71
72    let links_by_espn = player_link::links_by_espn(nfl.store.reader()).await?;
73    let mut designations: HashMap<NflPlayerId, Option<InjuryDesignation>> = HashMap::new();
74    for entry in &report.entries {
75        let Some(espn_id) = entry
76            .espn_id
77            .as_ref()
78            .map(|espn| espn.0.trim())
79            .filter(|espn| !espn.is_empty())
80        else {
81            continue;
82        };
83        let Some(gsis_id) = links_by_espn.get(espn_id) else {
84            continue;
85        };
86        match designations.entry(NflPlayerId(gsis_id.clone())) {
87            Entry::Vacant(slot) => {
88                slot.insert(Some(entry.designation));
89            }
90            Entry::Occupied(mut slot) => {
91                if *slot.get() != Some(entry.designation) {
92                    slot.insert(None);
93                }
94            }
95        }
96    }
97    if designations.is_empty() {
98        return Ok(());
99    }
100
101    for slate_id in current_week_slate_ids {
102        if let Some(by_slot) = built.get_mut(slate_id) {
103            for row in by_slot.values_mut().flatten() {
104                if let Some(id) = &row.id {
105                    row.injury = designations.get(id).copied().flatten();
106                }
107            }
108        }
109    }
110    Ok(())
111}
112
113// Input is ordered by SlateId.
114fn select_current_slate_id<'a>(
115    slates: impl Iterator<Item = &'a Slate>,
116    now: time::OffsetDateTime,
117) -> Option<SlateId> {
118    let mut last_known = None;
119    let mut greatest = None;
120    for slate in slates {
121        greatest = Some(slate.id);
122        if slate.kickoff.is_none() {
123            continue;
124        }
125        last_known = Some(slate.id);
126        if !slate.finished(now) {
127            return Some(slate.id);
128        }
129    }
130    last_known.or(greatest)
131}
132
133#[derive(Debug, Default)]
134pub struct Snapshot {
135    slates: BTreeMap<SlateId, Slate>,
136    current_week_slate_ids: Vec<SlateId>,
137    current_slate_id: Option<SlateId>,
138    games: HashMap<SlateId, Vec<Game>>,
139    salaried_players: HashMap<SlateId, SalariedPlayers>,
140    stats_available: HashSet<SlateId>,
141}
142
143impl Snapshot {
144    /// Build from the handle: the configured season's stored slates, then the
145    /// salaried players that resolve for them.
146    pub(crate) async fn build(nfl: &NflData) -> Result<Self, NflDataError> {
147        Self::build_at(nfl, time::OffsetDateTime::now_utc()).await
148    }
149
150    async fn build_at(nfl: &NflData, now: time::OffsetDateTime) -> Result<Self, NflDataError> {
151        let all_slates: Vec<Slate> = slates::all(nfl).await?.into_iter().collect();
152
153        // Every stored slate's games, resolved at build time; independent of
154        // whether the slate resolves to salaried players.
155        let mut games: HashMap<SlateId, Vec<Game>> = HashMap::with_capacity(all_slates.len());
156        for slate in &all_slates {
157            games.insert(slate.id, slates::games(nfl, &slate.id).await?);
158        }
159
160        let (mut built, available) =
161            salaried_players::build_salaried_players(nfl, all_slates.as_slice(), &games).await?;
162        built.retain(|_, by_slot| !by_slot.is_empty());
163
164        let slates: BTreeMap<SlateId, Slate> = all_slates
165            .into_iter()
166            .filter(|slate| built.contains_key(&slate.id))
167            .map(|slate| (slate.id, slate))
168            .collect();
169
170        // SlateId groups slates by week.
171        let current_week_slate_ids: Vec<SlateId> = match slates.last_key_value() {
172            Some((_, latest)) => {
173                let mut ids: Vec<SlateId> = slates
174                    .values()
175                    .rev()
176                    .take_while(|slate| slate.season_week == latest.season_week)
177                    .map(|slate| slate.id)
178                    .collect();
179                ids.reverse();
180                ids
181            }
182            None => Vec::new(),
183        };
184
185        annotate_injuries(nfl, &mut built, &current_week_slate_ids).await?;
186
187        let salaried: HashMap<SlateId, SalariedPlayers> = built
188            .into_iter()
189            .map(|(slate_id, by_slot)| (slate_id, SalariedPlayers::new(by_slot)))
190            .collect();
191
192        let stats_available = available
193            .into_iter()
194            .filter(|slate_id| slates.contains_key(slate_id))
195            .collect();
196
197        let current_slate_id = select_current_slate_id(
198            current_week_slate_ids
199                .iter()
200                .filter_map(|slate_id| slates.get(slate_id)),
201            now,
202        );
203
204        Ok(Self {
205            slates,
206            current_week_slate_ids,
207            current_slate_id,
208            games,
209            salaried_players: salaried,
210            stats_available,
211        })
212    }
213
214    /// Player and team stats cover both sides of every slate game in this publication.
215    /// This does not guarantee that the games are final.
216    pub fn stats_available(&self, slate_id: &SlateId) -> bool {
217        self.stats_available.contains(slate_id)
218    }
219
220    /// All slates with salaried players in ascending order
221    pub fn slates(&self) -> impl Iterator<Item = &Slate> + '_ {
222        self.slates.values()
223    }
224
225    /// Latest populated week's slates in ID order. Only these carry injuries.
226    pub fn current_week_slates(&self) -> impl Iterator<Item = &Slate> + '_ {
227        self.current_week_slate_ids
228            .iter()
229            .filter_map(|slate_id| self.slates.get(slate_id))
230    }
231
232    /// Current slate, fixed at build time.
233    pub fn current_slate(&self) -> Option<&Slate> {
234        self.current_slate_id
235            .as_ref()
236            .and_then(|slate_id| self.slates.get(slate_id))
237    }
238
239    /// The slate with this id, or `None` when it has no salaried players.
240    pub fn slate(&self, id: &SlateId) -> Option<&Slate> {
241        self.slates.get(id)
242    }
243
244    /// The stored slate's games as captured at build time, independent of
245    /// whether the slate resolves to salaried players: known kickoffs
246    /// ascending, unknown kickoffs last, game id breaking ties. `None` for the
247    /// slate itself does not make this empty. Unknown ids and slates with no
248    /// membership yield an empty slice.
249    pub fn games_for_slate(&self, slate_id: &SlateId) -> &[Game] {
250        self.games.get(slate_id).map(Vec::as_slice).unwrap_or(&[])
251    }
252
253    /// Player-only index for `slate_id`; `None` when unpopulated.
254    /// All positions, no flex duplicates, no defenses.
255    pub fn players_for_slate(
256        &self,
257        slate_id: &SlateId,
258    ) -> Option<&HashMap<NflPlayerId, SalariedPlayer>> {
259        self.salaried_players
260            .get(slate_id)
261            .map(|slate| &slate.players)
262    }
263
264    /// The player with this gsis id on `slate_id`, or `None` when the slate
265    /// has no such player.
266    pub fn player(&self, slate_id: &SlateId, id: &NflPlayerId) -> Option<&SalariedPlayer> {
267        self.salaried_players.get(slate_id)?.players.get(id)
268    }
269
270    /// The defense with this team on `slate_id`, or `None` when the slate has
271    /// no such defense.
272    pub fn defense(&self, slate_id: &SlateId, team: &TeamAbbr) -> Option<&SalariedPlayer> {
273        self.salaried_players.get(slate_id)?.defenses.get(team)
274    }
275
276    /// The salaried row for a player or a defense, whichever the id names.
277    pub fn salaried_player(
278        &self,
279        slate_id: &SlateId,
280        value: &PlayerOrDefenseId,
281    ) -> Option<&SalariedPlayer> {
282        match value {
283            PlayerOrDefenseId::Player(id) => self.player(slate_id, id),
284            PlayerOrDefenseId::Defense(team) => self.defense(slate_id, team),
285        }
286    }
287
288    pub fn salaried_players_for_position(
289        &self,
290        slate_id: &SlateId,
291        pos: &DfsPositionSlotType,
292    ) -> &[SalariedPlayer] {
293        self.salaried_players
294            .get(slate_id)
295            .and_then(|slate| slate.by_slot.get(pos))
296            .map(Vec::as_slice)
297            .unwrap_or(&[])
298    }
299}