Skip to main content

nfl_data/
lib.rs

1mod config;
2mod data_revision;
3mod error;
4mod identity;
5mod injuries;
6mod nflverse;
7pub mod salaried_players;
8mod salaries;
9pub mod scoring;
10pub mod slates;
11pub mod snapshot;
12mod store;
13mod sync;
14#[cfg(test)]
15mod test;
16mod web;
17
18use std::sync::{Arc, Mutex};
19use std::time::Duration;
20
21use arc_swap::ArcSwap;
22use nflverse_data::{NflverseData, SyncEvent};
23use tokio::sync::mpsc;
24use tokio::task::JoinHandle;
25use tracing::Instrument;
26
27pub use config::NflDataConfig;
28pub use data_revision::DataRevision;
29pub use error::NflDataError;
30pub use identity::PlayerIdentity;
31pub use nfl_model::live::{
32    EspnPlayerId, InjuryDesignation, InjuryEntry, InjuryProvider, LiveGame, LiveGamePhase,
33    LiveGameSnapshot, LivePlayerStats, LiveProviderError, LiveScoreProvider, LiveScoreboard,
34    LiveSlate, LiveTeamStats, ProviderOutcome, ProviderResponse,
35};
36pub use nfl_model::{
37    DfsPosition, Game, Player, PlayerWeekStats, Season, SeasonType, SeasonWeek, TeamAbbr,
38    TeamWeekStats, Week, WeeklyRosterEntry, eastern_offset, to_eastern,
39};
40pub(crate) use salaries::SalaryWeekOverview;
41pub use snapshot::Snapshot;
42pub(crate) use store::PlayerLink;
43pub use tank01_data::Tank01Config;
44pub use web::AdminConfig;
45pub use web::router as admin_router;
46
47pub struct NflData {
48    /// The published snapshot; the shared handle lets a rebuild swap it while
49    /// readers keep the snapshot they took.
50    pub(crate) snapshot: ArcSwap<Snapshot>,
51    pub(crate) nflverse: NflverseData,
52    pub(crate) fanduel: fanduel_data::FanduelData,
53    pub(crate) store: store::Store,
54    pub(crate) refresh_interval: Option<Duration>,
55    pub(crate) season: Season,
56    /// Serializes slate reconciliation, builds, and publication.
57    pub(crate) publication: tokio::sync::Mutex<()>,
58    /// A committed fill needs publication. Access under `publication` after initialization.
59    pub(crate) espn_fill_publish_pending: std::sync::atomic::AtomicBool,
60    /// Receive end of the nflverse source's sync events, taken once by
61    /// [`Self::start_background_tasks`].
62    pub(crate) sync_events: Mutex<Option<mpsc::UnboundedReceiver<SyncEvent>>>,
63    /// The notification task; aborted on drop.
64    pub(crate) update_worker: Mutex<Option<JoinHandle<()>>>,
65    pub(crate) injuries: injuries::InjuryState,
66}
67
68impl Drop for NflData {
69    fn drop(&mut self) {
70        if let Some(worker) = self
71            .update_worker
72            .get_mut()
73            .unwrap_or_else(|error| error.into_inner())
74            .take()
75        {
76            // Dropping a JoinHandle only detaches; the worker holds source
77            // clones and would outlive the handle.
78            worker.abort();
79        }
80        self.injuries.shutdown();
81    }
82}
83
84impl NflData {
85    /// Opens all databases, runs their migrations, reconciles the configured
86    /// season's slates, and builds the initial snapshot. Any failure is a
87    /// connection error; background work starts only through
88    /// [`Self::start_background_tasks`].
89    pub async fn connect(config: NflDataConfig) -> Result<Self, NflDataError> {
90        let injuries = match config.tank01.clone() {
91            Some(tank01) => {
92                injuries::InjuryState::configured(tank01_data::Tank01Client::new(tank01)?)
93            }
94            None => injuries::InjuryState::default(),
95        };
96        let refresh_interval = config
97            .refresh_interval
98            .filter(|interval| !interval.is_zero());
99        let (sync_events, sync_events_receiver) = mpsc::unbounded_channel();
100        let nflverse =
101            NflverseData::connect_with_sync_events(config.clone().into(), Some(sync_events))
102                .await?;
103        let fanduel = if config.fanduel_database_url == "sqlite::memory:" {
104            fanduel_data::FanduelData::in_memory().await
105        } else {
106            fanduel_data::FanduelData::connect(&config.fanduel_database_url).await
107        }?;
108        let store = store::Store::open(&config.database_url).await?;
109
110        let nfl_data = Self {
111            nflverse,
112            fanduel,
113            store,
114            refresh_interval,
115            season: config.season,
116            snapshot: ArcSwap::from_pointee(Snapshot::default()),
117            publication: tokio::sync::Mutex::new(()),
118            espn_fill_publish_pending: std::sync::atomic::AtomicBool::new(false),
119            sync_events: Mutex::new(Some(sync_events_receiver)),
120            update_worker: Mutex::new(None),
121            injuries,
122        };
123
124        // The initial build reads stored slates, so reconcile them first.
125        let initial = async {
126            slates::refresh(&nfl_data).await?;
127            nfl_data.build_and_publish().await
128        };
129        initial
130            .instrument(tracing::info_span!(
131                parent: None,
132                "snapshot_update",
133                season = nfl_data.season.0,
134                trigger = "initial_connect",
135            ))
136            .await?;
137
138        Ok(nfl_data)
139    }
140
141    /// A fresh, empty, in-memory cache: migrations applied, nothing synced.
142    /// Nothing builds a snapshot behind the caller's back: seeding tests
143    /// republish explicitly.
144    pub async fn in_memory() -> Result<Self, NflDataError> {
145        let nflverse = NflverseData::in_memory().await?;
146        let fanduel = fanduel_data::FanduelData::in_memory().await?;
147        let store = store::Store::in_memory().await?;
148        Ok(Self {
149            nflverse,
150            fanduel,
151            store,
152            refresh_interval: None,
153            season: Season::default(),
154            snapshot: ArcSwap::from_pointee(Snapshot::default()),
155            publication: tokio::sync::Mutex::new(()),
156            espn_fill_publish_pending: std::sync::atomic::AtomicBool::new(false),
157            sync_events: Mutex::new(None),
158            update_worker: Mutex::new(None),
159            injuries: injuries::InjuryState::default(),
160        })
161    }
162
163    /// The application season this handle carries, from its configuration.
164    pub fn season(&self) -> Season {
165        self.season
166    }
167
168    pub fn snapshot(&self) -> Arc<Snapshot> {
169        self.snapshot.load_full()
170    }
171}