Skip to main content

nflverse_data/
lib.rs

1mod client;
2mod config;
3use nfl_model::eastern;
4mod error;
5mod ingest;
6pub use nfl_model::live;
7mod model;
8mod refresh;
9mod store;
10mod sync;
11
12pub use refresh::RefreshStatus;
13
14use std::{collections::HashMap, sync::Arc};
15
16use tokio::sync::mpsc;
17
18use store::Store;
19
20pub use config::NflDataConfig as NflverseDataConfig;
21use config::NflDataConfig;
22pub use eastern::{eastern_offset, to_eastern};
23pub use error::NflDataError as NflverseDataError;
24pub use live::{
25    EspnPlayerId, InjuryDesignation, InjuryEntry, InjuryProvider, InjuryReport, LiveGame,
26    LiveGamePhase, LiveGameSnapshot, LivePlayerStats, LiveProviderError, LiveScoreProvider,
27    LiveScoreboard, LiveScoreboardGame, LiveSlate, LiveTeamStats, ProviderOutcome,
28    ProviderResponse, RawBody,
29};
30pub use model::{
31    AssetUpdate, Dataset, DatasetFreshness, DatasetReport, DatasetStatus, Game, Player,
32    PlayerWeekStats, Season, SeasonType, SeasonWeek, SyncEvent, SyncReport, TeamAbbr,
33    TeamWeekStats, Week, WeeklyRosterEntry,
34};
35
36#[derive(Clone)]
37pub struct NflverseData {
38    inner: Arc<Inner>,
39}
40
41struct Inner {
42    store: Store,
43    config: NflDataConfig,
44    refresh: refresh::Refresh,
45    /// Notified after each successful sync
46    sync_notify: Option<mpsc::UnboundedSender<()>>,
47    /// Sent one [`SyncEvent`] per completed sync — unchanged and fully failed
48    /// runs included. Setup failures emit nothing; closed receivers are
49    /// ignored.
50    sync_events: Option<mpsc::UnboundedSender<SyncEvent>>,
51}
52
53/// Publishes one [`SyncEvent`] per completed run — unchanged and fully failed
54/// runs included — and, for fully successful runs only, one `()` on the legacy
55/// channel. An `Err` outcome returns before either channel is touched.
56fn complete_sync(
57    outcome: Result<sync::SyncOutcome, NflverseDataError>,
58    sync_notify: Option<&mpsc::UnboundedSender<()>>,
59    sync_events: Option<&mpsc::UnboundedSender<SyncEvent>>,
60) -> Result<SyncReport, NflverseDataError> {
61    let outcome = outcome?;
62    let all_ok = outcome.report.all_ok();
63    if let Some(sync_events) = sync_events {
64        let _ = sync_events.send(SyncEvent {
65            all_ok,
66            updates: outcome.updates,
67        });
68    }
69    if all_ok && let Some(sync_notify) = sync_notify {
70        let _ = sync_notify.send(());
71    }
72    Ok(outcome.report)
73}
74
75impl NflverseData {
76    /// Opens (creating if missing) the cache database and runs migrations.
77    pub async fn connect(config: NflverseDataConfig) -> Result<Self, NflverseDataError> {
78        Self::connect_with_sync_notify(config, None).await
79    }
80
81    /// [`Self::connect`], also notifying `sync_notify` after each fully
82    /// successful sync.
83    pub async fn connect_with_sync_notify(
84        config: NflverseDataConfig,
85        sync_notify: Option<mpsc::UnboundedSender<()>>,
86    ) -> Result<Self, NflverseDataError> {
87        Self::connect_with_channels(config, sync_notify, None).await
88    }
89
90    /// [`Self::connect`], also sending one [`SyncEvent`] per completed sync on
91    /// `sync_events`.
92    pub async fn connect_with_sync_events(
93        config: NflverseDataConfig,
94        sync_events: Option<mpsc::UnboundedSender<SyncEvent>>,
95    ) -> Result<Self, NflverseDataError> {
96        Self::connect_with_channels(config, None, sync_events).await
97    }
98
99    async fn connect_with_channels(
100        config: NflverseDataConfig,
101        sync_notify: Option<mpsc::UnboundedSender<()>>,
102        sync_events: Option<mpsc::UnboundedSender<SyncEvent>>,
103    ) -> Result<Self, NflverseDataError> {
104        let store = Store::open(&config.database_url).await?;
105        Ok(Self {
106            inner: Arc::new(Inner {
107                store,
108                config,
109                refresh: refresh::Refresh::default(),
110                sync_notify,
111                sync_events,
112            }),
113        })
114    }
115
116    /// A fresh, empty, in-memory cache — for tests and tooling that need an
117    /// `NflverseData` handle without a database file. Migrations are applied; no data
118    /// is synced.
119    pub async fn in_memory() -> Result<Self, NflverseDataError> {
120        Ok(Self {
121            inner: Arc::new(Inner {
122                store: Store::in_memory().await?,
123                config: NflDataConfig::default(),
124                refresh: refresh::Refresh::default(),
125                sync_notify: None,
126                sync_events: None,
127            }),
128        })
129    }
130
131    /// Most recent weekly roster entry for each id, keyed by gsis id. Ids with
132    /// no entry are absent from the map rather than an error.
133    ///
134    /// Complements [`Self::players_by_gsis`]: candidate lists are built from
135    /// weekly rosters, and 144 of 2025's 3,133 rostered players have no row in
136    /// the `players` table, so a pick cannot always be named from there.
137    pub async fn weekly_roster_entries_by_gsis<I: AsRef<str>>(
138        &self,
139        ids: &[I],
140    ) -> Result<HashMap<String, WeeklyRosterEntry>, NflverseDataError> {
141        let mut out = HashMap::with_capacity(ids.len());
142        for id in ids {
143            let gsis = id.as_ref();
144            if out.contains_key(gsis) {
145                continue;
146            }
147            if let Some(e) = store::weekly_rosters::by_gsis(self.inner.store.reader(), gsis).await?
148            {
149                out.insert(gsis.to_string(), e);
150            }
151        }
152        Ok(out)
153    }
154
155    /// Seed weekly roster entries directly, for tests and tooling. Not part of
156    /// the stable API — bypasses the sync pipeline and `sync_state` bookkeeping.
157    #[doc(hidden)]
158    pub async fn seed_weekly_roster_for_test(
159        &self,
160        entries: &[WeeklyRosterEntry],
161    ) -> Result<(), NflverseDataError> {
162        self.inner
163            .store
164            .write_tx(async |conn| store::weekly_rosters::seed(conn, entries).await)
165            .await
166    }
167
168    /// Seed players and games directly, for tests and tooling. Not part of the
169    /// stable API — bypasses the sync pipeline and `sync_state` bookkeeping.
170    #[doc(hidden)]
171    pub async fn seed_for_test(
172        &self,
173        players: &[Player],
174        games: &[Game],
175    ) -> Result<(), NflverseDataError> {
176        self.inner
177            .store
178            .write_tx(async |conn| {
179                store::players::seed(conn, players).await?;
180                store::games::seed(conn, games).await?;
181                Ok(())
182            })
183            .await
184    }
185
186    /// All cached games for a season, ordered by week.
187    pub async fn games(&self, season: Season) -> Result<Vec<Game>, NflverseDataError> {
188        store::games::for_season(self.inner.store.reader(), season).await
189    }
190
191    /// All cached players, ordered by name.
192    pub async fn players(&self) -> Result<Vec<Player>, NflverseDataError> {
193        store::players::all(self.inner.store.reader()).await
194    }
195
196    /// Players for a small set of ids, keyed by gsis id. Ids with no player are
197    /// absent from the map rather than an error — callers render a fallback.
198    ///
199    /// One indexed seek per id — ~25µs for a nine-slot lineup, so the loop is
200    /// not worth batching at the sizes call sites actually pass. If that ever
201    /// changes, the set-based form is `WHERE gsis_id IN (SELECT value FROM
202    /// json_each(?))`: one bind parameter and static SQL, so `query_as!` still
203    /// applies and no `FromRow` impl is needed. It does require `gsis_id` to
204    /// lead an index — SQLite will not skip-scan an `IN` list, and drops to a
205    /// full table scan without one.
206    pub async fn players_by_gsis<I: AsRef<str>>(
207        &self,
208        ids: &[I],
209    ) -> Result<HashMap<String, Player>, NflverseDataError> {
210        let mut out = HashMap::with_capacity(ids.len());
211        for id in ids {
212            let gsis = id.as_ref();
213            if out.contains_key(gsis) {
214                continue;
215            }
216            if let Some(p) = store::players::by_gsis(self.inner.store.reader(), gsis).await? {
217                out.insert(gsis.to_string(), p);
218            }
219        }
220        Ok(out)
221    }
222
223    /// A team's cached roster for one week, ordered by player name.
224    pub async fn weekly_roster(
225        &self,
226        season_week: SeasonWeek,
227        team: &TeamAbbr,
228    ) -> Result<Vec<WeeklyRosterEntry>, NflverseDataError> {
229        store::weekly_rosters::for_team_week(self.inner.store.reader(), season_week, team).await
230    }
231
232    /// All players' cached stat lines for one week, ordered by player GSIS id.
233    pub async fn player_week_stats(
234        &self,
235        season_week: SeasonWeek,
236    ) -> Result<Vec<PlayerWeekStats>, NflverseDataError> {
237        store::player_stats::for_week(self.inner.store.reader(), season_week).await
238    }
239
240    /// All teams' pbp-derived DST lines for one week (sacks, takeaways, TDs,
241    /// blocks, conversion returns, and points_allowed = the opponent's
242    /// offensive points). Ordered by team.
243    pub async fn team_week_stats(
244        &self,
245        season_week: SeasonWeek,
246    ) -> Result<Vec<TeamWeekStats>, NflverseDataError> {
247        store::team_stats::for_week(self.inner.store.reader(), season_week).await
248    }
249    /// Freshness for every dataset, in sync order.
250    pub async fn freshness(&self) -> Result<Vec<DatasetFreshness>, NflverseDataError> {
251        let rows = store::sync_state::freshness(self.inner.store.reader()).await?;
252        Ok(Dataset::ALL
253            .into_iter()
254            .map(|dataset| {
255                let row = rows
256                    .iter()
257                    .find(|row| row.release_tag == dataset.release_tag());
258                DatasetFreshness {
259                    dataset,
260                    assets: row.map_or(0, |row| row.assets),
261                    last_synced_at: row.map(|row| row.last_synced_at),
262                }
263            })
264            .collect())
265    }
266
267    /// Fetch all datasets from nflverse, skipping assets whose upstream
268    /// updated_at matches the cache. Failures are isolated per dataset and
269    /// reported in the SyncReport; Err is reserved for setup-level failures.
270    /// For per-season datasets, isolation is finer still: a bad season's
271    /// asset doesn't block the other seasons in the same dataset from
272    /// updating.
273    pub async fn sync(&self) -> Result<SyncReport, NflverseDataError> {
274        complete_sync(
275            sync::run(&self.inner.store, &self.inner.config).await,
276            self.inner.sync_notify.as_ref(),
277            self.inner.sync_events.as_ref(),
278        )
279    }
280
281    /// Seed player and team week stats directly, for tests and tooling. Reuses the
282    /// sync-path `replace` inserts (per-season delete-then-insert). Not part of the
283    /// stable API.
284    #[doc(hidden)]
285    pub async fn seed_week_stats_for_test(
286        &self,
287        season: Season,
288        players: &[PlayerWeekStats],
289        teams: &[TeamWeekStats],
290    ) -> Result<(), NflverseDataError> {
291        let asset = store::sync_state::SyncedAsset {
292            release_tag: "test",
293            asset_name: "test",
294            updated_at: "1970-01-01T00:00:00Z",
295        };
296        store::player_stats::replace(&self.inner.store, &asset, season, players).await?;
297        store::team_stats::replace(&self.inner.store, &asset, season, teams).await?;
298        Ok(())
299    }
300}
301
302#[cfg(test)]
303mod freshness_tests {
304    use crate::{Dataset, NflverseData};
305
306    #[tokio::test]
307    async fn returns_fixed_order_and_ignores_unknown_tags() {
308        let nfl = NflverseData::in_memory().await.unwrap();
309        for (tag, asset) in [
310            ("test", "ignored"),
311            ("schedules", "games.csv"),
312            ("schedules", "extra.csv"),
313        ] {
314            sqlx::query(
315                "INSERT INTO sync_state (release_tag, asset_name, upstream_updated_at) \
316                 VALUES (?, ?, ?)",
317            )
318            .bind(tag)
319            .bind(asset)
320            .bind("2026-01-01T00:00:00Z")
321            .execute(nfl.inner.store.reader())
322            .await
323            .unwrap();
324        }
325
326        let rows = nfl.freshness().await.unwrap();
327        assert_eq!(
328            rows.iter().map(|row| row.dataset).collect::<Vec<_>>(),
329            Dataset::ALL
330        );
331        assert_eq!(rows[0].assets, 2);
332        assert!(rows[0].last_synced_at.is_some());
333        assert_eq!(rows[1].assets, 0);
334        assert!(rows[1].last_synced_at.is_none());
335    }
336}
337
338#[cfg(test)]
339mod sync_completion_tests {
340    use super::*;
341
342    #[test]
343    fn setup_failure_emits_no_completion_event_and_no_legacy_notification() {
344        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
345        let (events_tx, mut events_rx) = mpsc::unbounded_channel();
346
347        let result = complete_sync(
348            Err(NflverseDataError::GitHubApi {
349                status: 404,
350                url: "https://example.invalid/releases/tags/schedules".into(),
351            }),
352            Some(&notify_tx),
353            Some(&events_tx),
354        );
355
356        assert!(matches!(
357            result.unwrap_err(),
358            NflverseDataError::GitHubApi { status: 404, .. }
359        ));
360        assert!(
361            events_rx.try_recv().is_err(),
362            "setup failures emit no completion event"
363        );
364        assert!(
365            notify_rx.try_recv().is_err(),
366            "setup failures do not notify the legacy channel"
367        );
368    }
369}