1use crate::error::CliError;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::sync::Arc;
4use tokio::time::{sleep, Duration};
5
6pub struct ClickUpClient {
7 http: reqwest::Client,
8 base_url: String,
9 token: String,
10 rate_limit_remaining: Arc<AtomicU64>,
11 rate_limit_reset: Arc<AtomicU64>,
12}
13
14impl ClickUpClient {
15 pub fn new(token: &str, timeout_secs: u64) -> Result<Self, CliError> {
16 let http = reqwest::Client::builder()
17 .timeout(std::time::Duration::from_secs(timeout_secs))
18 .build()
19 .map_err(|e| CliError::ClientError {
20 message: format!("Failed to create HTTP client: {}", e),
21 status: 0,
22 })?;
23 let base_url = std::env::var("CLICKUP_API_URL")
24 .unwrap_or_else(|_| "https://api.clickup.com/api".to_string());
25 Ok(Self {
26 http,
27 base_url,
28 token: token.to_string(),
29 rate_limit_remaining: Arc::new(AtomicU64::new(100)),
30 rate_limit_reset: Arc::new(AtomicU64::new(0)),
31 })
32 }
33
34 fn update_rate_limits(&self, headers: &reqwest::header::HeaderMap) {
35 if let Some(remaining) = headers.get("X-RateLimit-Remaining") {
36 if let Ok(val) = remaining.to_str().unwrap_or("0").parse::<u64>() {
37 self.rate_limit_remaining.store(val, Ordering::Relaxed);
38 }
39 }
40 if let Some(reset) = headers.get("X-RateLimit-Reset") {
41 if let Ok(val) = reset.to_str().unwrap_or("0").parse::<u64>() {
42 self.rate_limit_reset.store(val, Ordering::Relaxed);
43 }
44 }
45 }
46
47 async fn parse_success_response(
48 resp: reqwest::Response,
49 status: u16,
50 ) -> Result<serde_json::Value, CliError> {
51 if status == 204 {
52 return Ok(serde_json::json!({}));
53 }
54
55 let body_text = resp.text().await.map_err(|e| CliError::ClientError {
56 message: format!("Failed to read response body: {}", e),
57 status,
58 })?;
59
60 if body_text.trim().is_empty() {
61 return Ok(serde_json::json!({}));
62 }
63
64 serde_json::from_str(&body_text).map_err(|e| CliError::ClientError {
65 message: format!("Failed to parse response: {}", e),
66 status,
67 })
68 }
69
70 async fn request(
71 &self,
72 method: reqwest::Method,
73 path: &str,
74 body: Option<&serde_json::Value>,
75 ) -> Result<serde_json::Value, CliError> {
76 let url = format!("{}{}", self.base_url, path);
77 let max_retries = 3;
78
79 for attempt in 0..=max_retries {
80 let mut req = self
81 .http
82 .request(method.clone(), &url)
83 .header("Authorization", &self.token)
84 .header("Content-Type", "application/json");
85
86 if let Some(b) = body {
87 req = req.json(b);
88 }
89
90 let resp = req.send().await.map_err(|e| CliError::ClientError {
91 message: format!("Request failed: {}", e),
92 status: 0,
93 })?;
94
95 let status = resp.status().as_u16();
96 self.update_rate_limits(resp.headers());
97
98 if (200..300).contains(&status) {
99 return Self::parse_success_response(resp, status).await;
100 }
101
102 if status == 429 && attempt == 0 {
104 let reset = self.rate_limit_reset.load(Ordering::Relaxed);
105 let now = std::time::SystemTime::now()
106 .duration_since(std::time::UNIX_EPOCH)
107 .unwrap()
108 .as_secs();
109 let wait = if reset > now { reset - now } else { 1 };
110 eprintln!("Rate limited. Waiting {} seconds...", wait);
111 sleep(Duration::from_secs(wait)).await;
112 continue;
113 }
114
115 if (500..=599).contains(&status) && attempt < max_retries {
117 let wait = 1u64 << attempt; eprintln!("Server error ({}). Retrying in {}s...", status, wait);
119 sleep(Duration::from_secs(wait)).await;
120 continue;
121 }
122
123 let body_text = resp.text().await.unwrap_or_default();
125 let message = serde_json::from_str::<serde_json::Value>(&body_text)
126 .ok()
127 .and_then(|v| v.get("err").and_then(|e| e.as_str()).map(String::from))
128 .unwrap_or_else(|| format!("HTTP {}", status));
129
130 return match status {
131 401 => Err(CliError::AuthError { message }),
132 403 => Err(CliError::Forbidden { message }),
133 404 => Err(CliError::NotFound {
134 message,
135 resource_id: String::new(),
136 }),
137 429 => Err(CliError::RateLimited {
138 message,
139 retry_after: None,
140 }),
141 500..=599 => Err(CliError::ServerError { message }),
142 _ => Err(CliError::ClientError { message, status }),
143 };
144 }
145
146 Err(CliError::ServerError {
147 message: "Max retries exceeded".into(),
148 })
149 }
150
151 pub async fn get(&self, path: &str) -> Result<serde_json::Value, CliError> {
152 self.request(reqwest::Method::GET, path, None).await
153 }
154
155 pub async fn post(
156 &self,
157 path: &str,
158 body: &serde_json::Value,
159 ) -> Result<serde_json::Value, CliError> {
160 self.request(reqwest::Method::POST, path, Some(body)).await
161 }
162
163 pub async fn put(
164 &self,
165 path: &str,
166 body: &serde_json::Value,
167 ) -> Result<serde_json::Value, CliError> {
168 self.request(reqwest::Method::PUT, path, Some(body)).await
169 }
170
171 pub async fn delete(&self, path: &str) -> Result<serde_json::Value, CliError> {
172 self.request(reqwest::Method::DELETE, path, None).await
173 }
174
175 pub async fn patch(
176 &self,
177 path: &str,
178 body: &serde_json::Value,
179 ) -> Result<serde_json::Value, CliError> {
180 self.request(reqwest::Method::PATCH, path, Some(body)).await
181 }
182
183 pub async fn delete_with_body(
184 &self,
185 path: &str,
186 body: &serde_json::Value,
187 ) -> Result<serde_json::Value, CliError> {
188 self.request(reqwest::Method::DELETE, path, Some(body))
189 .await
190 }
191
192 pub async fn upload_file(
193 &self,
194 path: &str,
195 file_path: &std::path::Path,
196 ) -> Result<serde_json::Value, CliError> {
197 let url = format!("{}{}", self.base_url, path);
198 let file_name = file_path
199 .file_name()
200 .and_then(|n| n.to_str())
201 .unwrap_or("file")
202 .to_string();
203 let file_bytes = tokio::fs::read(file_path)
204 .await
205 .map_err(CliError::IoError)?;
206 let part = reqwest::multipart::Part::bytes(file_bytes).file_name(file_name);
207 let form = reqwest::multipart::Form::new().part("attachment", part);
208
209 let resp = self
210 .http
211 .post(&url)
212 .header("Authorization", &self.token)
213 .multipart(form)
214 .send()
215 .await
216 .map_err(|e| CliError::ClientError {
217 message: format!("Upload failed: {}", e),
218 status: 0,
219 })?;
220
221 let status = resp.status().as_u16();
222 self.update_rate_limits(resp.headers());
223
224 if (200..300).contains(&status) {
225 return Self::parse_success_response(resp, status).await;
226 }
227
228 let body_text = resp.text().await.unwrap_or_default();
229 let message = serde_json::from_str::<serde_json::Value>(&body_text)
230 .ok()
231 .and_then(|v| v.get("err").and_then(|e| e.as_str()).map(String::from))
232 .unwrap_or_else(|| format!("HTTP {}", status));
233
234 Err(match status {
235 401 => CliError::AuthError { message },
236 404 => CliError::NotFound {
237 message,
238 resource_id: String::new(),
239 },
240 429 => CliError::RateLimited {
241 message,
242 retry_after: None,
243 },
244 500..=599 => CliError::ServerError { message },
245 _ => CliError::ClientError { message, status },
246 })
247 }
248
249 pub fn with_base_url(mut self, base_url: &str) -> Self {
251 self.base_url = base_url.to_string();
252 self
253 }
254}