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