wavekat_platform_client/
client.rs1use futures_util::StreamExt;
16use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
17use serde::de::DeserializeOwned;
18use serde::Serialize;
19use tokio::io::AsyncWriteExt;
20
21use crate::error::{Error, Result};
22use crate::token::Token;
23
24#[derive(Clone)]
29pub struct Client {
30 inner: reqwest::Client,
31 base_url: String,
32}
33
34impl Client {
35 pub fn new(base_url: impl Into<String>, token: Token) -> Result<Self> {
38 let mut headers = HeaderMap::new();
39 let value = format!("Bearer {}", token.as_str());
40 let header = HeaderValue::from_str(&value)
41 .map_err(|_| Error::BadRequest("token contained invalid bytes".into()))?;
42 headers.insert(AUTHORIZATION, header);
43
44 let inner = reqwest::Client::builder()
45 .default_headers(headers)
46 .user_agent(concat!(
47 "wavekat-platform-client/",
48 env!("CARGO_PKG_VERSION")
49 ))
50 .build()?;
51 Ok(Self {
52 inner,
53 base_url: base_url.into().trim_end_matches('/').to_string(),
54 })
55 }
56
57 pub fn base_url(&self) -> &str {
61 &self.base_url
62 }
63
64 fn url(&self, path: &str) -> String {
65 format!("{}{}", self.base_url, path)
66 }
67
68 pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
70 let url = self.url(path);
71 let resp = self.inner.get(&url).send().await?;
72 decode(url, resp).await
73 }
74
75 pub async fn get_json_query<T: DeserializeOwned, Q: Serialize + ?Sized>(
78 &self,
79 path: &str,
80 query: &Q,
81 ) -> Result<T> {
82 let url = self.url(path);
83 let resp = self.inner.get(&url).query(query).send().await?;
84 decode(url, resp).await
85 }
86
87 pub async fn post_json<T: DeserializeOwned, B: Serialize + ?Sized>(
90 &self,
91 path: &str,
92 body: &B,
93 ) -> Result<T> {
94 let url = self.url(path);
95 let resp = self.inner.post(&url).json(body).send().await?;
96 decode(url, resp).await
97 }
98
99 pub async fn post_empty(&self, path: &str) -> Result<()> {
101 let url = self.url(path);
102 let resp = self.inner.post(&url).send().await?;
103 ensure_success(url, resp).await
104 }
105
106 pub async fn post_empty_returning_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
110 let url = self.url(path);
111 let resp = self.inner.post(&url).send().await?;
112 decode(url, resp).await
113 }
114
115 pub async fn delete(&self, path: &str) -> Result<()> {
117 let url = self.url(path);
118 let resp = self.inner.delete(&url).send().await?;
119 ensure_success(url, resp).await
120 }
121
122 pub async fn put_proxy_bytes(&self, path: &str, body: Vec<u8>) -> Result<()> {
126 let url = self.url(path);
127 let resp = self
128 .inner
129 .put(&url)
130 .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
131 .body(body)
132 .send()
133 .await?;
134 ensure_success(url, resp).await
135 }
136
137 pub async fn put_presigned_bytes(presigned_url: &str, body: Vec<u8>) -> Result<()> {
142 let resp = reqwest::Client::new()
143 .put(presigned_url)
144 .body(body)
145 .send()
146 .await?;
147 ensure_success(presigned_url.to_string(), resp).await
148 }
149
150 pub async fn get_stream_to<W: AsyncWriteExt + Unpin>(
154 &self,
155 path: &str,
156 sink: &mut W,
157 ) -> Result<u64> {
158 let url = self.url(path);
159 let resp = self.inner.get(&url).send().await?;
160 let status = resp.status();
161 if !status.is_success() {
162 let body = resp.text().await.unwrap_or_default();
163 return Err(Error::Http {
164 status: status.as_u16(),
165 url,
166 body: truncate(&body, 500).to_string(),
167 });
168 }
169 let mut stream = resp.bytes_stream();
170 let mut written: u64 = 0;
171 while let Some(chunk) = stream.next().await {
172 let bytes = chunk?;
173 sink.write_all(&bytes).await?;
174 written += bytes.len() as u64;
175 }
176 sink.flush().await?;
177 Ok(written)
178 }
179}
180
181async fn decode<T: DeserializeOwned>(url: String, resp: reqwest::Response) -> Result<T> {
182 let status = resp.status();
183 let text = resp.text().await?;
184 if !status.is_success() {
185 return Err(Error::Http {
186 status: status.as_u16(),
187 url,
188 body: truncate(&text, 500).to_string(),
189 });
190 }
191 serde_json::from_str(&text).map_err(|source| Error::Decode { url, source })
192}
193
194async fn ensure_success(url: String, resp: reqwest::Response) -> Result<()> {
195 let status = resp.status();
196 if status.is_success() {
197 return Ok(());
198 }
199 let body = resp.text().await.unwrap_or_default();
200 Err(Error::Http {
201 status: status.as_u16(),
202 url,
203 body: truncate(&body, 500).to_string(),
204 })
205}
206
207fn truncate(s: &str, n: usize) -> &str {
208 if s.len() > n {
209 let mut end = n;
214 while end > 0 && !s.is_char_boundary(end) {
215 end -= 1;
216 }
217 &s[..end]
218 } else {
219 s
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 #[test]
228 fn http_error_format_matches_cli_shape() {
229 let e = Error::Http {
234 status: 401,
235 url: "https://platform.wavekat.com/api/me".into(),
236 body: "unauthorized".into(),
237 };
238 let s = e.to_string();
239 assert!(s.contains("401"), "{s}");
240 assert!(s.contains("https://platform.wavekat.com/api/me"), "{s}");
241 assert!(s.contains("unauthorized"), "{s}");
242 }
243
244 #[test]
245 fn truncate_respects_char_boundaries() {
246 let s = "a".repeat(498) + "é"; let t = truncate(&s, 499);
249 assert!(s.starts_with(t));
250 }
251}