-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.rs
More file actions
388 lines (353 loc) · 14.3 KB
/
Copy pathapi.rs
File metadata and controls
388 lines (353 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use crate::auth;
use crate::config;
use crate::util;
use crossterm::style::Stylize;
use serde::de::DeserializeOwned;
#[derive(Clone)]
pub struct ApiClient {
client: reqwest::blocking::Client,
api_key: String,
pub api_url: String,
workspace_id: Option<String>,
sandbox_id: Option<String>,
}
impl ApiClient {
/// Create a new API client. Loads config, pre-flights a JWT session.
/// Pass `workspace_id` for endpoints that require it, or `None` for
/// workspace-less endpoints.
pub fn new(workspace_id: Option<&str>) -> Self {
let profile_config = match config::load("default") {
Ok(c) => c,
Err(e) => {
eprintln!("{e}");
std::process::exit(1);
}
};
let api_key_fallback = profile_config
.api_key
.as_deref()
.filter(|k| !k.is_empty() && *k != "PLACEHOLDER");
// Pre-flight: return the cached JWT if valid, refresh it if
// close to expiry, or mint a new one from the API key. The
// returned string is a JWT — that's what we send on the wire.
let access_token = match crate::jwt::ensure_access_token(&profile_config, api_key_fallback)
{
Ok(t) => t,
Err(e) => {
eprintln!("{}", format!("error: {e}").red());
eprintln!("Run {} to log in, or pass --api-key.", "hotdata auth".cyan());
std::process::exit(1);
}
};
Self {
client: reqwest::blocking::Client::new(),
api_key: access_token,
api_url: profile_config.api_url.to_string(),
workspace_id: workspace_id.map(String::from),
sandbox_id: std::env::var("HOTDATA_SANDBOX").ok().or_else(|| {
if crate::sandbox::find_sandbox_run_ancestor().is_some() {
eprintln!("error: sandbox has been lost -- restart the process");
std::process::exit(1);
}
profile_config.sandbox
}),
}
}
/// Test-only client (no config load). Used with a local mock HTTP server.
#[cfg(test)]
pub(crate) fn test_new(api_url: &str, api_key: &str, workspace_id: Option<&str>) -> Self {
Self {
client: reqwest::blocking::Client::new(),
api_key: api_key.to_string(),
api_url: api_url.to_string(),
workspace_id: workspace_id.map(String::from),
sandbox_id: None,
}
}
/// Prints an error for a non-2xx response and exits. On 4xx, first re-probes
/// the API key: if it's actually invalid, a clear re-auth hint is shown
/// instead of whatever cryptic body the primary endpoint returned.
fn fail_response(&self, status: reqwest::StatusCode, body: String) -> ! {
let auth_status = if status.is_client_error() {
config::load("default").ok().map(|pc| auth::check_status(&pc))
} else {
None
};
eprintln!("{}", format_fail_message(status, &body, auth_status.as_ref()).red());
std::process::exit(1);
}
fn build_request(&self, method: reqwest::Method, url: &str) -> reqwest::blocking::RequestBuilder {
let mut req = self.client.request(method, url)
.header("Authorization", format!("Bearer {}", self.api_key));
if let Some(ref ws) = self.workspace_id {
req = req.header("X-Workspace-Id", ws);
}
if let Some(ref sid) = self.sandbox_id {
// Send both headers during the session→sandbox migration window.
req = req.header("X-Session-Id", sid);
req = req.header("X-Sandbox-Id", sid);
}
req
}
/// Send via `util::send_debug` and unwrap connection errors with the
/// CLI's standard "error connecting" exit. All public HTTP methods
/// route through here so debug logging is uniform.
fn send(
&self,
builder: reqwest::blocking::RequestBuilder,
body_for_log: Option<&serde_json::Value>,
) -> (reqwest::StatusCode, String) {
match util::send_debug(&self.client, builder, body_for_log) {
Ok(pair) => pair,
Err(e) => {
eprintln!("error connecting to API: {e}");
std::process::exit(1);
}
}
}
fn parse_json<T: DeserializeOwned>(body: &str) -> T {
match serde_json::from_str(body) {
Ok(v) => v,
Err(e) => {
eprintln!("error parsing response: {e}");
std::process::exit(1);
}
}
}
/// GET request with query parameters, returns parsed response.
/// Parameters with `None` values are omitted.
pub fn get_with_params<T: DeserializeOwned>(&self, path: &str, params: &[(&str, Option<String>)]) -> T {
let filtered: Vec<(&str, &String)> = params.iter()
.filter_map(|(k, v)| v.as_ref().map(|val| (*k, val)))
.collect();
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::GET, &url).query(&filtered);
let (status, body) = self.send(req, None);
if !status.is_success() {
self.fail_response(status, body);
}
Self::parse_json(&body)
}
/// GET request, returns parsed response.
pub fn get<T: DeserializeOwned>(&self, path: &str) -> T {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::GET, &url);
let (status, body) = self.send(req, None);
if !status.is_success() {
self.fail_response(status, body);
}
Self::parse_json(&body)
}
/// GET request; returns `None` on HTTP 404. Other status codes use the same handling as
/// [`Self::get`]. Used when probing many paths where a missing resource is normal.
pub fn get_none_if_not_found<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::GET, &url);
let (status, body) = self.send(req, None);
if status == reqwest::StatusCode::NOT_FOUND {
return None;
}
if !status.is_success() {
self.fail_response(status, body);
}
Some(Self::parse_json(&body))
}
/// POST request with JSON body, returns parsed response.
pub fn post<T: DeserializeOwned>(&self, path: &str, body: &serde_json::Value) -> T {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::POST, &url).json(body);
let (status, resp_body) = self.send(req, Some(body));
if !status.is_success() {
self.fail_response(status, resp_body);
}
Self::parse_json(&resp_body)
}
/// GET request, exits only on connection error, returns raw (status, body).
/// Use for best-effort endpoints (e.g. health checks) where the caller wants
/// to handle non-2xx responses gracefully instead of aborting.
pub fn get_raw(&self, path: &str) -> (reqwest::StatusCode, String) {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::GET, &url);
self.send(req, None)
}
/// POST request with JSON body, exits on error, returns raw (status, body).
pub fn post_raw(&self, path: &str, body: &serde_json::Value) -> (reqwest::StatusCode, String) {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::POST, &url).json(body);
self.send(req, Some(body))
}
/// PATCH request with JSON body, returns parsed response.
pub fn patch<T: DeserializeOwned>(&self, path: &str, body: &serde_json::Value) -> T {
let url = format!("{}{path}", self.api_url);
let req = self.build_request(reqwest::Method::PATCH, &url).json(body);
let (status, resp_body) = self.send(req, Some(body));
if !status.is_success() {
self.fail_response(status, resp_body);
}
Self::parse_json(&resp_body)
}
/// POST with a custom request body (for file uploads). Returns raw status and body.
pub fn post_body<R: std::io::Read + Send + 'static>(
&self,
path: &str,
content_type: &str,
reader: R,
content_length: Option<u64>,
) -> (reqwest::StatusCode, String) {
let url = format!("{}{path}", self.api_url);
let mut req = self.build_request(reqwest::Method::POST, &url)
.header("Content-Type", content_type);
if let Some(len) = content_length {
req = req.header("Content-Length", len);
}
let req = req.body(reqwest::blocking::Body::new(reader));
// Body is an opaque stream — nothing meaningful to print under
// --debug, so pass `None`. Headers (including the masked
// Authorization) still log.
self.send(req, None)
}
}
/// Decide what error text to print for a failed response. Pulled out as a pure
/// function so the 4xx-to-re-auth-hint logic can be unit-tested without
/// making real HTTP calls or touching `std::process::exit`.
fn format_fail_message(
status: reqwest::StatusCode,
body: &str,
auth_status: Option<&auth::AuthStatus>,
) -> String {
if status.is_client_error() {
if let Some(auth::AuthStatus::Invalid(_)) = auth_status {
return "error: API key is invalid. Run 'hotdata auth login' (or 'hotdata auth') to re-authenticate.".to_string();
}
}
util::api_error(body.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use auth::AuthStatus;
use serde::Deserialize;
#[derive(Deserialize)]
struct Probe {
n: i32,
}
#[test]
fn get_none_if_not_found_returns_none_on_404() {
let mut server = mockito::Server::new();
let mock = server
.mock("GET", "/missing")
.match_header("Authorization", "Bearer test-key")
.with_status(404)
.create();
let api = ApiClient::test_new(&server.url(), "test-key", None);
let got: Option<Probe> = api.get_none_if_not_found("/missing");
assert!(got.is_none());
mock.assert();
}
#[test]
fn get_none_if_not_found_returns_some_on_200() {
let mut server = mockito::Server::new();
let mock = server
.mock("GET", "/ok")
.match_header("Authorization", "Bearer test-key")
.match_header("X-Workspace-Id", "ws-1")
.with_status(200)
.with_body(r#"{"n":7}"#)
.create();
let api = ApiClient::test_new(&server.url(), "test-key", Some("ws-1"));
let got: Option<Probe> = api.get_none_if_not_found("/ok");
assert_eq!(got.unwrap().n, 7);
mock.assert();
}
#[test]
fn format_fail_message_401_with_invalid_key_shows_reauth_hint() {
let msg = format_fail_message(
reqwest::StatusCode::UNAUTHORIZED,
"",
Some(&AuthStatus::Invalid(401)),
);
assert!(msg.contains("API key is invalid"));
assert!(msg.contains("hotdata auth login") || msg.contains("hotdata auth"));
}
#[test]
fn format_fail_message_404_with_invalid_key_shows_reauth_hint() {
// This is the user-reported scenario: the server masks an auth failure
// behind a 404 with an empty body. The re-auth probe catches it.
let msg = format_fail_message(
reqwest::StatusCode::NOT_FOUND,
"",
Some(&AuthStatus::Invalid(401)),
);
assert!(msg.contains("API key is invalid"), "got: {msg}");
}
#[test]
fn format_fail_message_404_with_valid_key_shows_real_error() {
// If the auth probe says the key is fine, surface the upstream body.
let body = r#"{"error":{"message":"Query run 'qrun_notreal' not found"}}"#;
let msg = format_fail_message(
reqwest::StatusCode::NOT_FOUND,
body,
Some(&AuthStatus::Authenticated),
);
assert!(!msg.contains("API key is invalid"));
assert!(msg.contains("Query run 'qrun_notreal' not found"));
}
#[test]
fn format_fail_message_400_with_valid_key_shows_real_error() {
let body = r#"{"error":{"message":"invalid_sql"}}"#;
let msg = format_fail_message(
reqwest::StatusCode::BAD_REQUEST,
body,
Some(&AuthStatus::Authenticated),
);
assert_eq!(msg, "invalid_sql");
}
#[test]
fn format_fail_message_5xx_never_shows_reauth_hint() {
// 5xx is not a client error — the auth probe is not even run, so
// `auth_status` is None from the caller and we just surface the body.
let msg = format_fail_message(
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
"server exploded",
None,
);
assert!(!msg.contains("API key is invalid"));
assert_eq!(msg, "server exploded");
}
#[test]
fn format_fail_message_4xx_connection_error_on_probe_falls_through() {
// If the probe itself couldn't reach the API, we can't claim the key
// is invalid — surface the original body instead.
let body = r#"{"error":{"message":"forbidden"}}"#;
let msg = format_fail_message(
reqwest::StatusCode::FORBIDDEN,
body,
Some(&AuthStatus::ConnectionError("tcp reset".to_string())),
);
assert!(!msg.contains("API key is invalid"));
assert_eq!(msg, "forbidden");
}
#[test]
fn format_fail_message_4xx_no_probe_result_falls_through() {
// Caller couldn't load config (None) — still surface the upstream error.
let body = "plain body";
let msg = format_fail_message(
reqwest::StatusCode::NOT_FOUND,
body,
None,
);
assert!(!msg.contains("API key is invalid"));
assert_eq!(msg, "plain body");
}
#[test]
fn format_fail_message_4xx_authenticated_probe_shows_server_message() {
// Valid key but a genuine client error — upstream message wins.
let body = r#"{"error":{"message":"workspace_not_found"}}"#;
let msg = format_fail_message(
reqwest::StatusCode::NOT_FOUND,
body,
Some(&AuthStatus::Authenticated),
);
assert_eq!(msg, "workspace_not_found");
}
}