Skip to main content

sunday_slate/avatars/
fetch.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::Duration;
4
5use tracing::{Instrument, warn};
6
7use crate::media::{self, process::ProcessedImage, store as media_store};
8use crate::nfl_player_headshots::service as headshot_service;
9use crate::nfl_player_headshots::store as player_store;
10use crate::nfl_teams::store as team_store;
11use crate::{AppError, AppState};
12use utils::background::{Progress, Runner};
13
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct FetchReport {
16    pub players_fetched: usize,
17    pub teams_fetched: usize,
18    pub failed: usize,
19    pub skipped: usize,
20}
21
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct FetchProgress {
24    pub total: usize,
25    pub fetched: usize,
26    pub failed: usize,
27    pub skipped: usize,
28}
29
30pub type AvatarFetchRunner = Runner<FetchProgress, FetchReport>;
31
32const MAX_HEADSHOT_BYTES: usize = 20 * 1024 * 1024;
33const MAX_TEAM_LOGO_BYTES: usize = 5 * 1024 * 1024;
34/// Initial body buffer; Content-Length is untrusted, so it only seeds up to this.
35const INITIAL_BODY_CAPACITY: u64 = 1024 * 1024;
36
37fn oversized_image_error(max_bytes: usize) -> String {
38    format!("image response exceeds {} MB", max_bytes / (1024 * 1024))
39}
40
41pub fn espn_logo_url(abbr: &str) -> String {
42    let slug = match abbr {
43        "WAS" => "wsh".to_string(),
44        other => other.to_lowercase(),
45    };
46    format!("https://a.espncdn.com/i/teamlogos/nfl/500/{slug}.png")
47}
48
49pub async fn fetch_missing(
50    state: &AppState,
51    progress: &Progress<FetchProgress, FetchReport>,
52) -> Result<FetchReport, AppError> {
53    fetch_missing_with(state, progress, espn_logo_url).await
54}
55
56/// Start a fetch in the background. Returns `false` if one is running.
57pub fn start_fetch(state: &AppState) -> bool {
58    let runner = Arc::clone(&state.avatar_runner);
59    let state = state.clone();
60    let parent = tracing::Span::current();
61    let span = tracing::info_span!(parent: &parent, "background_job", job = "avatar_fetch");
62    let started = runner.try_start(FetchProgress::default(), move |progress| {
63        async move {
64            tracing::info!("avatar fetch started");
65            let started = std::time::Instant::now();
66            let result = fetch_missing(&state, &progress).await;
67            match &result {
68                Ok(report) => tracing::info!(
69                    players_fetched = report.players_fetched,
70                    teams_fetched = report.teams_fetched,
71                    failed = report.failed,
72                    skipped = report.skipped,
73                    duration_ms = started.elapsed().as_millis() as u64,
74                    "avatar fetch completed"
75                ),
76                Err(error) => tracing::error!(
77                    error = %error,
78                    duration_ms = started.elapsed().as_millis() as u64,
79                    "avatar fetch failed"
80                ),
81            }
82            result.map_err(|error| error.to_string())
83        }
84        .instrument(span)
85    });
86    if !started {
87        // Refusal is not a start.
88        tracing::debug!(job = "avatar_fetch", "avatar fetch already running");
89    }
90    started
91}
92
93async fn fetch_missing_with<F>(
94    state: &AppState,
95    progress: &Progress<FetchProgress, FetchReport>,
96    team_url: F,
97) -> Result<FetchReport, AppError>
98where
99    F: Fn(&str) -> String,
100{
101    let players = headshot_service::missing_headshots(state).await?;
102    let teams = team_store::missing_logos(state.db.reader()).await?;
103    let total = players.len() + teams.len();
104    let mut report = FetchReport::default();
105    publish(progress, total, &report);
106    let identities = if players.is_empty() {
107        HashMap::new()
108    } else {
109        state.nfl.identify(&players).await?
110    };
111    let client = reqwest::Client::new();
112
113    for player in players {
114        let Some(identity) = identities.get(&player) else {
115            report.skipped += 1;
116            publish(progress, total, &report);
117            continue;
118        };
119        let Some(url) = identity.headshot_url.as_deref() else {
120            report.skipped += 1;
121            publish(progress, total, &report);
122            continue;
123        };
124        let processed = match fetch_image(&client, url, MAX_HEADSHOT_BYTES).await {
125            Ok(image) => image,
126            Err(error) => {
127                warn!(
128                    nfl_player_id = %player.0,
129                    url,
130                    %error,
131                    "failed to fetch player headshot"
132                );
133                report.failed += 1;
134                publish(progress, total, &report);
135                continue;
136            }
137        };
138        let path = format!("headshots/{}.png", player.0);
139        if let Err(error) = state
140            .db
141            .write_tx(async |conn| -> Result<(), AppError> {
142                let media_id = save_avatar(conn, state, &path, &processed).await?;
143                player_store::set_headshot_media_id(&mut *conn, &player, media_id).await?;
144                Ok(())
145            })
146            .await
147        {
148            warn!(
149                nfl_player_id = %player.0,
150                %error,
151                "failed to save player headshot"
152            );
153            report.failed += 1;
154            publish(progress, total, &report);
155            continue;
156        }
157        report.players_fetched += 1;
158        publish(progress, total, &report);
159    }
160
161    for team in teams {
162        let url = team_url(&team.abbr);
163        let processed = match fetch_image(&client, &url, MAX_TEAM_LOGO_BYTES).await {
164            Ok(image) => image,
165            Err(error) => {
166                warn!(abbr = %team.abbr, url, %error, "failed to fetch team logo");
167                report.failed += 1;
168                publish(progress, total, &report);
169                continue;
170            }
171        };
172        let path = format!("logos/{}.png", team.abbr);
173        if let Err(error) = state
174            .db
175            .write_tx(async |conn| -> Result<(), AppError> {
176                let media_id = save_avatar(conn, state, &path, &processed).await?;
177                team_store::set_logo_media_id(&mut *conn, &team.abbr, media_id).await?;
178                Ok(())
179            })
180            .await
181        {
182            warn!(abbr = %team.abbr, %error, "failed to save team logo");
183            report.failed += 1;
184            publish(progress, total, &report);
185            continue;
186        }
187        report.teams_fetched += 1;
188        publish(progress, total, &report);
189    }
190
191    Ok(report)
192}
193
194/// Save an avatar at its stable path. A media row already at that path (for
195/// example one left behind by an unlink) is reused, because `media.path` is
196/// unique and a fresh insert would fail on every run.
197async fn save_avatar(
198    conn: &mut sqlx::SqliteConnection,
199    state: &AppState,
200    path: &str,
201    processed: &ProcessedImage,
202) -> Result<media::MediaId, AppError> {
203    let existing = media_store::get_by_path(&mut *conn, path)
204        .await?
205        .map(|row| row.id);
206    media::save_png(
207        conn,
208        &state.config.media_dir,
209        existing,
210        Some(path),
211        &processed.png,
212        processed.width,
213        processed.height,
214    )
215    .await
216}
217
218/// Progress is the report so far plus the item count, so the panel and the
219/// final report can never disagree.
220fn publish(progress: &Progress<FetchProgress, FetchReport>, total: usize, report: &FetchReport) {
221    progress.update(|p| {
222        *p = FetchProgress {
223            total,
224            fetched: report.players_fetched + report.teams_fetched,
225            failed: report.failed,
226            skipped: report.skipped,
227        }
228    });
229}
230
231async fn read_bounded_image_body(
232    response: reqwest::Response,
233    max_bytes: usize,
234) -> Result<Vec<u8>, String> {
235    let content_length = response.content_length();
236    if content_length.is_some_and(|length| length > max_bytes as u64) {
237        return Err(oversized_image_error(max_bytes));
238    }
239
240    let mut response = response;
241    let mut bytes = Vec::with_capacity(
242        content_length
243            .unwrap_or_default()
244            .min(INITIAL_BODY_CAPACITY) as usize,
245    );
246    while let Some(chunk) = response.chunk().await.map_err(|error| error.to_string())? {
247        if chunk.len() > max_bytes - bytes.len() {
248            return Err(oversized_image_error(max_bytes));
249        }
250        bytes.extend_from_slice(&chunk);
251    }
252    Ok(bytes)
253}
254
255async fn fetch_image(
256    client: &reqwest::Client,
257    url: &str,
258    max_bytes: usize,
259) -> Result<ProcessedImage, String> {
260    let response = client
261        .get(url)
262        .timeout(Duration::from_secs(10))
263        .send()
264        .await
265        .map_err(|error| error.to_string())?
266        .error_for_status()
267        .map_err(|error| error.to_string())?;
268    let bytes = read_bounded_image_body(response, max_bytes).await?;
269    tokio::task::spawn_blocking(move || media::process::process_avatar(&bytes))
270        .await
271        .map_err(|error| error.to_string())?
272        .map_err(|error| error.to_string())
273}
274
275#[cfg(test)]
276mod tests {
277    use std::io::Cursor;
278
279    use image::{DynamicImage, ImageFormat, RgbImage};
280    use nfl_model::NflPlayerId;
281    use sqlx::SqlitePool;
282    use uuid::Uuid;
283    use wiremock::matchers::{method, path};
284    use wiremock::{Mock, MockServer, ResponseTemplate};
285
286    use super::*;
287    use crate::media::{MediaId, store as media_store};
288    use crate::tests::TestApp;
289    use crate::tests::{headshot_player, headshot_salary_games, publish_headshot_slate};
290    use utils::background::{Progress, RunnerState};
291
292    /// A progress handle bound to a runner that is `Running`, so `update`
293    /// calls land somewhere a test can read back. The returned sender must
294    /// be held for the lifetime of the test's `fetch_missing_with` call —
295    /// dropping it early ends the job and returns the runner to `Idle`.
296    fn test_progress(
297        app: &TestApp,
298    ) -> (
299        Progress<FetchProgress, FetchReport>,
300        tokio::sync::oneshot::Sender<()>,
301    ) {
302        let runner = app.state.avatar_runner.clone();
303        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
304        assert!(runner.try_start(FetchProgress::default(), |_| async move {
305            let _ = rx.await;
306            Ok(FetchReport::default())
307        }));
308        (Progress::for_test(runner), tx)
309    }
310
311    fn image_bytes(width: u32, height: u32, format: ImageFormat) -> Vec<u8> {
312        let image = DynamicImage::ImageRgb8(RgbImage::new(width, height));
313        let mut bytes = Cursor::new(Vec::new());
314        image.write_to(&mut bytes, format).expect("encode image");
315        bytes.into_inner()
316    }
317
318    async fn dummy_media(pool: &SqlitePool) -> MediaId {
319        let path = format!("dummy-{}.png", Uuid::new_v4());
320        media_store::insert(pool, &path, "image/png", 1, 1, 1)
321            .await
322            .expect("dummy media")
323    }
324
325    async fn link_teams(pool: &SqlitePool, missing: Option<&str>) {
326        let media_id = dummy_media(pool).await;
327        let mut query = sqlx::query("UPDATE nfl_teams SET logo_media_id = ?1");
328        if let Some(abbr) = missing {
329            query = sqlx::query("UPDATE nfl_teams SET logo_media_id = ?1 WHERE abbr <> ?2")
330                .bind(media_id)
331                .bind(abbr);
332        } else {
333            query = query.bind(media_id);
334        }
335        query.execute(pool).await.expect("link teams");
336    }
337
338    async fn team_logo_id(pool: &SqlitePool) -> Option<i64> {
339        sqlx::query_scalar("SELECT logo_media_id FROM nfl_teams WHERE abbr = 'KC'")
340            .fetch_one(pool)
341            .await
342            .expect("team media id")
343    }
344
345    #[test]
346    fn espn_logo_url_uses_nflverse_abbreviations() {
347        assert_eq!(
348            espn_logo_url("KC"),
349            "https://a.espncdn.com/i/teamlogos/nfl/500/kc.png"
350        );
351        assert_eq!(
352            espn_logo_url("WAS"),
353            "https://a.espncdn.com/i/teamlogos/nfl/500/wsh.png"
354        );
355    }
356
357    #[tokio::test]
358    async fn fetch_missing_links_team_media() {
359        let app = TestApp::new().await;
360        let server = MockServer::start().await;
361        let team_body = image_bytes(200, 400, ImageFormat::Png);
362        Mock::given(method("GET"))
363            .and(path("/team.png"))
364            .respond_with(ResponseTemplate::new(200).set_body_bytes(team_body))
365            .expect(1)
366            .mount(&server)
367            .await;
368        link_teams(&app.pool, Some("KC")).await;
369
370        let state = app.state();
371        let team_url = format!("{}/team.png", server.uri());
372        let (progress, _hold) = test_progress(&app);
373        let report = fetch_missing_with(&state, &progress, |_| team_url.clone())
374            .await
375            .expect("fetch");
376
377        assert_eq!(
378            report,
379            FetchReport {
380                players_fetched: 0,
381                teams_fetched: 1,
382                failed: 0,
383                skipped: 0,
384            }
385        );
386        assert!(matches!(
387            app.state.avatar_runner.snapshot(),
388            RunnerState::Running {
389                progress: FetchProgress {
390                    total: 1,
391                    fetched: 1,
392                    failed: 0,
393                    skipped: 0
394                },
395                ..
396            }
397        ));
398        let team_media = media_store::get(
399            &app.pool,
400            MediaId(team_logo_id(&app.pool).await.expect("logo")),
401        )
402        .await
403        .expect("media")
404        .expect("team media");
405        assert_eq!((team_media.width, team_media.height), (128, 256));
406        assert_eq!(team_media.path, "logos/KC.png");
407        assert!(state.config.media_dir.join(&team_media.path).is_file());
408    }
409
410    #[tokio::test]
411    async fn fetch_missing_reuses_a_media_row_already_at_the_path() {
412        let app = TestApp::new().await;
413        let server = MockServer::start().await;
414        Mock::given(method("GET"))
415            .and(path("/team.png"))
416            .respond_with(ResponseTemplate::new(200).set_body_bytes(image_bytes(
417                64,
418                64,
419                ImageFormat::Png,
420            )))
421            .expect(1)
422            .mount(&server)
423            .await;
424        link_teams(&app.pool, Some("KC")).await;
425        let orphan = media_store::insert(&app.pool, "logos/KC.png", "image/png", 1, 1, 1)
426            .await
427            .expect("orphan row");
428
429        let state = app.state();
430        let team_url = format!("{}/team.png", server.uri());
431        let (progress, _hold) = test_progress(&app);
432        let report = fetch_missing_with(&state, &progress, |_| team_url.clone())
433            .await
434            .expect("fetch");
435
436        assert_eq!(report.teams_fetched, 1);
437        assert_eq!(report.failed, 0);
438        assert_eq!(team_logo_id(&app.pool).await, Some(orphan.0));
439        let media = media_store::get(&app.pool, orphan)
440            .await
441            .expect("media")
442            .expect("row");
443        assert_eq!((media.width, media.height), (64, 64));
444        assert!(state.config.media_dir.join(&media.path).is_file());
445    }
446
447    #[tokio::test]
448    async fn fetch_missing_counts_http_and_process_failures() {
449        let app = TestApp::new().await;
450        let server = MockServer::start().await;
451        Mock::given(method("GET"))
452            .and(path("/team.png"))
453            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad".to_vec()))
454            .expect(1)
455            .mount(&server)
456            .await;
457        link_teams(&app.pool, Some("KC")).await;
458
459        let team_url = format!("{}/team.png", server.uri());
460        let (progress, _hold) = test_progress(&app);
461        let report = fetch_missing_with(&app.state(), &progress, |_| team_url.clone())
462            .await
463            .expect("fetch");
464
465        assert_eq!(report.failed, 1);
466        assert_eq!(report.players_fetched, 0);
467        assert_eq!(report.teams_fetched, 0);
468        assert!(matches!(
469            app.state.avatar_runner.snapshot(),
470            RunnerState::Running {
471                progress: FetchProgress {
472                    total: 1,
473                    fetched: 0,
474                    failed: 1,
475                    skipped: 0
476                },
477                ..
478            }
479        ));
480        assert!(team_logo_id(&app.pool).await.is_none());
481    }
482
483    #[tokio::test]
484    async fn fetch_missing_rejects_oversized_team_body() {
485        let app = TestApp::new().await;
486        let server = MockServer::start().await;
487        Mock::given(method("GET"))
488            .and(path("/team.png"))
489            .respond_with(
490                ResponseTemplate::new(200).set_body_bytes(vec![0; MAX_TEAM_LOGO_BYTES + 1]),
491            )
492            .expect(1)
493            .mount(&server)
494            .await;
495        link_teams(&app.pool, Some("KC")).await;
496
497        let state = app.state();
498        let team_url = format!("{}/team.png", server.uri());
499        let (progress, _hold) = test_progress(&app);
500        let report = fetch_missing_with(&state, &progress, |_| team_url.clone())
501            .await
502            .expect("fetch");
503
504        assert_eq!(
505            report,
506            FetchReport {
507                players_fetched: 0,
508                teams_fetched: 0,
509                failed: 1,
510                skipped: 0,
511            }
512        );
513        assert!(team_logo_id(&app.pool).await.is_none());
514        let media_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM media")
515            .fetch_one(&app.pool)
516            .await
517            .expect("media count");
518        assert_eq!(media_count, 1);
519        assert!(
520            std::fs::read_dir(&state.config.media_dir)
521                .expect("media directory")
522                .next()
523                .is_none()
524        );
525    }
526
527    #[tokio::test]
528    async fn start_fetch_runs_in_the_background_and_records_the_report() {
529        let app = TestApp::new().await;
530        link_teams(&app.pool, None).await;
531
532        let state = app.state();
533        assert!(start_fetch(&state));
534        let last = state.avatar_runner.wait_idle().await.expect("last run");
535        assert_eq!(last.outcome, Ok(FetchReport::default()));
536    }
537
538    async fn headshot_media_id(pool: &SqlitePool, nfl_player_id: &NflPlayerId) -> Option<MediaId> {
539        sqlx::query_scalar(
540            "SELECT headshot_media_id FROM nfl_player_headshots WHERE nfl_player_id = ?1",
541        )
542        .bind(nfl_player_id)
543        .fetch_optional(pool)
544        .await
545        .expect("headshot link")
546    }
547
548    async fn media_count(pool: &SqlitePool) -> i64 {
549        sqlx::query_scalar("SELECT COUNT(*) FROM media")
550            .fetch_one(pool)
551            .await
552            .expect("media count")
553    }
554
555    async fn discovered_ids(app: &TestApp) -> Vec<NflPlayerId> {
556        let mut ids = headshot_service::missing_headshots(&app.state())
557            .await
558            .expect("discovery");
559        ids.sort_unstable();
560        ids
561    }
562
563    /// Sorted typed ids for set assertions.
564    fn nfl_player_ids(values: &[NflPlayerId]) -> Vec<NflPlayerId> {
565        let mut ids = values.to_vec();
566        ids.sort_unstable();
567        ids
568    }
569
570    /// Week-1 old id, week-2 scenarios, and an unslated id.
571    fn headshot_players(uri: &str) -> Vec<nfl_data::Player> {
572        let url = |path: &str| format!("{uri}/{path}");
573        vec![
574            headshot_player(
575                NflPlayerId("00-OLD".into()),
576                "Old",
577                "Timer",
578                Some(&url("old.png")),
579            ),
580            headshot_player(
581                NflPlayerId("00-CACHED".into()),
582                "Cached",
583                "Runner",
584                Some(&url("cached.png")),
585            ),
586            headshot_player(
587                NflPlayerId("00-NEW".into()),
588                "New",
589                "Runner",
590                Some(&url("new.png")),
591            ),
592            headshot_player(
593                NflPlayerId("00-FAIL".into()),
594                "Fail",
595                "Runner",
596                Some(&url("fail.png")),
597            ),
598            headshot_player(NflPlayerId("00-NOSOURCE".into()), "No", "Source", None),
599            headshot_player(
600                NflPlayerId("00-UNSLATED".into()),
601                "Un",
602                "Slated",
603                Some(&url("unslated.png")),
604            ),
605        ]
606    }
607
608    /// Seed players/games, publish weeks 1–2, prelink cached players and teams.
609    async fn seed_headshot_scenario(app: &TestApp, uri: &str) -> Vec<nfl_data::Player> {
610        let players = headshot_players(uri);
611        app.nfl
612            .seed_for_test(&players, &headshot_salary_games())
613            .await
614            .expect("seed nflverse");
615        publish_headshot_slate(app, 1, &players[..1]).await;
616        publish_headshot_slate(app, 2, &players[1..5]).await;
617
618        let media = dummy_media(&app.pool).await;
619        player_store::set_headshot_media_id(&app.pool, &NflPlayerId("00-CACHED".into()), media)
620            .await
621            .expect("prelink cached");
622        player_store::set_headshot_media_id(
623            &app.pool,
624            &NflPlayerId("00-CACHEONLY".into()),
625            dummy_media(&app.pool).await,
626        )
627        .await
628        .expect("cache-only id");
629        link_teams(&app.pool, None).await;
630        players
631    }
632
633    fn shapless_team_url(_: &str) -> String {
634        panic!("every team already has a logo")
635    }
636
637    #[tokio::test]
638    async fn missing_headshots_follows_the_latest_published_slate() {
639        let app = TestApp::new().await;
640        // no snapshot yet
641        assert!(discovered_ids(&app).await.is_empty());
642
643        seed_headshot_scenario(&app, "http://assets.invalid").await;
644        assert_eq!(
645            discovered_ids(&app).await,
646            nfl_player_ids(&[
647                NflPlayerId("00-FAIL".into()),
648                NflPlayerId("00-NEW".into()),
649                NflPlayerId("00-NOSOURCE".into()),
650            ]),
651            "only uncached latest-slate players, without flex duplicates or the defense"
652        );
653    }
654
655    #[tokio::test]
656    async fn fetch_missing_downloads_only_uncached_latest_slate_players() {
657        let app = TestApp::new().await;
658        let server = MockServer::start().await;
659        Mock::given(method("GET"))
660            .and(path("/new.png"))
661            .respond_with(ResponseTemplate::new(200).set_body_bytes(image_bytes(
662                200,
663                400,
664                ImageFormat::Png,
665            )))
666            .expect(1)
667            .mount(&server)
668            .await;
669        Mock::given(method("GET"))
670            .and(path("/fail.png"))
671            .respond_with(ResponseTemplate::new(500))
672            .expect(1)
673            .mount(&server)
674            .await;
675        seed_headshot_scenario(&app, &server.uri()).await;
676        let cached_id = headshot_media_id(&app.pool, &NflPlayerId("00-CACHED".into()))
677            .await
678            .expect("cached");
679        // unlinked row at the stable path is reused
680        let orphan = media_store::insert(&app.pool, "headshots/00-NEW.png", "image/png", 1, 1, 1)
681            .await
682            .expect("orphan row");
683
684        let state = app.state();
685        let (progress, _hold) = test_progress(&app);
686        let report = fetch_missing_with(&state, &progress, shapless_team_url)
687            .await
688            .expect("fetch");
689
690        assert_eq!(
691            report,
692            FetchReport {
693                players_fetched: 1,
694                teams_fetched: 0,
695                failed: 1,
696                skipped: 1,
697            }
698        );
699        assert!(matches!(
700            app.state.avatar_runner.snapshot(),
701            RunnerState::Running {
702                progress: FetchProgress {
703                    total: 3,
704                    fetched: 1,
705                    failed: 1,
706                    skipped: 1
707                },
708                ..
709            }
710        ));
711
712        assert_eq!(
713            headshot_media_id(&app.pool, &NflPlayerId("00-CACHED".into())).await,
714            Some(cached_id),
715            "a cached player keeps its link"
716        );
717        assert_eq!(
718            headshot_media_id(&app.pool, &NflPlayerId("00-NEW".into())).await,
719            Some(orphan)
720        );
721        let media = media_store::get(&app.pool, orphan)
722            .await
723            .expect("media")
724            .expect("reused row");
725        assert_eq!((media.width, media.height), (128, 256));
726        assert_eq!(media.path, "headshots/00-NEW.png");
727        let bytes = std::fs::read(state.config.media_dir.join(&media.path)).expect("saved png");
728        let image = image::load_from_memory(&bytes).expect("a decodable png");
729        assert_eq!((image.width(), image.height()), (128, 256));
730        assert_eq!(
731            headshot_media_id(&app.pool, &NflPlayerId("00-FAIL".into())).await,
732            None
733        );
734        assert_eq!(
735            headshot_media_id(&app.pool, &NflPlayerId("00-NOSOURCE".into())).await,
736            None
737        );
738
739        let mut requested: Vec<String> = server
740            .received_requests()
741            .await
742            .expect("requests")
743            .into_iter()
744            .map(|request| request.url.path().to_string())
745            .collect();
746        requested.sort_unstable();
747        assert_eq!(
748            requested,
749            ["/fail.png", "/new.png"],
750            "cached, old-slate, and unslated players are never downloaded"
751        );
752
753        assert_eq!(
754            discovered_ids(&app).await,
755            nfl_player_ids(&[
756                NflPlayerId("00-FAIL".into()),
757                NflPlayerId("00-NOSOURCE".into()),
758            ]),
759            "the downloaded player is cached; failed and sourceless ones retry"
760        );
761    }
762
763    #[tokio::test]
764    async fn fetch_missing_counts_malformed_player_images_as_failures() {
765        let app = TestApp::new().await;
766        let server = MockServer::start().await;
767        Mock::given(method("GET"))
768            .and(path("/bad.png"))
769            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad".to_vec()))
770            .expect(1)
771            .mount(&server)
772            .await;
773        let player = headshot_player(
774            NflPlayerId("00-BAD".into()),
775            "Bad",
776            "Image",
777            Some(&format!("{}/bad.png", server.uri())),
778        );
779        app.nfl
780            .seed_for_test(std::slice::from_ref(&player), &headshot_salary_games())
781            .await
782            .expect("seed nflverse");
783        publish_headshot_slate(&app, 1, std::slice::from_ref(&player)).await;
784        link_teams(&app.pool, None).await;
785
786        let state = app.state();
787        let (progress, _hold) = test_progress(&app);
788        let report = fetch_missing_with(&state, &progress, shapless_team_url)
789            .await
790            .expect("fetch");
791
792        assert_eq!(
793            report,
794            FetchReport {
795                players_fetched: 0,
796                teams_fetched: 0,
797                failed: 1,
798                skipped: 0,
799            }
800        );
801        assert_eq!(
802            headshot_media_id(&app.pool, &NflPlayerId("00-BAD".into())).await,
803            None
804        );
805        assert_eq!(media_count(&app.pool).await, 1, "only the team's dummy row");
806    }
807
808    #[tokio::test]
809    async fn fetch_missing_rolls_back_when_the_media_file_cannot_be_written() {
810        let app = TestApp::new().await;
811        let server = MockServer::start().await;
812        Mock::given(method("GET"))
813            .and(path("/save.png"))
814            .respond_with(ResponseTemplate::new(200).set_body_bytes(image_bytes(
815                64,
816                64,
817                ImageFormat::Png,
818            )))
819            .expect(1)
820            .mount(&server)
821            .await;
822        let player = headshot_player(
823            NflPlayerId("00-SAVE".into()),
824            "Save",
825            "Failure",
826            Some(&format!("{}/save.png", server.uri())),
827        );
828        app.nfl
829            .seed_for_test(std::slice::from_ref(&player), &headshot_salary_games())
830            .await
831            .expect("seed nflverse");
832        publish_headshot_slate(&app, 1, std::slice::from_ref(&player)).await;
833        link_teams(&app.pool, None).await;
834
835        // a file at the media dir fails every write
836        let media_dir = app.state.config.media_dir.clone();
837        std::fs::remove_dir_all(&media_dir).expect("remove media dir");
838        std::fs::write(&media_dir, b"not a directory").expect("replace media dir");
839
840        let state = app.state();
841        let (progress, _hold) = test_progress(&app);
842        let report = fetch_missing_with(&state, &progress, shapless_team_url)
843            .await
844            .expect("fetch");
845
846        assert_eq!(
847            report,
848            FetchReport {
849                players_fetched: 0,
850                teams_fetched: 0,
851                failed: 1,
852                skipped: 0,
853            }
854        );
855        assert_eq!(
856            headshot_media_id(&app.pool, &NflPlayerId("00-SAVE".into())).await,
857            None
858        );
859        assert_eq!(
860            media_count(&app.pool).await,
861            1,
862            "the failed save committed no media row"
863        );
864    }
865}