1use crate::{
2 credentials,
3 provider::{AccountData, Provider},
4 state::{Account, atomic_write, now, read_private},
5};
6use reqwest::{blocking::Client, redirect::Policy};
7use serde::{Deserialize, Serialize};
8use std::{
9 collections::BTreeMap,
10 io::Read,
11 path::Path,
12 sync::{Arc, Mutex},
13 time::Duration,
14};
15
16#[derive(Clone, Serialize, Deserialize)]
17pub struct Row {
18 pub account: String,
19 pub provider: String,
20 pub state: String,
21 pub detail: Option<String>,
22 pub data: Option<AccountData>,
23 pub observed_at: Option<u64>,
24 pub cached: bool,
25 pub stale: bool,
26 pub experimental: bool,
27}
28#[derive(Serialize, Deserialize)]
29struct Cache {
30 provider_fingerprint: String,
31 observed_at: u64,
32 data: AccountData,
33}
34fn fetch(
35 client: &Client,
36 provider: &Provider,
37 secret: String,
38 allow_local_http: bool,
39) -> Result<AccountData, (&'static str, &'static str)> {
40 let url = provider
41 .endpoint(allow_local_http)
42 .map_err(|_| ("configuration_error", "Invalid provider URL"))?;
43 let response = client
44 .request(provider.method.into(), url)
45 .header(
46 &provider.auth.header,
47 format!("{}{}", provider.auth.prefix, secret),
48 )
49 .send()
50 .map_err(|_| ("network_error", "Account request failed or timed out"))?;
51 let status = response.status().as_u16();
52 match status {
53 200..=299 => {}
54 401 => return Err(("login_required", "Credential rejected; run login")),
55 403 => {
56 return Err((
57 "permission_denied",
58 "Credential lacks account access; see provider credential help",
59 ));
60 }
61 429 => return Err(("rate_limited", "Account endpoint rate limited; try later")),
62 300..=399 => {
63 return Err((
64 "provider_error",
65 "Redirect refused; review provider endpoint",
66 ));
67 }
68 _ => return Err(("provider_error", "Account endpoint returned an error")),
69 }
70 let mut body = Vec::new();
71 response
72 .take(1048577)
73 .read_to_end(&mut body)
74 .map_err(|_| ("network_error", "Could not read account response"))?;
75 if body.len() > 1048576 {
76 return Err(("response_error", "Account response exceeds size limit"));
77 }
78 let value = serde_json::from_slice(&body)
79 .map_err(|_| ("response_error", "Account endpoint did not return JSON"))?;
80 provider.extract(&value).map_err(|_| {
81 (
82 "response_error",
83 "Account response does not match provider mapping",
84 )
85 })
86}
87pub fn collect(
88 accounts: &[Account],
89 providers: &BTreeMap<String, Provider>,
90 cache_root: &Path,
91 cached_only: bool,
92 refresh: bool,
93 allow_local_http: bool,
94) -> anyhow::Result<Vec<Row>> {
95 let client = Client::builder()
96 .timeout(Duration::from_secs(8))
97 .connect_timeout(Duration::from_secs(3))
98 .redirect(Policy::none())
99 .build()?;
100 let queue = Mutex::new(accounts.iter().enumerate());
101 let results = Arc::new(Mutex::new(Vec::new()));
102 std::thread::scope(|scope| {
103 for _ in 0..accounts.len().min(4) {
104 let client = &client;
105 let queue = &queue;
106 let results = &results;
107 scope.spawn(move || {
108 loop {
109 let next = queue.lock().expect("queue lock").next();
110 let Some((index, account)) = next else {
111 break;
112 };
113 let mut row = Row {
114 account: account.name.clone(),
115 provider: account.provider.clone(),
116 state: "unknown".into(),
117 detail: None,
118 data: None,
119 observed_at: None,
120 cached: false,
121 stale: false,
122 experimental: false,
123 };
124 let Some(provider) = providers.get(&account.provider) else {
125 row.detail = Some("Provider definition unavailable".into());
126 results.lock().unwrap().push((index, row));
127 continue;
128 };
129 row.experimental = provider.experimental;
130 if let Some(reason) = &provider.unsupported_reason {
131 row.state = "unsupported".into();
132 row.detail = Some(reason.clone());
133 results.lock().unwrap().push((index, row));
134 continue;
135 }
136 let fingerprint = provider.fingerprint();
137 if fingerprint != account.provider_fingerprint {
138 row.state = "login_required".into();
139 row.detail =
140 Some("Provider definition changed; review it and run login".into());
141 results.lock().unwrap().push((index, row));
142 continue;
143 }
144 let cache_path = cache_root.join(format!("{}.json", account.name));
145 let cache = read_private(&cache_path)
146 .ok()
147 .and_then(|bytes| serde_json::from_slice::<Cache>(&bytes).ok())
148 .filter(|c| {
149 c.provider_fingerprint == fingerprint && c.observed_at <= now()
150 });
151 if let Some(cache) = &cache {
152 row.data = Some(cache.data.clone());
153 row.observed_at = Some(cache.observed_at);
154 row.cached = true;
155 row.stale = now().saturating_sub(cache.observed_at) > 60;
156 }
157 if cached_only || (!refresh && cache.is_some() && !row.stale) {
158 row.state = if cache.is_some() { "cached" } else { "unknown" }.into();
159 } else {
160 let fetched = credentials::resolve(account)
161 .map_err(|_| {
162 (
163 "login_required",
164 "Credential unavailable; run login or check its reference",
165 )
166 })
167 .and_then(|secret| fetch(client, provider, secret, allow_local_http));
168 match fetched {
169 Ok(data) => {
170 let observed_at = now();
171 let cache = Cache {
172 provider_fingerprint: fingerprint,
173 observed_at,
174 data: data.clone(),
175 };
176 let saved = serde_json::to_vec(&cache)
177 .ok()
178 .is_some_and(|bytes| atomic_write(&cache_path, &bytes).is_ok());
179 row.state = "ready".into();
180 row.detail = (!saved)
181 .then(|| "Live data received; cache could not be saved".into());
182 row.data = Some(data);
183 row.observed_at = Some(observed_at);
184 row.cached = false;
185 row.stale = false;
186 }
187 Err((state, detail)) => {
188 row.state = state.into();
189 row.detail = Some(if state == "permission_denied" {
190 format!(
191 "{detail}. {} Run: token-manager login {}",
192 provider.credential_help, account.name
193 )
194 } else {
195 detail.into()
196 });
197 row.stale = row.cached;
198 }
199 }
200 }
201 results.lock().unwrap().push((index, row));
202 }
203 });
204 }
205 });
206 let mut rows = results.lock().unwrap().clone();
207 rows.sort_by_key(|(index, _)| *index);
208 Ok(rows.into_iter().map(|(_, row)| row).collect())
209}
210pub fn table(rows: &[Row]) -> String {
211 let mut output = format!(
212 "{:<20} {:<16} {:<25} {}\n",
213 "ACCOUNT", "PROVIDER", "STATUS", "ACCOUNT DATA"
214 );
215 if rows.is_empty() {
216 output.push_str("No accounts yet. Run: token-manager add vercel\n");
217 }
218 for row in rows {
219 let mut values = Vec::new();
220 if let Some(data) = &row.data {
221 for balance in &data.balances {
222 values.push(format!(
223 "{} {} remaining{}",
224 balance.currency,
225 balance.remaining,
226 balance
227 .used
228 .as_ref()
229 .map(|used| format!("; {used} used"))
230 .unwrap_or_default()
231 ));
232 }
233 for quota in &data.quotas {
234 let absolute = if quota.unit.is_some() {
235 format!(
236 "{} / {} {} used; ",
237 quota.used.as_deref().unwrap_or("?"),
238 quota.limit.as_deref().unwrap_or("?"),
239 quota.unit.as_deref().unwrap_or("units")
240 )
241 } else {
242 String::new()
243 };
244 values.push(format!(
245 "{}: {}{}{}",
246 quota.label,
247 absolute,
248 quota
249 .used_percent
250 .as_ref()
251 .map(|p| format!("{p}% used"))
252 .unwrap_or_else(|| "not available".into()),
253 quota
254 .reset_at
255 .as_ref()
256 .map(|s| format!("; resets {s}"))
257 .unwrap_or_default()
258 ));
259 }
260 }
261 if values.is_empty() {
262 values.push("not available".into());
263 }
264 output.push_str(&format!(
265 "{:<20} {:<16} {:<25} {}\n",
266 row.account,
267 row.provider,
268 row.state,
269 values.join(" | ")
270 ));
271 if let Some(when) = row.observed_at {
272 output.push_str(&format!(
273 " {} ยท observed {}s ago\n",
274 if row.stale {
275 "STALE cached data"
276 } else if row.cached {
277 "cached"
278 } else {
279 "live"
280 },
281 now().saturating_sub(when)
282 ));
283 }
284 if let Some(detail) = &row.detail {
285 output.push_str(&format!(" {detail}\n"));
286 }
287 if row.experimental {
288 output.push_str(" Experimental account endpoint; schema may change.\n");
289 }
290 }
291 output
292}