Skip to main content

clickupc_core/client/
mod.rs

1//! HTTP plumbing: auth header, retry on 429, error-body parsing. Resource
2//! methods live in sibling modules as `impl ClickUpClient` blocks.
3
4mod comment;
5mod doc;
6mod field;
7mod hierarchy;
8mod relation;
9mod task;
10mod time;
11
12pub use comment::COMMENT_PAGE_SIZE;
13pub use doc::DocParent;
14pub use field::{convert_field_value, relation_value, FieldValue};
15pub use relation::Dependency;
16pub use task::{CreateTask, MoveTask, UpdateTask, MAX_PAGES, PAGE_SIZE};
17pub use time::{NewTimeEntry, TimeQuery};
18
19use std::sync::Arc;
20
21use reqwest::{
22    header::{HeaderMap, HeaderValue, AUTHORIZATION},
23    Method, RequestBuilder, StatusCode,
24};
25use serde::de::DeserializeOwned;
26use serde_json::Value;
27
28use crate::{
29    config::ClickUpConfig,
30    error::{redact, ClickUpError, Result},
31    rate_limit::{retry_delay, RateLimiter},
32};
33
34/// Retries after the first 429 before giving up with `RateLimit`.
35pub const MAX_RETRIES: usize = 3;
36
37/// Query builder that keeps insertion order and supports repeated `key[]=`.
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Query(Vec<(String, String)>);
40
41impl Query {
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    pub fn push(mut self, key: &str, value: impl ToString) -> Self {
47        self.0.push((key.to_string(), value.to_string()));
48        self
49    }
50
51    pub fn push_opt(self, key: &str, value: Option<impl ToString>) -> Self {
52        match value {
53            Some(v) => self.push(key, v),
54            None => self,
55        }
56    }
57
58    pub fn push_if(self, key: &str, cond: bool) -> Self {
59        if cond {
60            self.push(key, "true")
61        } else {
62            self
63        }
64    }
65
66    /// `key` should include the `[]` suffix, e.g. `statuses[]`.
67    pub fn push_all<I, T>(mut self, key: &str, values: I) -> Self
68    where
69        I: IntoIterator<Item = T>,
70        T: ToString,
71    {
72        for v in values {
73            self.0.push((key.to_string(), v.to_string()));
74        }
75        self
76    }
77
78    pub fn extend(mut self, other: Query) -> Self {
79        self.0.extend(other.0);
80        self
81    }
82
83    pub fn pairs(&self) -> &[(String, String)] {
84        &self.0
85    }
86
87    pub fn get(&self, key: &str) -> Option<&str> {
88        self.0
89            .iter()
90            .find(|(k, _)| k == key)
91            .map(|(_, v)| v.as_str())
92    }
93}
94
95#[derive(Debug, Clone)]
96pub(crate) enum Body {
97    Json(Value),
98    File {
99        field: &'static str,
100        name: String,
101        bytes: Vec<u8>,
102        mime: String,
103    },
104}
105
106#[derive(Clone)]
107pub struct ClickUpClient {
108    http: reqwest::Client,
109    base: String,
110    workspace_id: Option<String>,
111    timezone: Option<String>,
112    limiter: Arc<RateLimiter>,
113}
114
115impl std::fmt::Debug for ClickUpClient {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.debug_struct("ClickUpClient")
118            .field("base", &self.base)
119            .field("workspace_id", &self.workspace_id)
120            .finish_non_exhaustive()
121    }
122}
123
124impl ClickUpClient {
125    pub fn new(cfg: &ClickUpConfig) -> Result<Self> {
126        let token = cfg.token()?;
127        let mut auth = HeaderValue::from_str(token)
128            .map_err(|_| ClickUpError::Auth("token contains invalid characters".into()))?;
129        auth.set_sensitive(true);
130        let mut headers = HeaderMap::new();
131        headers.insert(AUTHORIZATION, auth);
132        let http = reqwest::Client::builder()
133            .default_headers(headers)
134            .timeout(std::time::Duration::from_secs(cfg.timeout_secs))
135            .user_agent(concat!("clickupc/", env!("CARGO_PKG_VERSION")))
136            .build()?;
137        Ok(Self {
138            http,
139            base: cfg.base_url.trim_end_matches('/').to_string(),
140            workspace_id: cfg.workspace_id.clone(),
141            timezone: cfg.timezone.clone(),
142            limiter: Arc::new(RateLimiter::default()),
143        })
144    }
145
146    /// Share one limiter across clients (e.g. per-profile in the MCP server).
147    pub fn with_limiter(mut self, limiter: Arc<RateLimiter>) -> Self {
148        self.limiter = limiter;
149        self
150    }
151
152    pub fn with_workspace(mut self, workspace_id: impl Into<String>) -> Self {
153        self.workspace_id = Some(workspace_id.into());
154        self
155    }
156
157    pub fn limiter(&self) -> &Arc<RateLimiter> {
158        &self.limiter
159    }
160
161    pub fn timezone(&self) -> Option<&str> {
162        self.timezone.as_deref()
163    }
164
165    pub fn workspace_id(&self) -> Result<&str> {
166        self.workspace_id.as_deref().ok_or_else(|| {
167            ClickUpError::Config(
168                "no workspace selected; run `clickupc workspace use <name>` or set CLICKUP_WORKSPACE_ID"
169                    .into(),
170            )
171        })
172    }
173
174    pub(crate) async fn get<T: DeserializeOwned>(&self, path: &str, q: &Query) -> Result<T> {
175        self.call(Method::GET, path, q, None).await
176    }
177
178    pub(crate) async fn post<T: DeserializeOwned>(
179        &self,
180        path: &str,
181        q: &Query,
182        body: Value,
183    ) -> Result<T> {
184        self.call(Method::POST, path, q, Some(Body::Json(body)))
185            .await
186    }
187
188    pub(crate) async fn put<T: DeserializeOwned>(
189        &self,
190        path: &str,
191        q: &Query,
192        body: Value,
193    ) -> Result<T> {
194        self.call(Method::PUT, path, q, Some(Body::Json(body)))
195            .await
196    }
197
198    pub(crate) async fn delete(&self, path: &str, q: &Query) -> Result<Value> {
199        self.call(Method::DELETE, path, q, None).await
200    }
201
202    pub(crate) async fn call<T: DeserializeOwned>(
203        &self,
204        method: Method,
205        path: &str,
206        q: &Query,
207        body: Option<Body>,
208    ) -> Result<T> {
209        let value = self.send(method, path, q, body.as_ref()).await?;
210        Ok(serde_json::from_value(value)?)
211    }
212
213    fn build(&self, method: &Method, path: &str, q: &Query, body: Option<&Body>) -> RequestBuilder {
214        let mut req = self
215            .http
216            .request(method.clone(), format!("{}{}", self.base, path));
217        if !q.pairs().is_empty() {
218            req = req.query(q.pairs());
219        }
220        match body {
221            Some(Body::Json(v)) => req.json(v),
222            Some(Body::File {
223                field,
224                name,
225                bytes,
226                mime,
227            }) => {
228                let part = reqwest::multipart::Part::bytes(bytes.clone()).file_name(name.clone());
229                let part = part.mime_str(mime).unwrap_or_else(|_| {
230                    reqwest::multipart::Part::bytes(bytes.clone()).file_name(name.clone())
231                });
232                req.multipart(reqwest::multipart::Form::new().part(*field, part))
233            }
234            None => req,
235        }
236    }
237
238    async fn send(
239        &self,
240        method: Method,
241        path: &str,
242        q: &Query,
243        body: Option<&Body>,
244    ) -> Result<Value> {
245        let mut attempt = 0;
246        loop {
247            self.limiter.wait().await;
248            let resp = self.build(&method, path, q, body).send().await?;
249            let status = resp.status();
250            let headers = resp.headers().clone();
251            self.limiter.observe(&headers);
252            tracing::debug!(
253                %method,
254                path,
255                status = status.as_u16(),
256                remaining = ?self.limiter.remaining(),
257                "clickup request"
258            );
259
260            if status == StatusCode::TOO_MANY_REQUESTS {
261                let (delay, reset_at) = retry_delay(&headers);
262                if attempt >= MAX_RETRIES {
263                    return Err(ClickUpError::RateLimit { reset_at });
264                }
265                attempt += 1;
266                tracing::debug!(?delay, attempt, "429 from ClickUp; retrying");
267                tokio::time::sleep(delay).await;
268                continue;
269            }
270
271            let text = resp.text().await?;
272            if status.is_success() {
273                if text.trim().is_empty() {
274                    return Ok(Value::Null);
275                }
276                return Ok(serde_json::from_str(&text)?);
277            }
278            return Err(parse_error(status.as_u16(), &text));
279        }
280    }
281
282    /// Escape hatch for `clickupc api` / `clickup_api_request`.
283    /// `path` may carry a query string; `{workspace}` is substituted.
284    pub async fn raw(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value> {
285        let method = Method::from_bytes(method.trim().to_ascii_uppercase().as_bytes())
286            .map_err(|_| ClickUpError::Invalid(format!("invalid HTTP method '{method}'")))?;
287        let mut path = path.trim().to_string();
288        if path.contains("{workspace}") {
289            path = path.replace("{workspace}", self.workspace_id()?);
290        }
291        if let Some(rest) = path.strip_prefix("/api/") {
292            path = format!("/{rest}");
293        }
294        if !path.starts_with('/') {
295            return Err(ClickUpError::Invalid(
296                "path must start with '/' (e.g. /v2/team)".into(),
297            ));
298        }
299        let (path, query) = match path.split_once('?') {
300            Some((p, qs)) => {
301                let q = url::form_urlencoded::parse(qs.as_bytes())
302                    .fold(Query::new(), |q, (k, v)| q.push(&k, v));
303                (p.to_string(), q)
304            }
305            None => (path, Query::new()),
306        };
307        self.send(method, &path, &query, body.map(Body::Json).as_ref())
308            .await
309    }
310}
311
312/// v2: `{ "err": "...", "ECODE": "..." }`; v3: `{ "message", "trace_id", ... }`.
313pub(crate) fn parse_error(status: u16, text: &str) -> ClickUpError {
314    let v: Value = serde_json::from_str(text).unwrap_or(Value::Null);
315    let str_of = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
316    let code = str_of("ECODE").or_else(|| str_of("code"));
317    let message = str_of("err")
318        .or_else(|| str_of("message"))
319        .or_else(|| str_of("error"))
320        .unwrap_or_else(|| {
321            let t = text.trim();
322            if t.is_empty() {
323                StatusCode::from_u16(status)
324                    .ok()
325                    .and_then(|s| s.canonical_reason())
326                    .unwrap_or("request failed")
327                    .to_string()
328            } else {
329                t.chars().take(500).collect()
330            }
331        });
332    let message = redact(&message);
333    let with_code = match &code {
334        Some(c) => format!("{message} [{c}]"),
335        None => message.clone(),
336    };
337    match status {
338        401 => ClickUpError::Auth(with_code),
339        404 => ClickUpError::NotFound(with_code),
340        _ => ClickUpError::Api {
341            status,
342            code,
343            message: if status == 403 {
344                format!("{message} (this may require a higher ClickUp plan or more permissions)")
345            } else {
346                message
347            },
348            trace_id: str_of("trace_id"),
349        },
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn parses_v2_and_v3_errors() {
359        match parse_error(400, r#"{"err":"Status not found","ECODE":"CRTSK_001"}"#) {
360            ClickUpError::Api { code, message, .. } => {
361                assert_eq!(code.as_deref(), Some("CRTSK_001"));
362                assert_eq!(message, "Status not found");
363            }
364            other => panic!("unexpected {other:?}"),
365        }
366        match parse_error(
367            422,
368            r#"{"status":422,"message":"Bad page","trace_id":"t-1","timestamp":1}"#,
369        ) {
370            ClickUpError::Api {
371                trace_id, message, ..
372            } => {
373                assert_eq!(trace_id.as_deref(), Some("t-1"));
374                assert_eq!(message, "Bad page");
375            }
376            other => panic!("unexpected {other:?}"),
377        }
378        assert!(matches!(
379            parse_error(401, r#"{"err":"Token invalid","ECODE":"OAUTH_025"}"#),
380            ClickUpError::Auth(m) if m.contains("OAUTH_025")
381        ));
382        assert!(matches!(parse_error(404, ""), ClickUpError::NotFound(_)));
383        assert!(matches!(
384            parse_error(500, "upstream pk_secret_123 failed"),
385            ClickUpError::Api { message, .. } if !message.contains("secret")
386        ));
387    }
388
389    #[test]
390    fn query_builder_keeps_repeated_keys() {
391        let q = Query::new()
392            .push("page", 0)
393            .push_all("statuses[]", ["to do", "in progress"])
394            .push_opt("x", None::<String>)
395            .push_if("include_closed", true);
396        assert_eq!(
397            q.pairs(),
398            &[
399                ("page".into(), "0".into()),
400                ("statuses[]".into(), "to do".into()),
401                ("statuses[]".into(), "in progress".into()),
402                ("include_closed".into(), "true".into()),
403            ]
404        );
405    }
406}