@sigit / si Mirror · read-only
Fork 0

Mirror of github.com/getsigit/si.

Mirrored from https://github.com/getsigit/si.git

Synced Nov 24, 09:30 UTC

1 //! The HTTP transport every endpoint module is built on.
2
3 use {
4 crate::{
5 environment::{normalize_host, Environment},
6 error::{ApiError, ErrorResponse, Result},
7 CLIENT_HEADER,
8 },
9 reqwest::{Method, RequestBuilder, StatusCode},
10 serde::{de::DeserializeOwned, Serialize},
11 tracing::debug,
12 };
13
14 const USER_AGENT: &str = concat!("si/", env!("CARGO_PKG_VERSION"));
15
16 /// A configured client for one sigit.si environment.
17 ///
18 /// Cheap to clone (the inner `reqwest::Client` is an `Arc` over a shared
19 /// connection pool), so pass it around by value.
20 #[derive(Debug, Clone)]
21 pub struct Client {
22 http: reqwest::Client,
23 environment: Environment,
24 api_url: String,
25 base_url: String,
26 client_name: Option<String>,
27 token: Option<String>,
28 }
29
30 /// Builds a [`Client`]. Get one from [`Client::builder`].
31 #[derive(Debug)]
32 pub struct ClientBuilder {
33 environment: Environment,
34 http: Option<reqwest::Client>,
35 user_agent: Option<String>,
36 base_url: Option<String>,
37 client_name: Option<String>,
38 token: Option<String>,
39 }
40
41 impl ClientBuilder {
42 /// Use this `reqwest::Client` (and so its connection pool, TLS backend and
43 /// user agent) instead of building one. Required for HTTPS when the crate
44 /// is compiled without a TLS feature.
45 pub fn http_client(mut self, http: reqwest::Client) -> Self {
46 self.http = Some(http);
47 self
48 }
49
50 /// The `User-Agent` of the client the crate builds. Ignored when
51 /// [`ClientBuilder::http_client`] is set.
52 pub fn user_agent(mut self, user_agent: &str) -> Self {
53 self.user_agent = Some(user_agent.to_string());
54 self
55 }
56
57 /// An explicit origin such as `https://sigit.si` or `localhost:4000`. A
58 /// missing scheme takes the environment's default and a trailing slash is
59 /// dropped. It takes the place of the environment's defaults, so
60 /// `SIGIT_HOST` has no effect.
61 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
62 self.base_url = Some(base_url.into());
63 self
64 }
65
66 /// Name this client in the [`CLIENT_HEADER`] header on every request.
67 pub fn client_name(mut self, name: &str) -> Self {
68 self.client_name = Some(name.to_string());
69 self
70 }
71
72 /// The bearer token sent on every request.
73 pub fn token(mut self, token: impl Into<String>) -> Self {
74 self.token = Some(token.into());
75 self
76 }
77
78 pub fn build(self) -> Result<Client> {
79 let environment = self.environment;
80 let base_url = match self.base_url {
81 Some(url) => normalize_host(url.trim(), environment.default_scheme()),
82 None => environment.base_url(),
83 };
84
85 let http = match self.http {
86 Some(http) => http,
87 None => reqwest::Client::builder()
88 .user_agent(self.user_agent.as_deref().unwrap_or(USER_AGENT))
89 .build()
90 .map_err(|source| ApiError::Transport {
91 host: base_url.clone(),
92 source,
93 })?,
94 };
95
96 Ok(Client {
97 http,
98 environment,
99 api_url: format!("{base_url}/api/v1"),
100 base_url,
101 client_name: self.client_name,
102 token: self.token,
103 })
104 }
105 }
106
107 impl Client {
108 /// An unauthenticated client. Every endpoint on this API needs a token, so
109 /// this is mostly a starting point for [`Client::with_token`].
110 ///
111 /// Shorthand for `Client::builder(environment).build()`.
112 pub fn new(environment: Environment) -> Result<Self> {
113 Self::builder(environment).build()
114 }
115
116 /// Start configuring a client: base URL, user agent, client name, or your
117 /// own `reqwest::Client`.
118 pub fn builder(environment: Environment) -> ClientBuilder {
119 ClientBuilder {
120 environment,
121 http: None,
122 user_agent: None,
123 base_url: None,
124 client_name: None,
125 token: None,
126 }
127 }
128
129 /// Attach the bearer token sent on every subsequent request.
130 pub fn with_token(mut self, token: impl Into<String>) -> Self {
131 self.token = Some(token.into());
132 self
133 }
134
135 pub fn environment(&self) -> Environment {
136 self.environment
137 }
138
139 /// The web origin — the base for browser and `.git` clone URLs.
140 pub fn base_url(&self) -> &str {
141 &self.base_url
142 }
143
144 pub fn api_url(&self) -> &str {
145 &self.api_url
146 }
147
148 pub fn token(&self) -> Option<&str> {
149 self.token.as_deref()
150 }
151
152 // ── Verb helpers ────────────────────────────────────────────────────────
153
154 pub async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
155 self.send(self.request(Method::GET, path)).await
156 }
157
158 pub async fn post<T: DeserializeOwned>(&self, path: &str, body: &impl Serialize) -> Result<T> {
159 self.send(self.request(Method::POST, path).json(body)).await
160 }
161
162 pub async fn patch<T: DeserializeOwned>(&self, path: &str, body: &impl Serialize) -> Result<T> {
163 self.send(self.request(Method::PATCH, path).json(body))
164 .await
165 }
166
167 /// For endpoints that answer `204 No Content` (sign-out, deletes).
168 pub async fn delete(&self, path: &str) -> Result<()> {
169 self.send_empty(self.request(Method::DELETE, path)).await
170 }
171
172 /// Escape hatch for `si api` — an arbitrary method and path against the API
173 /// root, returning the raw JSON body.
174 pub async fn raw(
175 &self,
176 method: Method,
177 path: &str,
178 body: Option<serde_json::Value>,
179 ) -> Result<serde_json::Value> {
180 let mut builder = self.request(method, path);
181 if let Some(body) = body {
182 builder = builder.json(&body);
183 }
184
185 let response = self.execute(builder).await?;
186 let status = response.status();
187 let text = response.text().await.unwrap_or_default();
188
189 // A raw call reports the body as-is, whether or not the status is 2xx —
190 // seeing the server's actual error JSON is the point of the command.
191 // Only auth failures are translated, so the caller can clear the token.
192 if status == StatusCode::UNAUTHORIZED {
193 return Err(ApiError::Unauthorized);
194 }
195 if text.trim().is_empty() {
196 return Ok(serde_json::Value::Null);
197 }
198 serde_json::from_str(&text).map_err(|e| ApiError::Parse(format!("{e}: {text}")))
199 }
200
201 // ── Plumbing ────────────────────────────────────────────────────────────
202
203 /// Build a request against `<api_url>/<path>`, carrying the bearer token.
204 pub fn request(&self, method: Method, path: &str) -> RequestBuilder {
205 let url = format!("{}/{}", self.api_url, path.trim_start_matches('/'));
206 let mut builder = self.http.request(method, url);
207 if let Some(name) = &self.client_name {
208 builder = builder.header(CLIENT_HEADER, name);
209 }
210 match &self.token {
211 Some(token) => builder.bearer_auth(token),
212 None => builder,
213 }
214 }
215
216 /// Send a request and deserialize a JSON body.
217 pub async fn send<T: DeserializeOwned>(&self, builder: RequestBuilder) -> Result<T> {
218 let response = self.execute(builder).await?;
219 let status = response.status();
220 let text = response.text().await.unwrap_or_default();
221
222 if !status.is_success() {
223 return Err(Self::error_from(status, &text));
224 }
225
226 serde_json::from_str(&text).map_err(|e| ApiError::Parse(format!("{e}: {text}")))
227 }
228
229 /// Send a request that returns no useful body (`204`, or a `200` we ignore).
230 pub async fn send_empty(&self, builder: RequestBuilder) -> Result<()> {
231 let response = self.execute(builder).await?;
232 let status = response.status();
233
234 if status.is_success() {
235 return Ok(());
236 }
237
238 let text = response.text().await.unwrap_or_default();
239 Err(Self::error_from(status, &text))
240 }
241
242 async fn execute(&self, builder: RequestBuilder) -> Result<reqwest::Response> {
243 if self.token.is_none() {
244 debug!("sending an unauthenticated request to {}", self.api_url);
245 }
246
247 builder.send().await.map_err(|source| ApiError::Transport {
248 host: self.base_url.clone(),
249 source,
250 })
251 }
252
253 /// Turn a non-2xx response into the most specific error we can. The body is
254 /// usually an `ErrorResponse`; when it isn't (a proxy's HTML 502, say), fall
255 /// back to the status line so the message is still actionable.
256 fn error_from(status: StatusCode, body: &str) -> ApiError {
257 if status == StatusCode::UNAUTHORIZED {
258 return ApiError::Unauthorized;
259 }
260
261 match serde_json::from_str::<ErrorResponse>(body) {
262 Ok(error) => ApiError::Status {
263 status: status.as_u16(),
264 error_code: error.error_code,
265 message: error.message,
266 },
267 Err(_) => ApiError::Status {
268 status: status.as_u16(),
269 error_code: crate::error::codes::UNKNOWN,
270 message: format!(
271 "The server returned {}{}",
272 status,
273 truncate_for_message(body)
274 ),
275 },
276 }
277 }
278 }
279
280 /// Append a short excerpt of an unparseable body, so an HTML error page shows
281 /// something useful without dumping a full page into the terminal.
282 fn truncate_for_message(body: &str) -> String {
283 let body = body.trim();
284 if body.is_empty() {
285 return String::new();
286 }
287
288 const MAX: usize = 200;
289 let excerpt: String = body.chars().take(MAX).collect();
290 if body.chars().count() > MAX {
291 format!(": {excerpt}…")
292 } else {
293 format!(": {excerpt}")
294 }
295 }
296
297 #[cfg(test)]
298 mod tests {
299 use super::*;
300
301 #[test]
302 fn an_explicit_base_url_replaces_the_environment_default() {
303 let client = Client::builder(Environment::Production)
304 .base_url("127.0.0.1:3000/")
305 .build()
306 .unwrap();
307
308 assert_eq!(client.base_url(), "https://127.0.0.1:3000");
309 assert_eq!(client.api_url(), "https://127.0.0.1:3000/api/v1");
310 }
311
312 #[test]
313 fn a_bare_base_url_takes_the_environment_scheme() {
314 let client = Client::builder(Environment::Dev)
315 .base_url("127.0.0.1:3000")
316 .build()
317 .unwrap();
318 assert_eq!(client.api_url(), "http://127.0.0.1:3000/api/v1");
319 }
320
321 #[test]
322 fn requests_carry_the_client_name_and_token() {
323 let client = Client::builder(Environment::Production)
324 .base_url("https://sigit.si")
325 .client_name("example.app")
326 .token("tok")
327 .build()
328 .unwrap();
329 let request = client.request(Method::DELETE, "/me").build().unwrap();
330 assert_eq!(request.url().as_str(), "https://sigit.si/api/v1/me");
331 assert_eq!(request.method(), Method::DELETE);
332 assert_eq!(request.headers()[CLIENT_HEADER], "example.app");
333 assert_eq!(request.headers()["authorization"], "Bearer tok");
334 }
335
336 #[test]
337 fn requests_omit_the_client_header_by_default() {
338 let client = Client::new(Environment::Production).unwrap();
339 let request = client.request(Method::GET, "user").build().unwrap();
340 assert!(request.headers().get(CLIENT_HEADER).is_none());
341 }
342
343 #[test]
344 fn unauthorized_maps_to_the_dedicated_variant() {
345 let error = Client::error_from(StatusCode::UNAUTHORIZED, r#"{"error_code":100,"m":"x"}"#);
346 assert!(matches!(error, ApiError::Unauthorized));
347 }
348
349 #[test]
350 fn error_bodies_keep_the_servers_message_and_code() {
351 let body = r#"{"error_code":101,"message":"Repository not found."}"#;
352 match Client::error_from(StatusCode::NOT_FOUND, body) {
353 ApiError::Status {
354 status,
355 error_code,
356 message,
357 } => {
358 assert_eq!(status, 404);
359 assert_eq!(error_code, 101);
360 assert_eq!(message, "Repository not found.");
361 }
362 other => panic!("expected a Status error, got {other:?}"),
363 }
364 }
365
366 #[test]
367 fn non_json_bodies_fall_back_to_the_status_line() {
368 match Client::error_from(StatusCode::BAD_GATEWAY, "<html>nginx</html>") {
369 ApiError::Status { message, .. } => {
370 assert!(message.contains("502"), "{message}");
371 assert!(message.contains("nginx"), "{message}");
372 }
373 other => panic!("expected a Status error, got {other:?}"),
374 }
375 }
376
377 #[test]
378 fn long_html_bodies_are_truncated() {
379 let body = "x".repeat(1000);
380 let message = truncate_for_message(&body);
381 assert!(message.ends_with('…'));
382 assert!(message.chars().count() < 250);
383 }
384 }