todoist-api-rs 0.1.4

Todoist API client library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! HTTP client wrapper for the Todoist API.

use std::fmt;
use std::time::Duration;

use serde::{de::DeserializeOwned, Serialize};

use crate::error::Result;
use crate::quick_add::{QuickAddRequest, QuickAddResponse};
use crate::retry::{
    execute_empty_with_retry, execute_with_retry, RetryConfig, DEFAULT_INITIAL_BACKOFF_SECS,
    DEFAULT_MAX_BACKOFF_SECS, DEFAULT_MAX_RETRIES,
};
use crate::sync::{SyncRequest, SyncResponse};

/// Base URL for the Todoist API v1.
const BASE_URL: &str = "https://api.todoist.com/api/v1";

/// Default request timeout in seconds.
const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// Builder for creating a [`TodoistClient`] with custom configuration.
///
/// # Thread Safety
///
/// The builder itself is [`Send`] and [`Sync`]. The built [`TodoistClient`]
/// is also thread-safe and can be freely shared across threads.
///
/// # Example
///
/// ```
/// use std::time::Duration;
/// use todoist_api_rs::client::TodoistClientBuilder;
///
/// let client = TodoistClientBuilder::new("your-api-token")
///     .max_retries(5)
///     .initial_backoff(Duration::from_millis(500))
///     .max_backoff(Duration::from_secs(60))
///     .request_timeout(Duration::from_secs(45))
///     .build()
///     .expect("Failed to build client");
/// ```
#[derive(Clone, Debug)]
pub struct TodoistClientBuilder {
    token: String,
    base_url: String,
    max_retries: u32,
    initial_backoff: Duration,
    max_backoff: Duration,
    request_timeout: Duration,
}

impl TodoistClientBuilder {
    /// Creates a new builder with the given API token and default configuration.
    ///
    /// Default values:
    /// - `max_retries`: 3
    /// - `initial_backoff`: 1 second
    /// - `max_backoff`: 30 seconds
    /// - `request_timeout`: 30 seconds
    pub fn new(token: impl Into<String>) -> Self {
        Self {
            token: token.into(),
            base_url: BASE_URL.to_string(),
            max_retries: DEFAULT_MAX_RETRIES,
            initial_backoff: Duration::from_secs(DEFAULT_INITIAL_BACKOFF_SECS),
            max_backoff: Duration::from_secs(DEFAULT_MAX_BACKOFF_SECS),
            request_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
        }
    }

    /// Sets a custom base URL (primarily for testing).
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Sets the maximum number of retry attempts for rate-limited requests.
    ///
    /// Default: 3
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Sets the initial backoff duration for exponential backoff.
    ///
    /// Default: 1 second
    pub fn initial_backoff(mut self, initial_backoff: Duration) -> Self {
        self.initial_backoff = initial_backoff;
        self
    }

    /// Sets the maximum backoff duration for exponential backoff.
    ///
    /// Default: 30 seconds
    pub fn max_backoff(mut self, max_backoff: Duration) -> Self {
        self.max_backoff = max_backoff;
        self
    }

    /// Sets the request timeout duration.
    ///
    /// Default: 30 seconds
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = timeout;
        self
    }

    /// Builds the [`TodoistClient`] with the configured settings.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP client fails to build,
    /// which can happen due to TLS configuration issues or invalid settings.
    pub fn build(self) -> Result<TodoistClient> {
        let http_client = reqwest::Client::builder()
            .timeout(self.request_timeout)
            .build()
            .map_err(crate::error::Error::Http)?;

        Ok(TodoistClient {
            token: self.token,
            http_client,
            base_url: self.base_url,
            retry_config: RetryConfig {
                max_retries: self.max_retries,
                initial_backoff: self.initial_backoff,
                max_backoff: self.max_backoff,
            },
        })
    }
}

/// Client for interacting with the Todoist API.
///
/// # Thread Safety
///
/// `TodoistClient` is both [`Send`] and [`Sync`], making it safe to share across
/// threads. The underlying HTTP client (`reqwest::Client`) handles connection
/// pooling and is designed for concurrent use.
///
/// For optimal performance, create a single client instance and share it
/// (via `Arc` or cloning) across tasks rather than creating new clients.
///
/// ```
/// use std::sync::Arc;
/// use todoist_api_rs::client::TodoistClient;
///
/// let client = Arc::new(TodoistClient::new("token").unwrap());
///
/// // Clone the Arc to share across tasks
/// let client_clone = Arc::clone(&client);
/// ```
#[derive(Clone)]
pub struct TodoistClient {
    token: String,
    http_client: reqwest::Client,
    base_url: String,
    retry_config: RetryConfig,
}

impl TodoistClient {
    /// Creates a new TodoistClient with the given API token and default configuration.
    ///
    /// This is a convenience method equivalent to:
    /// ```
    /// # use todoist_api_rs::client::TodoistClientBuilder;
    /// # let token = "your-api-token";
    /// TodoistClientBuilder::new(token).build().unwrap();
    /// ```
    ///
    /// Default configuration:
    /// - Request timeout: 30 seconds
    /// - Max retries: 3
    /// - Initial backoff: 1 second
    /// - Max backoff: 30 seconds
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP client fails to build,
    /// which can happen due to TLS configuration issues or invalid settings.
    pub fn new(token: impl Into<String>) -> Result<Self> {
        TodoistClientBuilder::new(token).build()
    }

    /// Creates a new TodoistClient with a custom base URL (for testing).
    ///
    /// The client is configured with default retry/timeout settings.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP client fails to build.
    pub fn with_base_url(token: impl Into<String>, base_url: impl Into<String>) -> Result<Self> {
        TodoistClientBuilder::new(token).base_url(base_url).build()
    }

    /// Returns a builder for creating a client with custom configuration.
    pub fn builder(token: impl Into<String>) -> TodoistClientBuilder {
        TodoistClientBuilder::new(token)
    }

    /// Returns the API token.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Returns a reference to the underlying HTTP client.
    pub fn http_client(&self) -> &reqwest::Client {
        &self.http_client
    }

    /// Returns the base URL.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Returns the maximum number of retries configured.
    pub fn max_retries(&self) -> u32 {
        self.retry_config.max_retries
    }

    /// Returns the initial backoff duration configured.
    pub fn initial_backoff(&self) -> Duration {
        self.retry_config.initial_backoff
    }

    /// Returns the maximum backoff duration configured.
    pub fn max_backoff(&self) -> Duration {
        self.retry_config.max_backoff
    }

    /// Calculates the backoff duration for a retry attempt.
    ///
    /// If `retry_after` is provided (from a 429 response), uses that value.
    /// Otherwise, uses exponential backoff: initial * 2^attempt, capped at max_backoff.
    #[cfg(test)]
    fn calculate_backoff(&self, attempt: u32, retry_after: Option<u64>) -> Duration {
        self.retry_config.calculate_backoff(attempt, retry_after)
    }

    /// Performs a GET request to the given endpoint with automatic retry on rate limiting.
    ///
    /// # Arguments
    /// * `endpoint` - The API endpoint path (e.g., "/tasks", "/projects/123")
    ///
    /// # Returns
    /// The deserialized response body.
    pub async fn get<T: DeserializeOwned>(&self, endpoint: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, endpoint);
        let http_client = self.http_client.clone();
        let token = self.token.clone();

        execute_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            async move {
                http_client
                    .get(&url)
                    .bearer_auth(&token)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }

    /// Performs a POST request to the given endpoint with a JSON body and automatic retry.
    ///
    /// # Arguments
    /// * `endpoint` - The API endpoint path
    /// * `body` - The request body to serialize as JSON
    ///
    /// # Returns
    /// The deserialized response body.
    pub async fn post<T: DeserializeOwned, B: Serialize + Clone>(
        &self,
        endpoint: &str,
        body: &B,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, endpoint);
        let http_client = self.http_client.clone();
        let token = self.token.clone();
        let body = body.clone();

        execute_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            let body = body.clone();
            async move {
                http_client
                    .post(&url)
                    .bearer_auth(&token)
                    .json(&body)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }

    /// Performs a POST request without a body with automatic retry.
    ///
    /// # Arguments
    /// * `endpoint` - The API endpoint path
    ///
    /// # Returns
    /// The deserialized response body.
    pub async fn post_empty<T: DeserializeOwned>(&self, endpoint: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, endpoint);
        let http_client = self.http_client.clone();
        let token = self.token.clone();

        execute_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            async move {
                http_client
                    .post(&url)
                    .bearer_auth(&token)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }

    /// Performs a DELETE request to the given endpoint with automatic retry.
    ///
    /// # Arguments
    /// * `endpoint` - The API endpoint path
    ///
    /// # Returns
    /// Ok(()) on success.
    pub async fn delete(&self, endpoint: &str) -> Result<()> {
        let url = format!("{}{}", self.base_url, endpoint);
        let http_client = self.http_client.clone();
        let token = self.token.clone();

        execute_empty_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            async move {
                http_client
                    .delete(&url)
                    .bearer_auth(&token)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }

    /// Performs a sync request to the Todoist Sync API.
    ///
    /// The Sync API is the primary mechanism for reading and writing data in Todoist.
    /// It supports:
    /// - Full sync (sync_token = "*") to retrieve all data
    /// - Incremental sync using a stored sync_token
    /// - Command execution for write operations
    ///
    /// # Arguments
    /// * `request` - The sync request containing sync_token, resource_types, and/or commands
    ///
    /// # Returns
    /// A `SyncResponse` containing the requested resources and command results.
    ///
    /// # Example
    /// ```no_run
    /// use todoist_api_rs::client::TodoistClient;
    /// use todoist_api_rs::sync::SyncRequest;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let client = TodoistClient::new("your-api-token").unwrap();
    ///     let request = SyncRequest::full_sync();
    ///     let response = client.sync(request).await.unwrap();
    ///     println!("Got {} projects", response.projects.len());
    /// }
    /// ```
    pub async fn sync(&self, request: SyncRequest) -> Result<SyncResponse> {
        let url = format!("{}/sync", self.base_url);
        let http_client = self.http_client.clone();
        let token = self.token.clone();
        let form_body = request.to_form_body();

        execute_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            let form_body = form_body.clone();
            async move {
                http_client
                    .post(&url)
                    .bearer_auth(&token)
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(form_body)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }

    /// Creates a task using the Quick Add endpoint with NLP parsing.
    ///
    /// The Quick Add endpoint parses natural language input to extract project,
    /// labels, priority, due date, etc., using the same syntax as Todoist's quick add.
    ///
    /// # Arguments
    /// * `request` - The quick add request containing the text to parse
    ///
    /// # Returns
    /// A `QuickAddResponse` containing the created task and parsed metadata.
    ///
    /// # Example
    /// ```no_run
    /// use todoist_api_rs::client::TodoistClient;
    /// use todoist_api_rs::quick_add::QuickAddRequest;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let client = TodoistClient::new("your-api-token").unwrap();
    ///     let request = QuickAddRequest::new("Buy milk tomorrow #Shopping p2 @errands").unwrap();
    ///     let response = client.quick_add(request).await.unwrap();
    ///     println!("Created task: {} in project {}", response.content, response.project_id);
    /// }
    /// ```
    pub async fn quick_add(&self, request: QuickAddRequest) -> Result<QuickAddResponse> {
        let url = format!("{}/tasks/quick", self.base_url);
        let http_client = self.http_client.clone();
        let token = self.token.clone();

        execute_with_retry(&self.retry_config, || {
            let url = url.clone();
            let http_client = http_client.clone();
            let token = token.clone();
            let request = request.clone();
            async move {
                http_client
                    .post(&url)
                    .bearer_auth(&token)
                    .json(&request)
                    .send()
                    .await
                    .map_err(crate::error::Error::Http)
            }
        })
        .await
    }
}

impl fmt::Debug for TodoistClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TodoistClient")
            .field("token", &"[REDACTED]")
            .field("http_client", &self.http_client)
            .finish()
    }
}

#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;