Skip to main content

bitbucket_cli/api/
client.rs

1use anyhow::{Context, Result};
2use reqwest::{Client, Response, StatusCode};
3use serde::de::DeserializeOwned;
4
5use crate::auth::{AuthManager, Credential, OAuthFlow};
6use crate::models::Paginated;
7
8const API_BASE_URL: &str = "https://api.bitbucket.org/2.0";
9
10/// User-Agent header sent with every request, versioned from Cargo metadata.
11pub(crate) const USER_AGENT: &str = concat!("bitbucket-cli/", env!("CARGO_PKG_VERSION"));
12
13/// Bitbucket API client
14#[derive(Clone)]
15pub struct BitbucketClient {
16    client: Client,
17    credential: Credential,
18}
19
20impl BitbucketClient {
21    /// Create a new authenticated client
22    pub fn new(credential: Credential) -> Result<Self> {
23        let client = Client::builder()
24            .user_agent(USER_AGENT)
25            .timeout(std::time::Duration::from_secs(30))
26            .connect_timeout(std::time::Duration::from_secs(10))
27            .build()
28            .context("Failed to create HTTP client")?;
29
30        Ok(Self { client, credential })
31    }
32
33    /// Create a client from stored credentials, automatically refreshing if needed
34    pub async fn from_stored() -> Result<Self> {
35        let auth_manager = AuthManager::new()?;
36        let credential = auth_manager
37            .get_credentials()?
38            .context("Not authenticated. Run 'bitbucket auth login' first.")?;
39
40        // Auto-refresh if the token is expiring soon and we have everything needed
41        let credential = if credential.needs_refresh() {
42            if let (
43                Credential::OAuth {
44                    refresh_token: Some(refresh_token),
45                    ..
46                },
47                Some((client_id, client_secret)),
48            ) = (&credential, credential.oauth_consumer_credentials())
49            {
50                let flow = OAuthFlow::new(client_id.to_string(), client_secret.to_string());
51                match flow.refresh_token(&auth_manager, refresh_token).await {
52                    Ok(refreshed) => refreshed,
53                    Err(e) => {
54                        eprintln!("Warning: token refresh failed: {}", e);
55                        credential // Fall back to existing credential if refresh fails
56                    }
57                }
58            } else {
59                credential
60            }
61        } else {
62            credential
63        };
64
65        Self::new(credential)
66    }
67
68    /// Build a URL for an API endpoint
69    pub fn url(&self, path: &str) -> String {
70        format!("{}{}", API_BASE_URL, path)
71    }
72
73    /// Make a GET request
74    pub async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
75        let response = self
76            .client
77            .get(self.url(path))
78            .header("Authorization", self.credential.auth_header())
79            .send()
80            .await
81            .context("Request failed")?;
82
83        self.handle_response(response).await
84    }
85
86    /// Make a GET request with query parameters
87    pub async fn get_with_query<T: DeserializeOwned>(
88        &self,
89        path: &str,
90        query: &[(&str, &str)],
91    ) -> Result<T> {
92        let response = self
93            .client
94            .get(self.url(path))
95            .header("Authorization", self.credential.auth_header())
96            .query(query)
97            .send()
98            .await
99            .context("Request failed")?;
100
101        self.handle_response(response).await
102    }
103
104    /// Make a GET request to an absolute URL (e.g. a pagination `next` link)
105    pub(crate) async fn get_absolute<T: DeserializeOwned>(&self, url: &str) -> Result<T> {
106        let response = self
107            .client
108            .get(url)
109            .header("Authorization", self.credential.auth_header())
110            .send()
111            .await
112            .context("Request failed")?;
113
114        self.handle_response(response).await
115    }
116
117    /// Make a GET request that returns the raw response body as text
118    pub(crate) async fn get_text(&self, path: &str, accept: Option<&str>) -> Result<String> {
119        let mut request = self
120            .client
121            .get(self.url(path))
122            .header("Authorization", self.credential.auth_header());
123
124        if let Some(accept) = accept {
125            request = request.header("Accept", accept);
126        }
127
128        let response = request.send().await.context("Request failed")?;
129        let status = response.status();
130
131        if status.is_success() {
132            response
133                .text()
134                .await
135                .context("Failed to read response body")
136        } else {
137            self.handle_error(status, response).await
138        }
139    }
140
141    /// Make a GET request that returns the raw response body as bytes
142    pub(crate) async fn get_bytes(&self, path: &str) -> Result<bytes::Bytes> {
143        let response = self
144            .client
145            .get(self.url(path))
146            .header("Authorization", self.credential.auth_header())
147            .send()
148            .await
149            .context("Request failed")?;
150
151        let status = response.status();
152
153        if status.is_success() {
154            response
155                .bytes()
156                .await
157                .context("Failed to read response body")
158        } else {
159            self.handle_error(status, response).await
160        }
161    }
162
163    /// Make a POST request with JSON body
164    pub async fn post<T: DeserializeOwned, B: serde::Serialize>(
165        &self,
166        path: &str,
167        body: &B,
168    ) -> Result<T> {
169        let response = self
170            .client
171            .post(self.url(path))
172            .header("Authorization", self.credential.auth_header())
173            .json(body)
174            .send()
175            .await
176            .context("Request failed")?;
177
178        self.handle_response(response).await
179    }
180
181    /// Make a POST request without expecting a response body
182    pub async fn post_no_response<B: serde::Serialize>(&self, path: &str, body: &B) -> Result<()> {
183        let response = self
184            .client
185            .post(self.url(path))
186            .header("Authorization", self.credential.auth_header())
187            .json(body)
188            .send()
189            .await
190            .context("Request failed")?;
191
192        self.handle_empty_response(response).await
193    }
194
195    /// Make a multipart/form-data POST request, not expecting a JSON response body.
196    ///
197    /// Used for endpoints like repository downloads, which accept file uploads and
198    /// respond with `201 Created` and an empty body.
199    pub async fn post_multipart(&self, path: &str, form: reqwest::multipart::Form) -> Result<()> {
200        let response = self
201            .client
202            .post(self.url(path))
203            .header("Authorization", self.credential.auth_header())
204            .multipart(form)
205            // Uploads carry arbitrarily large bodies; the client-wide 30s
206            // timeout is tuned for JSON calls and would doom large transfers,
207            // so override it per-request (connect_timeout still applies).
208            .timeout(std::time::Duration::from_secs(900))
209            .send()
210            .await
211            .context("Request failed")?;
212
213        self.handle_empty_response(response).await
214    }
215
216    /// Make a PUT request with JSON body
217    pub async fn put<T: DeserializeOwned, B: serde::Serialize>(
218        &self,
219        path: &str,
220        body: &B,
221    ) -> Result<T> {
222        let response = self
223            .client
224            .put(self.url(path))
225            .header("Authorization", self.credential.auth_header())
226            .json(body)
227            .send()
228            .await
229            .context("Request failed")?;
230
231        self.handle_response(response).await
232    }
233
234    /// Make a DELETE request
235    pub async fn delete(&self, path: &str) -> Result<()> {
236        let response = self
237            .client
238            .delete(self.url(path))
239            .header("Authorization", self.credential.auth_header())
240            .send()
241            .await
242            .context("Request failed")?;
243
244        self.handle_empty_response(response).await
245    }
246
247    /// Fetch all pages of a paginated endpoint
248    pub async fn get_all_pages<T: DeserializeOwned>(&self, path: &str) -> Result<Vec<T>> {
249        let mut all_items = Vec::new();
250        let mut next_url: Option<String> = Some(self.url(path));
251
252        while let Some(url) = next_url {
253            let response = self
254                .client
255                .get(&url)
256                .header("Authorization", self.credential.auth_header())
257                .send()
258                .await
259                .context("Request failed")?;
260
261            let page: Paginated<T> = self.handle_response(response).await?;
262            all_items.extend(page.values);
263            next_url = page.next;
264        }
265
266        Ok(all_items)
267    }
268
269    /// Handle API response
270    async fn handle_response<T: DeserializeOwned>(&self, response: Response) -> Result<T> {
271        let status = response.status();
272
273        if status.is_success() {
274            response
275                .json()
276                .await
277                .context("Failed to parse response JSON")
278        } else {
279            self.handle_error(status, response).await
280        }
281    }
282
283    /// Handle empty response (for DELETE, etc.)
284    async fn handle_empty_response(&self, response: Response) -> Result<()> {
285        let status = response.status();
286
287        if status.is_success() {
288            Ok(())
289        } else {
290            self.handle_error(status, response).await
291        }
292    }
293
294    /// Handle API errors
295    async fn handle_error<T>(&self, status: StatusCode, response: Response) -> Result<T> {
296        let body = response.text().await.unwrap_or_default();
297
298        match status {
299            StatusCode::UNAUTHORIZED => {
300                anyhow::bail!("Authentication failed. Try running 'bitbucket auth login' again.")
301            }
302            StatusCode::FORBIDDEN => {
303                anyhow::bail!("Access denied. You don't have permission to access this resource.")
304            }
305            StatusCode::NOT_FOUND => {
306                anyhow::bail!("Resource not found.")
307            }
308            StatusCode::TOO_MANY_REQUESTS => {
309                anyhow::bail!("Rate limit exceeded. Please wait and try again.")
310            }
311            _ => {
312                // Try to parse error message from response
313                if let Ok(error) = serde_json::from_str::<ApiError>(&body) {
314                    if let Some(msg) = error.error.message {
315                        anyhow::bail!("API error: {}", msg);
316                    }
317                }
318                anyhow::bail!("API error ({}): {}", status, body)
319            }
320        }
321    }
322}
323
324#[derive(serde::Deserialize)]
325struct ApiError {
326    error: ApiErrorDetail,
327}
328
329#[derive(serde::Deserialize)]
330struct ApiErrorDetail {
331    message: Option<String>,
332}