Skip to main content

gitfox_client/
client.rs

1//! The HTTP client every other module and both front-ends (CLI, and later MCP)
2//! go through.
3
4use std::fmt;
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
8use serde::de::DeserializeOwned;
9use serde_json::Value;
10use url::Url;
11use url::form_urlencoded;
12
13use crate::auth::AuthApi;
14use crate::error::{Error, Result};
15use crate::pipeline::PipelinesApi;
16use crate::principal::PrincipalsApi;
17use crate::pull_request::PullRequestsApi;
18use crate::repo::ReposApi;
19
20pub use reqwest::Method;
21
22pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
23
24/// Attempts after the first, for requests that are safe to repeat.
25pub const DEFAULT_RETRIES: u32 = 2;
26
27/// The longest we will wait between attempts, including a server's own
28/// `Retry-After`.
29///
30/// Someone is usually watching a CLI run. A command that goes silent for
31/// minutes because a header asked it to is worse than one that gives up and
32/// says why — the caller can always run it again, and an agent can back off on
33/// its own schedule.
34const MAX_BACKOFF: Duration = Duration::from_secs(5);
35
36const USER_AGENT: &str = concat!("fx/", env!("CARGO_PKG_VERSION"));
37
38/// A GitFox API client bound to one host.
39#[derive(Clone)]
40pub struct GitFoxClient {
41    base_url: Url,
42    token: Option<String>,
43    timeout_secs: u64,
44    retries: u32,
45    http: reqwest::Client,
46}
47
48/// Redacted on purpose: the token must never reach a log line or an error
49/// message. Every `{:?}` of a client or anything holding one goes through here.
50impl fmt::Debug for GitFoxClient {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.debug_struct("GitFoxClient")
53            .field("base_url", &self.base_url.as_str())
54            .field("token", &self.token.as_ref().map(|_| "***"))
55            .field("timeout_secs", &self.timeout_secs)
56            .field("retries", &self.retries)
57            .finish()
58    }
59}
60
61impl GitFoxClient {
62    pub fn builder(host: impl Into<String>) -> GitFoxClientBuilder {
63        GitFoxClientBuilder {
64            host: host.into(),
65            token: None,
66            timeout_secs: DEFAULT_TIMEOUT_SECS,
67            retries: DEFAULT_RETRIES,
68            insecure: false,
69        }
70    }
71
72    pub fn base_url(&self) -> &Url {
73        &self.base_url
74    }
75
76    pub fn has_token(&self) -> bool {
77        self.token.is_some()
78    }
79
80    pub fn auth(&self) -> AuthApi<'_> {
81        AuthApi::new(self)
82    }
83
84    pub fn repos(&self) -> ReposApi<'_> {
85        ReposApi::new(self)
86    }
87
88    pub fn pull_requests(&self) -> PullRequestsApi<'_> {
89        PullRequestsApi::new(self)
90    }
91
92    pub fn principals(&self) -> PrincipalsApi<'_> {
93        PrincipalsApi::new(self)
94    }
95
96    pub fn pipelines(&self) -> PipelinesApi<'_> {
97        PipelinesApi::new(self)
98    }
99
100    /// Resolve an API path against the host.
101    ///
102    /// Accepts `/api/v1/user`, `api/v1/user` and a fully qualified URL, so
103    /// `fx api` can take whatever the user pasted.
104    pub fn resolve(&self, path: &str) -> Result<Url> {
105        if path.starts_with("http://") || path.starts_with("https://") {
106            return Url::parse(path).map_err(|e| Error::InvalidUrl(format!("{path}: {e}")));
107        }
108        self.base_url
109            .join(path.trim_start_matches('/'))
110            .map_err(|e| Error::InvalidUrl(format!("{path}: {e}")))
111    }
112
113    /// The one place an HTTP request is issued. Everything typed is built on top.
114    ///
115    /// Transient failures are retried with exponential backoff — but only for
116    /// methods that are safe to repeat. See [`is_retryable_method`].
117    pub async fn request(
118        &self,
119        method: Method,
120        path: &str,
121        body: Option<&Value>,
122        extra_headers: &[(String, String)],
123    ) -> Result<RawResponse> {
124        let url = self.resolve(path)?;
125        let budget = if is_retryable_method(&method) {
126            self.retries
127        } else {
128            0
129        };
130
131        let mut attempt = 0;
132        loop {
133            tracing::debug!(method = %method, url = %url, attempt, "gitfox request");
134            let outcome = self
135                .attempt(method.clone(), url.clone(), body, extra_headers)
136                .await;
137
138            let Err(error) = outcome else {
139                return outcome;
140            };
141
142            let Some(delay) = self.backoff(&error, attempt, budget) else {
143                return Err(error);
144            };
145            tracing::warn!(
146                method = %method,
147                url = %url,
148                attempt,
149                delay_ms = delay.as_millis(),
150                error = %error,
151                "transient failure; retrying"
152            );
153            tokio::time::sleep(delay).await;
154            attempt += 1;
155        }
156    }
157
158    /// One trip to the server, with no retry logic of its own.
159    async fn attempt(
160        &self,
161        method: Method,
162        url: Url,
163        body: Option<&Value>,
164        extra_headers: &[(String, String)],
165    ) -> Result<RawResponse> {
166        let mut req = self.http.request(method, url);
167        // JSON unless the caller asked for something else. The pull request
168        // diff endpoint serves either JSON or a raw unified diff depending on
169        // this header, which is the whole reason it is overridable.
170        if !extra_headers
171            .iter()
172            .any(|(name, _)| name.eq_ignore_ascii_case("accept"))
173        {
174            req = req.header(ACCEPT, "application/json");
175        }
176        if let Some(token) = &self.token {
177            let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
178                .map_err(|_| Error::Builder("token contains invalid header bytes".into()))?;
179            // Marks the header sensitive so it stays out of any logging that
180            // honours the flag.
181            value.set_sensitive(true);
182            req = req.header(AUTHORIZATION, value);
183        }
184        for (name, value) in extra_headers {
185            let name = HeaderName::from_bytes(name.as_bytes())
186                .map_err(|_| Error::Builder(format!("invalid header name `{name}`")))?;
187            let value = HeaderValue::from_str(value)
188                .map_err(|_| Error::Builder(format!("invalid value for header `{name}`")))?;
189            req = req.header(name, value);
190        }
191        if let Some(body) = body {
192            req = req.header(CONTENT_TYPE, "application/json").json(body);
193        }
194
195        let response = req.send().await.map_err(|e| self.transport_error(&e))?;
196        let status = response.status();
197        let headers = response.headers().clone();
198        let text = response
199            .text()
200            .await
201            .map_err(|e| self.transport_error(&e))?;
202        let json = if text.trim().is_empty() {
203            None
204        } else {
205            serde_json::from_str::<Value>(&text).ok()
206        };
207
208        let raw = RawResponse {
209            status: status.as_u16(),
210            headers,
211            json,
212            text,
213        };
214
215        if status.is_success() {
216            Ok(raw)
217        } else {
218            Err(self.status_error(&raw))
219        }
220    }
221
222    /// How long to wait before trying again, or `None` to give up.
223    ///
224    /// A server that said `Retry-After` is obeyed up to [`MAX_BACKOFF`];
225    /// otherwise the delay doubles each attempt from 250ms, with jitter so a
226    /// fleet of agents retrying at once does not do so in lockstep.
227    fn backoff(&self, error: &Error, attempt: u32, budget: u32) -> Option<Duration> {
228        if attempt >= budget || !is_transient(error) {
229            return None;
230        }
231        if let Error::RateLimited { retry_after, .. } = error
232            && let Some(secs) = retry_after
233        {
234            return Some(Duration::from_secs(*secs).min(MAX_BACKOFF));
235        }
236        let base = Duration::from_millis(250 * 2u64.pow(attempt.min(6)));
237        Some((base + jitter(base)).min(MAX_BACKOFF))
238    }
239
240    /// Convenience wrapper for typed GET requests.
241    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
242        self.request(Method::GET, path, None, &[])
243            .await?
244            .deserialize()
245    }
246
247    fn transport_error(&self, err: &reqwest::Error) -> Error {
248        if err.is_timeout() {
249            Error::Timeout(self.timeout_secs)
250        } else if err.is_decode() {
251            Error::Decode(err.to_string())
252        } else {
253            Error::Network(err.to_string())
254        }
255    }
256
257    fn status_error(&self, raw: &RawResponse) -> Error {
258        let fallback = if raw.text.trim().is_empty() {
259            format!("HTTP {}", raw.status)
260        } else {
261            raw.text.trim().chars().take(500).collect()
262        };
263        let message = Error::message_from_body(&raw.json, &fallback);
264        match raw.status {
265            429 => Error::RateLimited {
266                retry_after: raw
267                    .headers
268                    .get("retry-after")
269                    .and_then(|v| v.to_str().ok())
270                    .and_then(|v| v.trim().parse::<u64>().ok()),
271                message,
272            },
273            401 if self.token.is_none() => Error::AuthRequired,
274            401 | 403 => Error::AuthFailed,
275            404 => Error::NotFound {
276                kind: "resource",
277                reference: message,
278            },
279            408 | 504 => Error::Timeout(self.timeout_secs),
280            status => Error::Api {
281                status,
282                message,
283                body: raw.json.clone(),
284            },
285        }
286    }
287}
288
289/// A response that succeeded at the HTTP level, kept in both raw and parsed form
290/// so `fx api` can pass anything through untouched.
291#[derive(Debug, Clone)]
292pub struct RawResponse {
293    pub status: u16,
294    pub headers: HeaderMap,
295    pub json: Option<Value>,
296    pub text: String,
297}
298
299impl RawResponse {
300    pub fn json_or_null(&self) -> Value {
301        self.json.clone().unwrap_or(Value::Null)
302    }
303
304    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
305        let value = self
306            .json
307            .clone()
308            .ok_or_else(|| Error::Decode("expected a JSON response body".into()))?;
309        serde_json::from_value(value).map_err(|e| Error::Decode(e.to_string()))
310    }
311}
312
313pub struct GitFoxClientBuilder {
314    host: String,
315    token: Option<String>,
316    timeout_secs: u64,
317    retries: u32,
318    insecure: bool,
319}
320
321impl GitFoxClientBuilder {
322    pub fn token(mut self, token: Option<String>) -> Self {
323        self.token = token.filter(|t| !t.trim().is_empty());
324        self
325    }
326
327    pub fn timeout_secs(mut self, secs: u64) -> Self {
328        self.timeout_secs = secs;
329        self
330    }
331
332    /// How many times to try again after a transient failure. Zero disables
333    /// retrying entirely.
334    pub fn retries(mut self, retries: u32) -> Self {
335        self.retries = retries;
336        self
337    }
338
339    /// Skip TLS verification. Self-hosted instances with private CAs need it;
340    /// callers are expected to warn the user loudly when they turn it on.
341    pub fn insecure(mut self, insecure: bool) -> Self {
342        self.insecure = insecure;
343        self
344    }
345
346    pub fn build(self) -> Result<GitFoxClient> {
347        let base_url = normalize_host(&self.host)?;
348        let http = reqwest::Client::builder()
349            .user_agent(USER_AGENT)
350            .timeout(Duration::from_secs(self.timeout_secs))
351            .danger_accept_invalid_certs(self.insecure)
352            .build()
353            .map_err(|e| Error::Builder(e.to_string()))?;
354        Ok(GitFoxClient {
355            base_url,
356            token: self.token,
357            timeout_secs: self.timeout_secs,
358            retries: self.retries,
359            http,
360        })
361    }
362}
363
364/// Turn whatever the user configured into a base URL that `Url::join` behaves
365/// well against: `git.example.com` -> `https://git.example.com/`.
366pub fn normalize_host(host: &str) -> Result<Url> {
367    let host = host.trim();
368    if host.is_empty() {
369        return Err(Error::InvalidUrl("host is empty".into()));
370    }
371    let with_scheme = if host.contains("://") {
372        host.to_string()
373    } else {
374        format!("https://{host}")
375    };
376    let mut url =
377        Url::parse(&with_scheme).map_err(|e| Error::InvalidUrl(format!("{host}: {e}")))?;
378    if url.cannot_be_a_base() || url.host_str().is_none() {
379        return Err(Error::InvalidUrl(format!("{host}: missing host")));
380    }
381    if !url.path().ends_with('/') {
382        let path = format!("{}/", url.path());
383        url.set_path(&path);
384    }
385    Ok(url)
386}
387
388/// Whether repeating this method is safe.
389///
390/// `POST` is excluded on purpose. A retried `POST /pullreq` that timed out
391/// after the server accepted it would open a second pull request — silently
392/// doing the thing twice is worse than reporting that it might not have
393/// happened at all. `PATCH` is excluded for the same reason: GitFox uses it for
394/// partial updates, which are not guaranteed idempotent.
395pub fn is_retryable_method(method: &Method) -> bool {
396    matches!(
397        *method,
398        Method::GET | Method::HEAD | Method::OPTIONS | Method::PUT | Method::DELETE
399    )
400}
401
402/// Whether this failure is worth another try.
403///
404/// Deliberately narrow: a 500 is not here, because an internal error that
405/// repeats is usually a bug being hit again rather than a blip, and retrying it
406/// just triples the time before the user sees the message.
407fn is_transient(error: &Error) -> bool {
408    match error {
409        Error::Network(_) | Error::Timeout(_) | Error::RateLimited { .. } => true,
410        Error::Api { status, .. } => matches!(status, 502..=504),
411        _ => false,
412    }
413}
414
415/// Up to half the base delay, derived from the clock rather than a PRNG so the
416/// crate keeps no random-number dependency.
417fn jitter(base: Duration) -> Duration {
418    let nanos = SystemTime::now()
419        .duration_since(UNIX_EPOCH)
420        .map(|d| d.subsec_nanos() as u64)
421        .unwrap_or(0);
422    Duration::from_millis((base.as_millis() as u64 / 2).saturating_mul(nanos % 1000) / 1000)
423}
424
425/// A percent-encoded query string.
426///
427/// Kept here rather than in each endpoint module so every request encodes the
428/// same way, and so `Option` parameters can be dropped without an `if` at each
429/// call site.
430#[derive(Debug, Default, Clone)]
431pub struct Query(Vec<(String, String)>);
432
433impl Query {
434    pub fn new() -> Self {
435        Self::default()
436    }
437
438    pub fn push(&mut self, key: &str, value: impl ToString) -> &mut Self {
439        self.0.push((key.to_string(), value.to_string()));
440        self
441    }
442
443    /// Append only when the value is present, so unset filters never reach the
444    /// server as empty strings (which GitFox treats as a real filter).
445    pub fn push_opt<T: ToString>(&mut self, key: &str, value: Option<T>) -> &mut Self {
446        if let Some(value) = value {
447            self.push(key, value);
448        }
449        self
450    }
451
452    pub fn extend<T: ToString>(
453        &mut self,
454        key: &str,
455        values: impl IntoIterator<Item = T>,
456    ) -> &mut Self {
457        for value in values {
458            self.push(key, value);
459        }
460        self
461    }
462
463    pub fn is_empty(&self) -> bool {
464        self.0.is_empty()
465    }
466
467    pub fn encode(&self) -> String {
468        form_urlencoded::Serializer::new(String::new())
469            .extend_pairs(self.0.iter().map(|(k, v)| (k.as_str(), v.as_str())))
470            .finish()
471    }
472
473    /// `path?a=1&b=2`, or `path` when there is nothing to add.
474    pub fn apply(&self, path: &str) -> String {
475        if self.is_empty() {
476            return path.to_string();
477        }
478        format!("{path}?{}", self.encode())
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485
486    #[test]
487    fn adds_https_when_scheme_is_missing() {
488        assert_eq!(
489            normalize_host("git.example.com").unwrap().as_str(),
490            "https://git.example.com/"
491        );
492    }
493
494    #[test]
495    fn keeps_explicit_scheme_port_and_base_path() {
496        assert_eq!(
497            normalize_host("http://localhost:3000").unwrap().as_str(),
498            "http://localhost:3000/"
499        );
500        assert_eq!(
501            normalize_host("https://example.com/gitfox")
502                .unwrap()
503                .as_str(),
504            "https://example.com/gitfox/"
505        );
506    }
507
508    #[test]
509    fn rejects_unusable_hosts() {
510        for bad in ["", "   ", "https://"] {
511            assert!(
512                normalize_host(bad).is_err(),
513                "expected `{bad}` to be rejected"
514            );
515        }
516    }
517
518    #[test]
519    fn resolves_paths_with_and_without_leading_slash() {
520        let c = GitFoxClient::builder("https://git.example.com")
521            .build()
522            .unwrap();
523        assert_eq!(
524            c.resolve("/api/v1/user").unwrap().as_str(),
525            "https://git.example.com/api/v1/user"
526        );
527        assert_eq!(
528            c.resolve("api/v1/user").unwrap().as_str(),
529            "https://git.example.com/api/v1/user"
530        );
531    }
532
533    #[test]
534    fn resolve_preserves_a_base_path() {
535        let c = GitFoxClient::builder("https://example.com/gitfox")
536            .build()
537            .unwrap();
538        assert_eq!(
539            c.resolve("/api/v1/user").unwrap().as_str(),
540            "https://example.com/gitfox/api/v1/user"
541        );
542    }
543
544    #[test]
545    fn resolve_preserves_a_percent_encoded_slash_in_a_repo_ref() {
546        // `ai/backend` travels as one path segment, `ai%2Fbackend`. If `join`
547        // ever decoded or double-encoded it, every repo-scoped call would 404.
548        let c = GitFoxClient::builder("https://git.example.com")
549            .build()
550            .unwrap();
551        let url = c.resolve("/api/v1/repos/ai%2Fbackend/pullreq").unwrap();
552        assert_eq!(
553            url.as_str(),
554            "https://git.example.com/api/v1/repos/ai%2Fbackend/pullreq"
555        );
556    }
557
558    #[test]
559    fn resolve_keeps_a_query_string_intact() {
560        let c = GitFoxClient::builder("https://git.example.com")
561            .build()
562            .unwrap();
563        let url = c
564            .resolve("/api/v1/repos/ai%2Fbackend/pullreq?state=open&limit=30")
565            .unwrap();
566        assert_eq!(url.query(), Some("state=open&limit=30"));
567        assert_eq!(url.path(), "/api/v1/repos/ai%2Fbackend/pullreq");
568    }
569
570    #[test]
571    fn query_encodes_pairs_and_skips_absent_values() {
572        let mut q = Query::new();
573        q.push("limit", 30)
574            .push_opt("author_id", Some(7))
575            .push_opt::<String>("query", None)
576            .extend("state", ["open", "merged"]);
577        assert_eq!(
578            q.apply("/x"),
579            "/x?limit=30&author_id=7&state=open&state=merged"
580        );
581        assert_eq!(Query::new().apply("/x"), "/x");
582    }
583
584    #[test]
585    fn query_escapes_values_that_would_break_the_url() {
586        let mut q = Query::new();
587        q.push("query", "fix: auth & tokens");
588        assert_eq!(q.encode(), "query=fix%3A+auth+%26+tokens");
589    }
590
591    #[test]
592    fn an_explicit_accept_header_replaces_the_default() {
593        // Verified through the header names the builder ends up with rather
594        // than by sending: two Accept headers would make the server choose.
595        let names = ["Accept", "accept", "ACCEPT"];
596        for name in names {
597            assert!(
598                [(name.to_string(), "text/plain".to_string())]
599                    .iter()
600                    .any(|(n, _)| n.eq_ignore_ascii_case("accept")),
601                "`{name}` should be recognised as Accept"
602            );
603        }
604        assert!(
605            ![("X-Trace".to_string(), "1".to_string())]
606                .iter()
607                .any(|(n, _)| n.eq_ignore_ascii_case("accept"))
608        );
609    }
610
611    #[test]
612    fn debug_never_reveals_the_token() {
613        let c = GitFoxClient::builder("git.example.com")
614            .token(Some("super-secret-token".into()))
615            .build()
616            .unwrap();
617        let rendered = format!("{c:?}");
618        assert!(!rendered.contains("super-secret-token"), "{rendered}");
619        assert!(rendered.contains("***"), "{rendered}");
620    }
621
622    #[test]
623    fn blank_tokens_are_treated_as_absent() {
624        let c = GitFoxClient::builder("git.example.com")
625            .token(Some("   ".into()))
626            .build()
627            .unwrap();
628        assert!(!c.has_token());
629    }
630}