1use std::sync::Arc;
2
3use anyhow::{Result, anyhow};
4pub use cloud_api_types::*;
5use futures::AsyncReadExt as _;
6use http_client::{AsyncBody, HttpClientWithUrl, Method, Request};
7use parking_lot::RwLock;
8
9struct Credentials {
10 user_id: u32,
11 access_token: String,
12}
13
14pub struct CloudApiClient {
15 credentials: RwLock<Option<Credentials>>,
16 http_client: Arc<HttpClientWithUrl>,
17}
18
19impl CloudApiClient {
20 pub fn new(http_client: Arc<HttpClientWithUrl>) -> Self {
21 Self {
22 credentials: RwLock::new(None),
23 http_client,
24 }
25 }
26
27 pub fn has_credentials(&self) -> bool {
28 self.credentials.read().is_some()
29 }
30
31 pub fn set_credentials(&self, user_id: u32, access_token: String) {
32 *self.credentials.write() = Some(Credentials {
33 user_id,
34 access_token,
35 });
36 }
37
38 fn authorization_header(&self) -> Result<String> {
39 let guard = self.credentials.read();
40 let credentials = guard
41 .as_ref()
42 .ok_or_else(|| anyhow!("No credentials provided"))?;
43
44 Ok(format!(
45 "{} {}",
46 credentials.user_id, credentials.access_token
47 ))
48 }
49
50 pub async fn get_authenticated_user(&self) -> Result<GetAuthenticatedUserResponse> {
51 let request = Request::builder()
52 .method(Method::GET)
53 .uri(
54 self.http_client
55 .build_zed_cloud_url("/client/users/me", &[])?
56 .as_ref(),
57 )
58 .header("Content-Type", "application/json")
59 .header("Authorization", self.authorization_header()?)
60 .body(AsyncBody::default())?;
61
62 let mut response = self.http_client.send(request).await?;
63
64 if !response.status().is_success() {
65 let mut body = String::new();
66 response.body_mut().read_to_string(&mut body).await?;
67
68 anyhow::bail!(
69 "Failed to get authenticated user.\nStatus: {:?}\nBody: {body}",
70 response.status()
71 )
72 }
73
74 let mut body = String::new();
75 response.body_mut().read_to_string(&mut body).await?;
76
77 Ok(serde_json::from_str(&body)?)
78 }
79}