1use std::fmt;
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use reqwest::header::{
8 ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, LOCATION,
9};
10use reqwest::redirect::Policy;
11use serde::de::DeserializeOwned;
12use serde_json::Value;
13use url::Url;
14use url::form_urlencoded;
15
16use crate::auth::AuthApi;
17use crate::error::{Error, Result};
18use crate::pipeline::PipelinesApi;
19use crate::principal::PrincipalsApi;
20use crate::pull_request::PullRequestsApi;
21use crate::repo::ReposApi;
22
23pub use reqwest::Method;
24
25pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
26
27pub const DEFAULT_RETRIES: u32 = 2;
29
30const MAX_BACKOFF: Duration = Duration::from_secs(5);
38
39const USER_AGENT: &str = concat!("fx/", env!("CARGO_PKG_VERSION"));
40
41#[derive(Clone)]
43pub struct GitFoxClient {
44 base_url: Url,
45 token: Option<String>,
46 timeout_secs: u64,
47 retries: u32,
48 http: reqwest::Client,
49 http_no_redirect: reqwest::Client,
52}
53
54impl fmt::Debug for GitFoxClient {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.debug_struct("GitFoxClient")
59 .field("base_url", &self.base_url.as_str())
60 .field("token", &self.token.as_ref().map(|_| "***"))
61 .field("timeout_secs", &self.timeout_secs)
62 .field("retries", &self.retries)
63 .finish()
64 }
65}
66
67impl GitFoxClient {
68 pub fn builder(host: impl Into<String>) -> GitFoxClientBuilder {
69 GitFoxClientBuilder {
70 host: host.into(),
71 token: None,
72 timeout_secs: DEFAULT_TIMEOUT_SECS,
73 retries: DEFAULT_RETRIES,
74 insecure: false,
75 }
76 }
77
78 pub fn base_url(&self) -> &Url {
79 &self.base_url
80 }
81
82 pub fn has_token(&self) -> bool {
83 self.token.is_some()
84 }
85
86 pub fn auth(&self) -> AuthApi<'_> {
87 AuthApi::new(self)
88 }
89
90 pub fn repos(&self) -> ReposApi<'_> {
91 ReposApi::new(self)
92 }
93
94 pub fn pull_requests(&self) -> PullRequestsApi<'_> {
95 PullRequestsApi::new(self)
96 }
97
98 pub fn principals(&self) -> PrincipalsApi<'_> {
99 PrincipalsApi::new(self)
100 }
101
102 pub fn pipelines(&self) -> PipelinesApi<'_> {
103 PipelinesApi::new(self)
104 }
105
106 pub fn resolve(&self, path: &str) -> Result<Url> {
111 if path.starts_with("http://") || path.starts_with("https://") {
112 return Url::parse(path).map_err(|e| Error::InvalidUrl(format!("{path}: {e}")));
113 }
114 self.base_url
115 .join(path.trim_start_matches('/'))
116 .map_err(|e| Error::InvalidUrl(format!("{path}: {e}")))
117 }
118
119 pub async fn request(
124 &self,
125 method: Method,
126 path: &str,
127 body: Option<&Value>,
128 extra_headers: &[(String, String)],
129 ) -> Result<RawResponse> {
130 let url = self.resolve(path)?;
131 let budget = if is_retryable_method(&method) {
132 self.retries
133 } else {
134 0
135 };
136
137 let mut attempt = 0;
138 loop {
139 tracing::debug!(method = %method, url = %url, attempt, "gitfox request");
140 let outcome = self
141 .attempt(method.clone(), url.clone(), body, extra_headers)
142 .await;
143
144 let Err(error) = outcome else {
145 return outcome;
146 };
147
148 let Some(delay) = self.backoff(&error, attempt, budget) else {
149 return Err(error);
150 };
151 tracing::warn!(
152 method = %method,
153 url = %url,
154 attempt,
155 delay_ms = delay.as_millis(),
156 error = %error,
157 "transient failure; retrying"
158 );
159 tokio::time::sleep(delay).await;
160 attempt += 1;
161 }
162 }
163
164 async fn attempt(
166 &self,
167 method: Method,
168 url: Url,
169 body: Option<&Value>,
170 extra_headers: &[(String, String)],
171 ) -> Result<RawResponse> {
172 let http = if follows_redirects(&method) {
173 &self.http
174 } else {
175 &self.http_no_redirect
176 };
177 let mut req = http.request(method.clone(), url);
178 if !extra_headers
182 .iter()
183 .any(|(name, _)| name.eq_ignore_ascii_case("accept"))
184 {
185 req = req.header(ACCEPT, "application/json");
186 }
187 if let Some(token) = &self.token {
188 let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
189 .map_err(|_| Error::Builder("token contains invalid header bytes".into()))?;
190 value.set_sensitive(true);
193 req = req.header(AUTHORIZATION, value);
194 }
195 for (name, value) in extra_headers {
196 let name = HeaderName::from_bytes(name.as_bytes())
197 .map_err(|_| Error::Builder(format!("invalid header name `{name}`")))?;
198 let value = HeaderValue::from_str(value)
199 .map_err(|_| Error::Builder(format!("invalid value for header `{name}`")))?;
200 req = req.header(name, value);
201 }
202 if let Some(body) = body {
203 req = req.header(CONTENT_TYPE, "application/json").json(body);
204 }
205
206 let response = req.send().await.map_err(|e| self.transport_error(&e))?;
207 let status = response.status();
208 let headers = response.headers().clone();
209 let text = response
210 .text()
211 .await
212 .map_err(|e| self.transport_error(&e))?;
213 let json = if text.trim().is_empty() {
214 None
215 } else {
216 serde_json::from_str::<Value>(&text).ok()
217 };
218
219 let raw = RawResponse {
220 status: status.as_u16(),
221 headers,
222 json,
223 text,
224 };
225
226 if status.is_success() {
227 return Ok(raw);
228 }
229 Err(redirect_error(&method, &raw).unwrap_or_else(|| self.status_error(&raw)))
230 }
231
232 fn backoff(&self, error: &Error, attempt: u32, budget: u32) -> Option<Duration> {
238 if attempt >= budget || !is_transient(error) {
239 return None;
240 }
241 if let Error::RateLimited { retry_after, .. } = error
242 && let Some(secs) = retry_after
243 {
244 return Some(Duration::from_secs(*secs).min(MAX_BACKOFF));
245 }
246 let base = Duration::from_millis(250 * 2u64.pow(attempt.min(6)));
247 Some((base + jitter(base)).min(MAX_BACKOFF))
248 }
249
250 pub async fn sse_lines<T: DeserializeOwned>(
262 &self,
263 path: &str,
264 idle: Duration,
265 ) -> Result<Vec<T>> {
266 let url = self.resolve(path)?;
267 tracing::debug!(url = %url, "gitfox log stream");
268
269 let mut req = self
270 .http
271 .get(url)
272 .header(ACCEPT, "text/event-stream")
273 .timeout(Duration::from_secs(60 * 60));
274 if let Some(token) = &self.token {
275 let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
276 .map_err(|_| Error::Builder("token contains invalid header bytes".into()))?;
277 value.set_sensitive(true);
278 req = req.header(AUTHORIZATION, value);
279 }
280
281 let mut response = req.send().await.map_err(|e| self.transport_error(&e))?;
282 if !response.status().is_success() {
285 let status = response.status().as_u16();
286 let text = response.text().await.unwrap_or_default();
287 let json = serde_json::from_str::<Value>(&text).ok();
288 return Err(self.status_error(&RawResponse {
289 status,
290 headers: HeaderMap::new(),
291 json,
292 text,
293 }));
294 }
295
296 let mut collected = Vec::new();
297 let mut buffer = Vec::new();
298 let mut last_event: Option<String> = None;
299
300 loop {
301 let chunk = match tokio::time::timeout(idle, response.chunk()).await {
302 Err(_) => break,
304 Ok(Ok(Some(chunk))) => chunk,
305 Ok(Ok(None)) => break,
306 Ok(Err(e)) => return Err(self.transport_error(&e)),
307 };
308 buffer.extend_from_slice(&chunk);
309
310 while let Some(newline) = buffer.iter().position(|b| *b == b'\n') {
311 let line = buffer.drain(..=newline).collect::<Vec<u8>>();
312 let line = String::from_utf8_lossy(&line);
313 let line = line.trim_end_matches(['\r', '\n']);
314
315 if let Some(name) = line.strip_prefix("event:") {
316 last_event = Some(name.trim().to_string());
317 continue;
318 }
319 let Some(payload) = line.strip_prefix("data:") else {
320 continue;
322 };
323 let payload = payload.trim();
324 if last_event.as_deref() == Some("error") {
325 return Ok(collected);
328 }
329 if let Ok(value) = serde_json::from_str::<T>(payload) {
330 collected.push(value);
331 }
332 }
333 }
334 Ok(collected)
335 }
336
337 pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
339 self.request(Method::GET, path, None, &[])
340 .await?
341 .deserialize()
342 }
343
344 fn transport_error(&self, err: &reqwest::Error) -> Error {
345 if err.is_timeout() {
346 Error::Timeout(self.timeout_secs)
347 } else if err.is_decode() {
348 Error::Decode(err.to_string())
349 } else {
350 Error::Network(err.to_string())
351 }
352 }
353
354 fn status_error(&self, raw: &RawResponse) -> Error {
355 let fallback = if raw.text.trim().is_empty() {
356 format!("HTTP {}", raw.status)
357 } else {
358 raw.text.trim().chars().take(500).collect()
359 };
360 let message = Error::message_from_body(&raw.json, &fallback);
361 match raw.status {
362 429 => Error::RateLimited {
363 retry_after: raw
364 .headers
365 .get("retry-after")
366 .and_then(|v| v.to_str().ok())
367 .and_then(|v| v.trim().parse::<u64>().ok()),
368 message,
369 },
370 401 if self.token.is_none() => Error::AuthRequired,
371 401 | 403 => Error::AuthFailed,
372 404 => Error::NotFound {
373 kind: "resource",
374 reference: message,
375 },
376 408 | 504 => Error::Timeout(self.timeout_secs),
377 status => Error::Api {
378 status,
379 message,
380 body: raw.json.clone(),
381 },
382 }
383 }
384}
385
386#[derive(Debug, Clone)]
389pub struct RawResponse {
390 pub status: u16,
391 pub headers: HeaderMap,
392 pub json: Option<Value>,
393 pub text: String,
394}
395
396impl RawResponse {
397 pub fn json_or_null(&self) -> Value {
398 self.json.clone().unwrap_or(Value::Null)
399 }
400
401 pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
402 let value = self
403 .json
404 .clone()
405 .ok_or_else(|| Error::Decode("expected a JSON response body".into()))?;
406 serde_json::from_value(value).map_err(|e| Error::Decode(e.to_string()))
407 }
408}
409
410pub struct GitFoxClientBuilder {
411 host: String,
412 token: Option<String>,
413 timeout_secs: u64,
414 retries: u32,
415 insecure: bool,
416}
417
418impl GitFoxClientBuilder {
419 pub fn token(mut self, token: Option<String>) -> Self {
420 self.token = token.filter(|t| !t.trim().is_empty());
421 self
422 }
423
424 pub fn timeout_secs(mut self, secs: u64) -> Self {
425 self.timeout_secs = secs;
426 self
427 }
428
429 pub fn retries(mut self, retries: u32) -> Self {
432 self.retries = retries;
433 self
434 }
435
436 pub fn insecure(mut self, insecure: bool) -> Self {
439 self.insecure = insecure;
440 self
441 }
442
443 pub fn build(self) -> Result<GitFoxClient> {
444 let base_url = normalize_host(&self.host)?;
445 let http = |redirect| {
446 reqwest::Client::builder()
447 .user_agent(USER_AGENT)
448 .timeout(Duration::from_secs(self.timeout_secs))
449 .danger_accept_invalid_certs(self.insecure)
450 .redirect(redirect)
451 .build()
452 .map_err(|e| Error::Builder(e.to_string()))
453 };
454 Ok(GitFoxClient {
455 http: http(Policy::default())?,
456 http_no_redirect: http(Policy::none())?,
457 base_url,
458 token: self.token,
459 timeout_secs: self.timeout_secs,
460 retries: self.retries,
461 })
462 }
463}
464
465pub fn normalize_host(host: &str) -> Result<Url> {
468 let host = host.trim();
469 if host.is_empty() {
470 return Err(Error::InvalidUrl("host is empty".into()));
471 }
472 let with_scheme = if host.contains("://") {
473 host.to_string()
474 } else {
475 format!("https://{host}")
476 };
477 let mut url =
478 Url::parse(&with_scheme).map_err(|e| Error::InvalidUrl(format!("{host}: {e}")))?;
479 if url.cannot_be_a_base() || url.host_str().is_none() {
480 return Err(Error::InvalidUrl(format!("{host}: missing host")));
481 }
482 if !url.path().ends_with('/') {
483 let path = format!("{}/", url.path());
484 url.set_path(&path);
485 }
486 Ok(url)
487}
488
489fn follows_redirects(method: &Method) -> bool {
498 matches!(*method, Method::GET | Method::HEAD)
499}
500
501fn redirect_error(method: &Method, raw: &RawResponse) -> Option<Error> {
507 if follows_redirects(method) || !(300..400).contains(&raw.status) {
508 return None;
509 }
510 let location = raw.headers.get(LOCATION)?.to_str().ok()?;
511 Some(Error::Api {
512 status: raw.status,
513 message: format!(
514 "the server redirected this {method} to {location}; a request that changes \
515 data does not follow redirects, so send it there instead"
516 ),
517 body: raw.json.clone(),
518 })
519}
520
521pub fn is_retryable_method(method: &Method) -> bool {
529 matches!(
530 *method,
531 Method::GET | Method::HEAD | Method::OPTIONS | Method::PUT | Method::DELETE
532 )
533}
534
535fn is_transient(error: &Error) -> bool {
541 match error {
542 Error::Network(_) | Error::Timeout(_) | Error::RateLimited { .. } => true,
543 Error::Api { status, .. } => matches!(status, 502..=504),
544 _ => false,
545 }
546}
547
548fn jitter(base: Duration) -> Duration {
551 let nanos = SystemTime::now()
552 .duration_since(UNIX_EPOCH)
553 .map(|d| d.subsec_nanos() as u64)
554 .unwrap_or(0);
555 Duration::from_millis((base.as_millis() as u64 / 2).saturating_mul(nanos % 1000) / 1000)
556}
557
558#[derive(Debug, Default, Clone)]
564pub struct Query(Vec<(String, String)>);
565
566impl Query {
567 pub fn new() -> Self {
568 Self::default()
569 }
570
571 pub fn push(&mut self, key: &str, value: impl ToString) -> &mut Self {
572 self.0.push((key.to_string(), value.to_string()));
573 self
574 }
575
576 pub fn push_opt<T: ToString>(&mut self, key: &str, value: Option<T>) -> &mut Self {
579 if let Some(value) = value {
580 self.push(key, value);
581 }
582 self
583 }
584
585 pub fn extend<T: ToString>(
586 &mut self,
587 key: &str,
588 values: impl IntoIterator<Item = T>,
589 ) -> &mut Self {
590 for value in values {
591 self.push(key, value);
592 }
593 self
594 }
595
596 pub fn is_empty(&self) -> bool {
597 self.0.is_empty()
598 }
599
600 pub fn encode(&self) -> String {
601 form_urlencoded::Serializer::new(String::new())
602 .extend_pairs(self.0.iter().map(|(k, v)| (k.as_str(), v.as_str())))
603 .finish()
604 }
605
606 pub fn apply(&self, path: &str) -> String {
608 if self.is_empty() {
609 return path.to_string();
610 }
611 format!("{path}?{}", self.encode())
612 }
613}
614
615#[cfg(test)]
616mod tests {
617 use super::*;
618
619 #[test]
620 fn adds_https_when_scheme_is_missing() {
621 assert_eq!(
622 normalize_host("git.example.com").unwrap().as_str(),
623 "https://git.example.com/"
624 );
625 }
626
627 #[test]
628 fn keeps_explicit_scheme_port_and_base_path() {
629 assert_eq!(
630 normalize_host("http://localhost:3000").unwrap().as_str(),
631 "http://localhost:3000/"
632 );
633 assert_eq!(
634 normalize_host("https://example.com/gitfox")
635 .unwrap()
636 .as_str(),
637 "https://example.com/gitfox/"
638 );
639 }
640
641 #[test]
642 fn rejects_unusable_hosts() {
643 for bad in ["", " ", "https://"] {
644 assert!(
645 normalize_host(bad).is_err(),
646 "expected `{bad}` to be rejected"
647 );
648 }
649 }
650
651 #[test]
652 fn resolves_paths_with_and_without_leading_slash() {
653 let c = GitFoxClient::builder("https://git.example.com")
654 .build()
655 .unwrap();
656 assert_eq!(
657 c.resolve("/api/v1/user").unwrap().as_str(),
658 "https://git.example.com/api/v1/user"
659 );
660 assert_eq!(
661 c.resolve("api/v1/user").unwrap().as_str(),
662 "https://git.example.com/api/v1/user"
663 );
664 }
665
666 #[test]
667 fn resolve_preserves_a_base_path() {
668 let c = GitFoxClient::builder("https://example.com/gitfox")
669 .build()
670 .unwrap();
671 assert_eq!(
672 c.resolve("/api/v1/user").unwrap().as_str(),
673 "https://example.com/gitfox/api/v1/user"
674 );
675 }
676
677 #[test]
678 fn resolve_preserves_a_percent_encoded_slash_in_a_repo_ref() {
679 let c = GitFoxClient::builder("https://git.example.com")
682 .build()
683 .unwrap();
684 let url = c.resolve("/api/v1/repos/ai%2Fbackend/pullreq").unwrap();
685 assert_eq!(
686 url.as_str(),
687 "https://git.example.com/api/v1/repos/ai%2Fbackend/pullreq"
688 );
689 }
690
691 #[test]
692 fn resolve_keeps_a_query_string_intact() {
693 let c = GitFoxClient::builder("https://git.example.com")
694 .build()
695 .unwrap();
696 let url = c
697 .resolve("/api/v1/repos/ai%2Fbackend/pullreq?state=open&limit=30")
698 .unwrap();
699 assert_eq!(url.query(), Some("state=open&limit=30"));
700 assert_eq!(url.path(), "/api/v1/repos/ai%2Fbackend/pullreq");
701 }
702
703 #[test]
704 fn query_encodes_pairs_and_skips_absent_values() {
705 let mut q = Query::new();
706 q.push("limit", 30)
707 .push_opt("author_id", Some(7))
708 .push_opt::<String>("query", None)
709 .extend("state", ["open", "merged"]);
710 assert_eq!(
711 q.apply("/x"),
712 "/x?limit=30&author_id=7&state=open&state=merged"
713 );
714 assert_eq!(Query::new().apply("/x"), "/x");
715 }
716
717 #[test]
718 fn query_escapes_values_that_would_break_the_url() {
719 let mut q = Query::new();
720 q.push("query", "fix: auth & tokens");
721 assert_eq!(q.encode(), "query=fix%3A+auth+%26+tokens");
722 }
723
724 #[test]
725 fn an_explicit_accept_header_replaces_the_default() {
726 let names = ["Accept", "accept", "ACCEPT"];
729 for name in names {
730 assert!(
731 [(name.to_string(), "text/plain".to_string())]
732 .iter()
733 .any(|(n, _)| n.eq_ignore_ascii_case("accept")),
734 "`{name}` should be recognised as Accept"
735 );
736 }
737 assert!(
738 ![("X-Trace".to_string(), "1".to_string())]
739 .iter()
740 .any(|(n, _)| n.eq_ignore_ascii_case("accept"))
741 );
742 }
743
744 #[test]
745 fn debug_never_reveals_the_token() {
746 let c = GitFoxClient::builder("git.example.com")
747 .token(Some("super-secret-token".into()))
748 .build()
749 .unwrap();
750 let rendered = format!("{c:?}");
751 assert!(!rendered.contains("super-secret-token"), "{rendered}");
752 assert!(rendered.contains("***"), "{rendered}");
753 }
754
755 #[test]
756 fn blank_tokens_are_treated_as_absent() {
757 let c = GitFoxClient::builder("git.example.com")
758 .token(Some(" ".into()))
759 .build()
760 .unwrap();
761 assert!(!c.has_token());
762 }
763}