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 self.put_raw_bytes(path, "application/octet-stream", body)
127 .await
128 }
129
130 pub async fn put_raw_bytes(&self, path: &str, content_type: &str, body: Vec<u8>) -> Result<()> {
135 let url = self.url(path);
136 let resp = self
137 .inner
138 .put(&url)
139 .header(reqwest::header::CONTENT_TYPE, content_type)
140 .body(body)
141 .send()
142 .await?;
143 ensure_success(url, resp).await
144 }
145
146 pub async fn put_presigned_bytes(presigned_url: &str, body: Vec<u8>) -> Result<()> {
151 let resp = reqwest::Client::new()
152 .put(presigned_url)
153 .body(body)
154 .send()
155 .await?;
156 ensure_success(presigned_url.to_string(), resp).await
157 }
158
159 pub async fn get_stream_to<W: AsyncWriteExt + Unpin>(
163 &self,
164 path: &str,
165 sink: &mut W,
166 ) -> Result<u64> {
167 let url = self.url(path);
168 let resp = self.inner.get(&url).send().await?;
169 let status = resp.status();
170 if !status.is_success() {
171 let body = resp.text().await.unwrap_or_default();
172 return Err(http_error(status.as_u16(), url, body));
173 }
174 let mut stream = resp.bytes_stream();
175 let mut written: u64 = 0;
176 while let Some(chunk) = stream.next().await {
177 let bytes = chunk?;
178 sink.write_all(&bytes).await?;
179 written += bytes.len() as u64;
180 }
181 sink.flush().await?;
182 Ok(written)
183 }
184}
185
186async fn decode<T: DeserializeOwned>(url: String, resp: reqwest::Response) -> Result<T> {
187 let status = resp.status();
188 let text = resp.text().await?;
189 if !status.is_success() {
190 return Err(http_error(status.as_u16(), url, text));
191 }
192 serde_json::from_str(&text).map_err(|source| Error::Decode { url, source })
193}
194
195async fn ensure_success(url: String, resp: reqwest::Response) -> Result<()> {
196 let status = resp.status();
197 if status.is_success() {
198 return Ok(());
199 }
200 let body = resp.text().await.unwrap_or_default();
201 Err(http_error(status.as_u16(), url, body))
202}
203
204fn http_error(status: u16, url: String, body: String) -> Error {
209 let body = truncate(&body, 500).to_string();
210 if status == 401 {
211 Error::Unauthorized { url, body }
212 } else {
213 Error::Http { status, url, body }
214 }
215}
216
217fn truncate(s: &str, n: usize) -> &str {
218 if s.len() > n {
219 let mut end = n;
224 while end > 0 && !s.is_char_boundary(end) {
225 end -= 1;
226 }
227 &s[..end]
228 } else {
229 s
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn http_error_format_matches_cli_shape() {
239 let e = Error::Http {
244 status: 500,
245 url: "https://platform.wavekat.com/api/me".into(),
246 body: "boom".into(),
247 };
248 let s = e.to_string();
249 assert!(s.contains("500"), "{s}");
250 assert!(s.contains("https://platform.wavekat.com/api/me"), "{s}");
251 assert!(s.contains("boom"), "{s}");
252 }
253
254 #[test]
255 fn http_error_splits_401_into_unauthorized() {
256 let e = http_error(
259 401,
260 "https://platform.wavekat.com/api/me".into(),
261 "{\"error\":\"unauthenticated\"}".into(),
262 );
263 assert!(
264 matches!(e, Error::Unauthorized { .. }),
265 "expected Unauthorized, got {e:?}"
266 );
267 let s = e.to_string();
269 assert!(s.contains("401"), "{s}");
270 assert!(s.contains("https://platform.wavekat.com/api/me"), "{s}");
271 }
272
273 #[test]
274 fn http_error_keeps_non_401_in_http_variant() {
275 let e = http_error(
276 500,
277 "https://platform.wavekat.com/api/me".into(),
278 "boom".into(),
279 );
280 assert!(
281 matches!(e, Error::Http { status: 500, .. }),
282 "expected Http {{ status: 500 }}, got {e:?}"
283 );
284 }
285
286 #[test]
287 fn truncate_respects_char_boundaries() {
288 let s = "a".repeat(498) + "é"; let t = truncate(&s, 499);
291 assert!(s.starts_with(t));
292 }
293}