1use crate::provider::{AccountData, Provider};
3use anyhow::{Context, Result, ensure};
4use reqwest::blocking::Client;
5use rust_decimal::Decimal;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::{
9 collections::{BTreeMap, BTreeSet},
10 io::Read,
11 str::FromStr,
12};
13
14#[derive(Clone, Deserialize, Serialize)]
15#[serde(deny_unknown_fields)]
16pub struct CostMap {
17 pub start_parameter: String,
18 pub end_parameter: String,
19 pub time_format: TimeFormat,
20 #[serde(default)]
21 pub query: BTreeMap<String, String>,
22 pub rows: String,
23 pub nested_rows: Option<String>,
24 pub amount: String,
25 pub currency: String,
26 pub divisor: u32,
27 pub has_more: String,
28 pub next_page: String,
29 pub page_parameter: String,
30}
31#[derive(Clone, Deserialize, Serialize)]
32#[serde(rename_all = "snake_case")]
33pub enum TimeFormat {
34 UnixSeconds,
35 Rfc3339,
36}
37#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
38pub struct Cost {
39 pub currency: String,
40 pub amount: Option<String>,
41 pub starting_at: String,
42 pub ending_at: String,
43}
44impl CostMap {
45 pub fn validate(&self) -> Result<()> {
46 ensure!(self.divisor > 0, "cost divisor must be positive");
47 for pointer in [
48 &self.rows,
49 &self.amount,
50 &self.currency,
51 &self.has_more,
52 &self.next_page,
53 ]
54 .into_iter()
55 .chain(self.nested_rows.iter())
56 {
57 ensure!(
58 pointer.starts_with('/'),
59 "cost mapping requires JSON pointers"
60 );
61 }
62 let params = [
63 &self.start_parameter,
64 &self.end_parameter,
65 &self.page_parameter,
66 ];
67 ensure!(
68 params.iter().collect::<BTreeSet<_>>().len() == 3,
69 "cost parameters must be distinct"
70 );
71 for name in params.into_iter().chain(self.query.keys()) {
72 ensure!(
73 !name.is_empty()
74 && name.len() <= 64
75 && name
76 .bytes()
77 .all(|b| b.is_ascii_alphanumeric() || b"_[]".contains(&b)),
78 "invalid cost query parameter"
79 );
80 }
81 ensure!(
82 !self.query.keys().any(|k| params.contains(&k)),
83 "fixed queries cannot override cost window or pagination"
84 );
85 Ok(())
86 }
87 pub fn page(&self, value: &Value) -> Result<(Option<Decimal>, Option<String>)> {
88 let rows = value
89 .pointer(&self.rows)
90 .and_then(Value::as_array)
91 .context("cost rows missing")?;
92 let mut total: Option<Decimal> = None;
93 for row in rows {
94 let entries: Vec<&Value> = if let Some(pointer) = &self.nested_rows {
95 row.pointer(pointer)
96 .and_then(Value::as_array)
97 .context("cost bucket missing results")?
98 .iter()
99 .collect()
100 } else {
101 vec![row]
102 };
103 for entry in entries {
104 let currency = entry
105 .pointer(&self.currency)
106 .and_then(Value::as_str)
107 .context("cost currency missing")?;
108 ensure!(
109 currency.eq_ignore_ascii_case("usd"),
110 "unexpected cost currency"
111 );
112 let raw = entry.pointer(&self.amount).context("cost amount missing")?;
113 let text = match raw {
114 Value::String(s) => s.clone(),
115 Value::Number(n) => n.to_string(),
116 _ => anyhow::bail!("cost amount unavailable"),
117 };
118 let amount = Decimal::from_str(&text)
119 .context("invalid cost amount")?
120 .checked_div(Decimal::from(self.divisor))
121 .context("cost overflow")?;
122 total = Some(
123 total
124 .unwrap_or_default()
125 .checked_add(amount)
126 .context("cost overflow")?,
127 );
128 }
129 }
130 let more = value
131 .pointer(&self.has_more)
132 .and_then(Value::as_bool)
133 .context("cost pagination missing")?;
134 let next = if more {
135 let cursor = value
136 .pointer(&self.next_page)
137 .and_then(Value::as_str)
138 .context("cost cursor missing")?;
139 ensure!(
140 !cursor.is_empty() && cursor.len() <= 2048 && !cursor.chars().any(char::is_control),
141 "invalid cost cursor"
142 );
143 Some(cursor.to_owned())
144 } else {
145 None
146 };
147 Ok((total, next))
148 }
149}
150fn timestamp(seconds: u64) -> Result<String> {
151 chrono::DateTime::from_timestamp(i64::try_from(seconds)?, 0)
152 .map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
153 .context("invalid cost timestamp")
154}
155type FetchError = (&'static str, &'static str);
156pub fn fetch(
157 client: &Client,
158 provider: &Provider,
159 secret: &str,
160 local: bool,
161) -> Result<AccountData, FetchError> {
162 let map = provider
163 .costs
164 .as_ref()
165 .ok_or(("configuration_error", "Cost mapping missing"))?;
166 let end = crate::state::now() / 86400 * 86400;
168 let start = end.saturating_sub(30 * 86400);
169 let starting_at =
170 timestamp(start).map_err(|_| ("configuration_error", "Invalid cost window"))?;
171 let ending_at = timestamp(end).map_err(|_| ("configuration_error", "Invalid cost window"))?;
172 let mut url = provider
173 .endpoint(local)
174 .map_err(|_| ("configuration_error", "Invalid provider URL"))?;
175 let (start_value, end_value) = match map.time_format {
176 TimeFormat::UnixSeconds => (start.to_string(), end.to_string()),
177 TimeFormat::Rfc3339 => (starting_at.clone(), ending_at.clone()),
178 };
179 url.query_pairs_mut()
180 .append_pair(&map.start_parameter, &start_value)
181 .append_pair(&map.end_parameter, &end_value)
182 .extend_pairs(&map.query);
183 let mut cursor: Option<String> = None;
184 let mut seen = BTreeSet::new();
185 let mut total: Option<Decimal> = None;
186 for _ in 0..16 {
187 let mut page_url = url.clone();
188 if let Some(cursor) = &cursor {
189 page_url
190 .query_pairs_mut()
191 .append_pair(&map.page_parameter, cursor);
192 }
193 let mut request = client.get(page_url).header(
194 &provider.auth.header,
195 format!("{}{}", provider.auth.prefix, secret),
196 );
197 for (name, value) in &provider.headers {
198 request = request.header(name, value);
199 }
200 let response = request
201 .send()
202 .map_err(|_| ("network_error", "Cost request failed or timed out"))?;
203 match response.status().as_u16() {
204 200..=299 => {}
205 401 => return Err(("login_required", "Credential rejected; run login")),
206 403 => return Err(("permission_denied", "Credential lacks cost-report access")),
207 429 => return Err(("rate_limited", "Cost endpoint rate limited; try later")),
208 _ => {
209 return Err((
210 "provider_error",
211 "Cost endpoint returned an error or redirect",
212 ));
213 }
214 }
215 let mut body = Vec::new();
216 response
217 .take(1048577)
218 .read_to_end(&mut body)
219 .map_err(|_| ("network_error", "Could not read cost response"))?;
220 if body.len() > 1048576 {
221 return Err(("response_error", "Cost response exceeds size limit"));
222 }
223 let value = serde_json::from_slice(&body)
224 .map_err(|_| ("response_error", "Cost endpoint did not return JSON"))?;
225 let (amount, next) = map.page(&value).map_err(|_| {
226 (
227 "response_error",
228 "Cost response does not match provider mapping",
229 )
230 })?;
231 if let Some(amount) = amount {
232 total = Some(
233 total
234 .unwrap_or_default()
235 .checked_add(amount)
236 .ok_or(("response_error", "Cost arithmetic overflow"))?,
237 );
238 }
239 match next {
240 Some(next) => {
241 if !seen.insert(next.clone()) {
242 return Err(("response_error", "Cost pagination repeated a cursor"));
243 }
244 cursor = Some(next);
245 }
246 None => {
247 return Ok(AccountData {
248 costs: vec![Cost {
249 currency: "USD".into(),
250 amount: total.map(|n| n.normalize().to_string()),
251 starting_at,
252 ending_at,
253 }],
254 ..Default::default()
255 });
256 }
257 }
258 }
259 Err((
260 "response_error",
261 "Cost report exceeds pagination limit; partial totals discarded",
262 ))
263}