Skip to main content

token_manager/
status.rs

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