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