Skip to main content

nfl_data/
sync.rs

1//! Background refresh lifecycle and post-sync reconciliation.
2
3use std::collections::{BTreeMap, HashMap};
4use std::sync::{Arc, Weak, atomic::Ordering};
5use std::time::Instant;
6
7use nflverse_data::{Dataset, SyncEvent};
8use tracing::Instrument;
9
10use crate::slates::{self, Slate, SlateId};
11use crate::snapshot::Snapshot;
12use crate::store;
13use crate::store::player_link;
14use crate::{NflData, NflDataError, Season};
15
16/// Identity fallback can read weekly rosters from any season.
17fn update_is_relevant(update: &nflverse_data::AssetUpdate, season: Season) -> bool {
18    update.season == Some(season)
19        || matches!(
20            update.dataset,
21            Dataset::Schedules | Dataset::Players | Dataset::WeeklyRosters
22        )
23}
24
25/// The stored slate state a build reads: metadata plus game membership.
26async fn stored_slates(
27    nfl: &NflData,
28) -> Result<BTreeMap<SlateId, (Slate, Vec<String>)>, NflDataError> {
29    let mut state = BTreeMap::new();
30    for slate in slates::all(nfl).await? {
31        let game_ids = store::slates::game_ids(nfl.store.reader(), &slate.id).await?;
32        state.insert(slate.id, (slate, game_ids));
33    }
34    Ok(state)
35}
36
37impl NflData {
38    /// Start configured internal background work. Repeated calls are safe: the
39    /// scheduler refreshes upstream datasets when configured, and the
40    /// notification task republishes the snapshot after each relevant sync.
41    pub fn start_background_tasks(self: &Arc<Self>) {
42        if let Some(interval) = self.refresh_interval {
43            self.nflverse.start_scheduler(interval);
44        }
45        self.start_update_worker();
46        self.start_injury_worker();
47        self.start_injury_polling();
48    }
49
50    /// Stop future automatic task triggers without cancelling an active
51    /// refresh. The notification task keeps running: aborting it here would
52    /// make a later start unable to restore its receiver.
53    pub fn stop_background_tasks(&self) {
54        self.nflverse.stop_scheduler();
55        self.stop_injury_polling();
56    }
57
58    /// Spawn the notification task; the receiver is taken on the first call, so
59    /// later calls are no-ops.
60    fn start_update_worker(self: &Arc<Self>) {
61        let Some(mut sync_events) = self
62            .sync_events
63            .lock()
64            .unwrap_or_else(|error| error.into_inner())
65            .take()
66        else {
67            return;
68        };
69        // A weak owner keeps a dropped handle droppable: the task upgrades
70        // only to process one event and releases it before waiting again.
71        let updates = Arc::downgrade(self);
72        let worker = tokio::spawn(async move {
73            while let Some(event) = sync_events.recv().await {
74                let Some(nfl) = Weak::upgrade(&updates) else {
75                    return;
76                };
77                nfl.apply_sync_event(event).await;
78            }
79        });
80        *self
81            .update_worker
82            .lock()
83            .unwrap_or_else(|error| error.into_inner()) = Some(worker);
84    }
85
86    /// Span for an update the caller owns; nested work inherits its trigger.
87    fn snapshot_update_span(&self, trigger: &'static str) -> tracing::Span {
88        tracing::info_span!("snapshot_update", season = self.season.0, trigger)
89    }
90
91    /// A failed operation leaves readers on the current snapshot.
92    fn log_update_failure(&self, error: &NflDataError) {
93        tracing::error!(error = %error, "snapshot update failed");
94    }
95
96    /// Apply one completed sync: republish when the configured season's data
97    /// changed, otherwise reconcile the slates only.
98    async fn apply_sync_event(&self, event: SyncEvent) {
99        let relevant = event
100            .updates
101            .iter()
102            .any(|update| update_is_relevant(update, self.season));
103        // Channels carry no request context: root the span explicitly.
104        let span = tracing::info_span!(
105            parent: None,
106            "snapshot_update",
107            season = self.season.0,
108            trigger = "sync_event",
109            committed_updates = event.updates.len(),
110            relevant,
111        );
112        async move {
113            if !relevant && !event.all_ok {
114                // Nothing committed that this season can see.
115                tracing::debug!("snapshot update skipped");
116                return;
117            }
118            tracing::info!("snapshot update started");
119            let outcome = if relevant {
120                self.reconcile_slates_and_rebuild_inner().await
121            } else {
122                self.reconcile_slates_if_changed_inner().await
123            };
124            // Failures were logged at the operation that failed.
125            drop(outcome);
126        }
127        .instrument(span)
128        .await
129    }
130
131    /// Reconcile the configured season's slates and republish. Returns after
132    /// the new snapshot is published, or leaves the old one on error.
133    pub(crate) async fn reconcile_slates_and_rebuild(&self) -> Result<(), NflDataError> {
134        let span = self.snapshot_update_span("reconcile_slates");
135        async {
136            tracing::info!("snapshot update started");
137            self.reconcile_slates_and_rebuild_inner().await
138        }
139        .instrument(span)
140        .await
141    }
142
143    /// [`Self::reconcile_slates_and_rebuild`] without a start event.
144    async fn reconcile_slates_and_rebuild_inner(&self) -> Result<(), NflDataError> {
145        let _publication = self.publication.lock().await;
146        if let Err(error) = slates::refresh(self).await {
147            self.log_update_failure(&error);
148            return Err(error);
149        }
150        self.build_and_publish().await
151    }
152
153    /// Reconcile and republish only when stored slate state changed.
154    async fn reconcile_slates_if_changed_inner(&self) -> Result<(), NflDataError> {
155        let _publication = self.publication.lock().await;
156        let before = match stored_slates(self).await {
157            Ok(before) => before,
158            Err(error) => {
159                self.log_update_failure(&error);
160                return Err(error);
161            }
162        };
163        if let Err(error) = slates::refresh(self).await {
164            self.log_update_failure(&error);
165            return Err(error);
166        }
167        let after = match stored_slates(self).await {
168            Ok(after) => after,
169            Err(error) => {
170                self.log_update_failure(&error);
171                return Err(error);
172            }
173        };
174        if after == before {
175            tracing::debug!("snapshot update skipped");
176            return Ok(());
177        }
178        self.build_and_publish().await
179    }
180
181    /// Retry publication after a failed build, even if the next fill changes no rows.
182    pub(crate) async fn apply_espn_id_fill(
183        &self,
184        updates: &HashMap<nfl_model::NflPlayerId, String>,
185    ) -> Result<u64, NflDataError> {
186        let span = self.snapshot_update_span("fill_missing_espn_ids");
187        async {
188            let _publication = self.publication.lock().await;
189            let updated = player_link::update_espn_ids(&self.store, updates).await?;
190            if updated > 0 {
191                self.espn_fill_publish_pending
192                    .store(true, Ordering::Relaxed);
193            }
194            if self.espn_fill_publish_pending.load(Ordering::Relaxed) {
195                self.build_and_publish().await?;
196            }
197            Ok(updated)
198        }
199        .instrument(span)
200        .await
201    }
202
203    /// Rebuild the snapshot and publish it. A failed build keeps the snapshot
204    /// readers already hold; the next request to rebuild tries again.
205    pub(crate) async fn rebuild_snapshot(&self) -> Result<(), NflDataError> {
206        let span = self.snapshot_update_span("rebuild");
207        async {
208            tracing::info!("snapshot update started");
209            let _publication = self.publication.lock().await;
210            self.build_and_publish().await
211        }
212        .instrument(span)
213        .await
214    }
215
216    /// [`Self::rebuild_snapshot`] with the publication lock already held.
217    pub(crate) async fn build_and_publish(&self) -> Result<(), NflDataError> {
218        let started = Instant::now();
219        let snapshot = match Snapshot::build(self).await {
220            Ok(snapshot) => snapshot,
221            Err(error) => {
222                tracing::error!(
223                    error = %error,
224                    duration_ms = started.elapsed().as_millis() as u64,
225                    "snapshot update failed"
226                );
227                return Err(error);
228            }
229        };
230        self.snapshot.store(Arc::new(snapshot));
231        self.espn_fill_publish_pending
232            .store(false, Ordering::Relaxed);
233        tracing::info!(
234            duration_ms = started.elapsed().as_millis() as u64,
235            "snapshot published"
236        );
237        Ok(())
238    }
239}