Skip to main content

tank01_data/
injuries.rs

1use std::collections::HashMap;
2
3use nfl_model::{
4    EspnPlayerId, InjuryDesignation, InjuryEntry, InjuryProvider, InjuryReport, LiveProviderError,
5    ProviderOutcome, ProviderResponse, TeamAbbr,
6};
7use serde::Deserialize;
8use serde_json::Value;
9use time::Date;
10
11use crate::client::Tank01Client;
12
13const INJURIES_ENDPOINT: &str = "getNFLInjuriesByDate";
14
15const COMPACT_DATE: &[time::format_description::BorrowedFormatItem<'static>] =
16    time::macros::format_description!("[year][month padding:zero][day padding:zero]");
17
18#[derive(Deserialize)]
19#[serde(rename_all = "camelCase")]
20struct RawBody {
21    inj_list: Option<Vec<RawRow>>,
22    inj_date: Option<String>,
23}
24
25#[derive(Deserialize)]
26#[serde(rename_all = "camelCase")]
27struct RawRow {
28    #[serde(rename = "playerID")]
29    player_id: Option<String>,
30    long_name: String,
31    team: Option<String>,
32    pos: Option<String>,
33    designation: String,
34}
35
36impl Tank01Client {
37    /// Preserves duplicate source rows; the legacy trait adapter is last-row-wins.
38    pub async fn current_injuries(&self) -> ProviderResponse<InjuryReport> {
39        self.request_injuries().await
40    }
41
42    async fn request_injuries(&self) -> ProviderResponse<InjuryReport> {
43        let observation = self.request(INJURIES_ENDPOINT, &[]).await;
44        let parsed = Tank01Client::classify_http(&observation).and_then(Tank01Client::parse);
45        match parsed {
46            Ok(report) => Tank01Client::response(observation, ProviderOutcome::Value(report)),
47            Err(LiveProviderError::Normalization { .. }) => Tank01Client::response(
48                observation,
49                ProviderOutcome::Pregame {
50                    message: "injuries body unavailable".into(),
51                },
52            ),
53            Err(error) => Tank01Client::response(observation, ProviderOutcome::Error(error)),
54        }
55    }
56
57    fn parse(value: &Value) -> Result<InjuryReport, LiveProviderError> {
58        let body = value
59            .get("body")
60            .filter(|body| body.is_object())
61            .ok_or_else(|| LiveProviderError::Normalization {
62                message: "injuries body missing".into(),
63            })?;
64        let raw = RawBody::deserialize(body).map_err(|error| LiveProviderError::Normalization {
65            message: format!("injuries body malformed: {error}"),
66        })?;
67        let inj_list = raw
68            .inj_list
69            .ok_or_else(|| LiveProviderError::Normalization {
70                message: "injList missing".into(),
71            })?;
72
73        Ok(InjuryReport {
74            report_date: raw
75                .inj_date
76                .as_deref()
77                .and_then(|raw| Date::parse(raw, COMPACT_DATE).ok()),
78            entries: inj_list.iter().filter_map(map_row).collect(),
79        })
80    }
81}
82
83fn dedupe_by_espn_id(entries: Vec<InjuryEntry>) -> Vec<InjuryEntry> {
84    let mut out: Vec<InjuryEntry> = Vec::with_capacity(entries.len());
85    let mut slots: HashMap<String, usize> = HashMap::new();
86    for entry in entries {
87        match entry.espn_id.as_ref() {
88            Some(EspnPlayerId(key)) => match slots.get(key).copied() {
89                Some(slot) => out[slot] = entry,
90                None => {
91                    slots.insert(key.clone(), out.len());
92                    out.push(entry);
93                }
94            },
95            None => out.push(entry),
96        }
97    }
98    out
99}
100
101fn map_row(raw: &RawRow) -> Option<InjuryEntry> {
102    let designation = match raw.designation.as_str() {
103        "Q" => InjuryDesignation::Questionable,
104        "D" => InjuryDesignation::Doubtful,
105        "O" => InjuryDesignation::Out,
106        "IR" => InjuryDesignation::InjuredReserve,
107        other => {
108            tracing::warn!(
109                player = %raw.long_name,
110                code = %other,
111                "unknown injury designation; dropping row"
112            );
113            return None;
114        }
115    };
116    let team = raw
117        .team
118        .as_deref()
119        .map(str::trim)
120        .filter(|team| !team.is_empty())
121        .and_then(|team| team.parse::<TeamAbbr>().ok());
122    let player_id = raw
123        .player_id
124        .as_deref()
125        .filter(|id| !id.is_empty())
126        .map(|id| EspnPlayerId(id.into()));
127    Some(InjuryEntry {
128        espn_id: player_id,
129        name: raw.long_name.clone(),
130        team,
131        position: raw.pos.clone(),
132        designation,
133    })
134}
135
136impl InjuryProvider for Tank01Client {
137    async fn current_injuries(&self) -> ProviderResponse<InjuryReport> {
138        let mut response = Tank01Client::current_injuries(self).await;
139        if let ProviderOutcome::Value(report) = &mut response.outcome {
140            report.entries = dedupe_by_espn_id(std::mem::take(&mut report.entries));
141        }
142        response
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use std::time::Duration;
149
150    use nfl_model::LiveProviderError;
151    use utils::Secret;
152
153    use wiremock::matchers::{method, path};
154    use wiremock::{Mock, MockServer, ResponseTemplate};
155
156    use super::*;
157    use crate::config::Tank01Config;
158
159    fn client(server: &MockServer) -> Tank01Client {
160        Tank01Client::new(
161            Tank01Config::new(Secret::new("secret-key"))
162                .with_base_url(server.uri())
163                .with_rapidapi_host("mock.rapidapi.example")
164                .with_timeout(Duration::from_secs(5)),
165        )
166        .unwrap()
167    }
168
169    fn bodies() -> Vec<Value> {
170        include_str!("../tests/fixtures/tank01_injury_bodies.ndjson")
171            .lines()
172            .filter(|line| !line.trim().is_empty())
173            .map(|line| {
174                let envelope: Value = serde_json::from_str(line).unwrap();
175                envelope["body"].clone()
176            })
177            .collect()
178    }
179
180    #[tokio::test]
181    async fn concrete_injuries_keep_every_normalized_row_in_source_order() {
182        let server = MockServer::start().await;
183        let body = bodies()[0].clone();
184        Mock::given(method("GET"))
185            .and(path("/getNFLInjuriesByDate"))
186            .respond_with(
187                ResponseTemplate::new(200)
188                    .insert_header("content-type", "application/json")
189                    .set_body_json(body),
190            )
191            .expect(1)
192            .mount(&server)
193            .await;
194
195        let response = client(&server).current_injuries().await;
196        assert_eq!(response.http_status, Some(200));
197        let report = match &response.outcome {
198            ProviderOutcome::Value(report) => report,
199            other => panic!("expected parsed injuries, got {other:?}"),
200        };
201        let observed: Vec<_> = report
202            .entries
203            .iter()
204            .map(|entry| (entry.name.as_str(), entry.designation))
205            .collect();
206        assert_eq!(
207            observed,
208            [
209                ("Matt Hennessy", InjuryDesignation::InjuredReserve),
210                ("Cooper Kupp", InjuryDesignation::Questionable),
211                ("Jalen Carter", InjuryDesignation::Out),
212                ("Josh Allen", InjuryDesignation::Questionable),
213                ("Cooper Kupp", InjuryDesignation::Doubtful),
214            ],
215            "every normalized row survives, including the conflicting duplicate, in source order"
216        );
217        assert_eq!(
218            report.report_date,
219            Some(time::macros::date!(2026 - 09 - 22))
220        );
221
222        let kupp = &report.entries[1];
223        assert_eq!(kupp.espn_id, Some(EspnPlayerId("18538".into())));
224        assert_eq!(kupp.team, Some(TeamAbbr::SEA));
225        assert_eq!(kupp.position.as_deref(), Some("WR"));
226    }
227
228    #[tokio::test]
229    async fn legacy_provider_deduplicates_with_the_later_row_winning() {
230        let server = MockServer::start().await;
231        let body = bodies()[0].clone();
232        Mock::given(method("GET"))
233            .and(path("/getNFLInjuriesByDate"))
234            .respond_with(
235                ResponseTemplate::new(200)
236                    .insert_header("content-type", "application/json")
237                    .set_body_json(body),
238            )
239            .expect(1)
240            .mount(&server)
241            .await;
242
243        let response = InjuryProvider::current_injuries(&client(&server)).await;
244        let report = match &response.outcome {
245            ProviderOutcome::Value(report) => report,
246            other => panic!("expected parsed injuries, got {other:?}"),
247        };
248        assert_eq!(
249            report.entries.len(),
250            4,
251            "the duplicate ESPN id and the unknown designation each drop one row"
252        );
253        let kupp: Vec<_> = report
254            .entries
255            .iter()
256            .filter(|entry| entry.name == "Cooper Kupp")
257            .collect();
258        assert_eq!(kupp.len(), 1);
259        assert_eq!(kupp[0].designation, InjuryDesignation::Doubtful);
260        for (name, designation) in [
261            ("Matt Hennessy", InjuryDesignation::InjuredReserve),
262            ("Jalen Carter", InjuryDesignation::Out),
263            ("Josh Allen", InjuryDesignation::Questionable),
264        ] {
265            assert!(
266                report
267                    .entries
268                    .iter()
269                    .any(|entry| { entry.name == name && entry.designation == designation }),
270                "{name} survives with its designation"
271            );
272        }
273    }
274
275    #[tokio::test]
276    async fn treats_body_without_inj_list_as_pregame() {
277        let server = MockServer::start().await;
278        Mock::given(method("GET"))
279            .and(path("/getNFLInjuriesByDate"))
280            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
281                "statusCode": 200,
282                "body": {}
283            })))
284            .expect(1)
285            .mount(&server)
286            .await;
287
288        let response = client(&server).current_injuries().await;
289        assert!(
290            matches!(&response.outcome, ProviderOutcome::Pregame { .. }),
291            "expected pregame, got {:?}",
292            response.outcome
293        );
294        let serialized = serde_json::to_string(&response).unwrap();
295        assert!(!serialized.contains("secret-key"));
296    }
297
298    #[tokio::test]
299    async fn surfaces_http_failures_as_provider_errors() {
300        let server = MockServer::start().await;
301        Mock::given(method("GET"))
302            .and(path("/getNFLInjuriesByDate"))
303            .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
304            .expect(1)
305            .mount(&server)
306            .await;
307
308        let response = client(&server).current_injuries().await;
309        assert!(matches!(
310            &response.outcome,
311            ProviderOutcome::Error(LiveProviderError::Http { status: 500, .. })
312        ));
313    }
314}