asanaclient 0.1.1

Rust SDK for the Asana API
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Events API endpoints for incremental sync.

use crate::types::{EventsResponse, EventsSyncReset};
use crate::{Client, Error};

/// Fields to request for events.
const EVENT_FIELDS: &str = "action,change,change.action,change.field,\
    created_at,parent,parent.name,resource,resource.name,type,user,user.name";

/// API for event operations (incremental sync).
pub struct EventsApi<'a> {
    client: &'a Client,
}

impl<'a> EventsApi<'a> {
    /// Create a new events API instance.
    pub fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Establish a sync token for a resource by making an initial request.
    ///
    /// The Events API requires an initial call (which returns 412) to obtain
    /// a sync token. This method makes that call and returns the fresh token.
    pub async fn establish(&self, resource_gid: &str) -> Result<String, Error> {
        let url = format!("{}/events", self.client.base_url());
        let query = [("resource", resource_gid), ("opt_fields", EVENT_FIELDS)];

        let response = self.client.http().get(&url).query(&query).send().await?;
        let status = response.status();

        if status == reqwest::StatusCode::PRECONDITION_FAILED {
            let body = response.text().await?;
            let reset: EventsSyncReset = serde_json::from_str(&body).map_err(Error::Parse)?;
            Ok(reset.sync)
        } else if status.is_success() {
            // Unexpected success on first call — parse the response and return the token
            let body = response.text().await?;
            let resp: EventsResponse = serde_json::from_str(&body).map_err(Error::Parse)?;
            Ok(resp.sync)
        } else {
            let body = response.text().await.unwrap_or_default();
            Err(Error::Api {
                message: format!("Events establish failed: HTTP {status} {body}"),
            })
        }
    }

    /// Get events for a resource since the given sync token.
    ///
    /// Automatically drains all pages (following `has_more`) and returns
    /// the aggregated response with the final sync token.
    ///
    /// Returns `Error::SyncTokenExpired { sync }` if the token has expired (412).
    pub async fn get_events(
        &self,
        resource_gid: &str,
        sync: &str,
    ) -> Result<EventsResponse, Error> {
        let mut all_events = Vec::new();
        let mut current_sync = sync.to_string();

        loop {
            let url = format!("{}/events", self.client.base_url());
            let query = [
                ("resource", resource_gid),
                ("sync", current_sync.as_str()),
                ("opt_fields", EVENT_FIELDS),
            ];

            let response = self.client.http().get(&url).query(&query).send().await?;
            let status = response.status();

            if status == reqwest::StatusCode::PRECONDITION_FAILED {
                let body = response.text().await?;
                let reset: EventsSyncReset = serde_json::from_str(&body).map_err(Error::Parse)?;
                return Err(Error::SyncTokenExpired { sync: reset.sync });
            }

            if !status.is_success() {
                let body = response.text().await.unwrap_or_default();
                return Err(Error::Api {
                    message: format!("Events API error: HTTP {status} {body}"),
                });
            }

            let body = response.text().await?;
            let page: EventsResponse = serde_json::from_str(&body).map_err(Error::Parse)?;

            all_events.extend(page.data);
            current_sync = page.sync;

            if !page.has_more {
                break;
            }
        }

        Ok(EventsResponse {
            data: all_events,
            sync: current_sync,
            has_more: false,
        })
    }
}

impl Client {
    /// Access the Events API.
    pub fn events(&self) -> EventsApi<'_> {
        EventsApi::new(self)
    }
}

#[cfg(test)]
mod tests {
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use crate::Client;

    fn test_client(server: &MockServer) -> Client {
        Client::new("test-token")
            .unwrap()
            .with_base_url(&server.uri())
    }

    #[tokio::test]
    async fn test_establish_returns_sync_token() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .respond_with(ResponseTemplate::new(412).set_body_json(serde_json::json!({
                "sync": "fresh_token_abc",
                "errors": [{"message": "Sync token invalid or too old. If you are attempting to keep resources in sync, you must re-fetch the full dataset."}]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let token = client.events().establish("project123").await.unwrap();
        assert_eq!(token, "fresh_token_abc");
    }

    #[tokio::test]
    async fn test_get_events_success() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [
                    {
                        "resource": {"gid": "task1", "resource_type": "task", "name": "Task 1"},
                        "action": "changed",
                        "change": {"field": "completed", "action": "changed"}
                    },
                    {
                        "resource": {"gid": "task2", "resource_type": "task", "name": "Task 2"},
                        "action": "added"
                    }
                ],
                "sync": "token_2",
                "has_more": false
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let resp = client
            .events()
            .get_events("project123", "token_1")
            .await
            .unwrap();

        assert_eq!(resp.data.len(), 2);
        assert_eq!(resp.sync, "token_2");
        assert!(!resp.has_more);
        assert_eq!(resp.data[0].resource.gid, "task1");
        assert_eq!(resp.data[0].action, "changed");
        assert_eq!(resp.data[1].resource.gid, "task2");
        assert_eq!(resp.data[1].action, "added");
    }

    #[tokio::test]
    async fn test_get_events_has_more() {
        let server = MockServer::start().await;

        // First page
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [
                    {
                        "resource": {"gid": "task1", "resource_type": "task"},
                        "action": "changed"
                    }
                ],
                "sync": "token_2",
                "has_more": true
            })))
            .mount(&server)
            .await;

        // Second page
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [
                    {
                        "resource": {"gid": "task2", "resource_type": "task"},
                        "action": "added"
                    }
                ],
                "sync": "token_3",
                "has_more": false
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let resp = client
            .events()
            .get_events("project123", "token_1")
            .await
            .unwrap();

        assert_eq!(resp.data.len(), 2);
        assert_eq!(resp.sync, "token_3");
        assert_eq!(resp.data[0].resource.gid, "task1");
        assert_eq!(resp.data[1].resource.gid, "task2");
    }

    #[tokio::test]
    async fn test_get_events_token_expired() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "old_token"))
            .respond_with(ResponseTemplate::new(412).set_body_json(serde_json::json!({
                "sync": "new_fresh_token",
                "errors": [{"message": "Sync token invalid or too old."}]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().get_events("project123", "old_token").await;

        match result {
            Err(crate::Error::SyncTokenExpired { sync }) => {
                assert_eq!(sync, "new_fresh_token");
            }
            other => panic!("Expected SyncTokenExpired, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_get_events_sends_opt_fields() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .and(query_param(
                "opt_fields",
                "action,change,change.action,change.field,created_at,parent,parent.name,resource,resource.name,type,user,user.name",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [],
                "sync": "token_2",
                "has_more": false
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let resp = client
            .events()
            .get_events("project123", "token_1")
            .await
            .unwrap();

        assert!(resp.data.is_empty());
        assert_eq!(resp.sync, "token_2");
    }

    #[tokio::test]
    async fn test_establish_unexpected_success() {
        let server = MockServer::start().await;

        // Unexpected 200 response on first call (should be 412, but API returns 200)
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [
                    {
                        "resource": {"gid": "task1", "resource_type": "task"},
                        "action": "changed"
                    }
                ],
                "sync": "unexpected_token",
                "has_more": false
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let token = client.events().establish("project123").await.unwrap();
        assert_eq!(token, "unexpected_token");
    }

    #[tokio::test]
    async fn test_establish_api_error() {
        let server = MockServer::start().await;

        // API returns 500 error
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "errors": [{"message": "Internal server error"}]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().establish("project123").await;

        match result {
            Err(crate::Error::Api { message }) => {
                assert!(
                    message.contains("HTTP 500"),
                    "Expected HTTP 500 in message, got: {}",
                    message
                );
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_establish_malformed_412_response() {
        let server = MockServer::start().await;

        // 412 response with invalid JSON body
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .respond_with(ResponseTemplate::new(412).set_body_string("not valid json"))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().establish("project123").await;

        match result {
            Err(crate::Error::Parse(_)) => {
                // Expected parse error
            }
            other => panic!("Expected Parse error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_get_events_api_error() {
        let server = MockServer::start().await;

        // API returns 429 rate limit error
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(429).set_body_json(serde_json::json!({
                "errors": [{"message": "Rate limit exceeded"}]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().get_events("project123", "token_1").await;

        match result {
            Err(crate::Error::Api { message }) => {
                assert!(
                    message.contains("HTTP 429"),
                    "Expected HTTP 429 in message, got: {}",
                    message
                );
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_get_events_malformed_response() {
        let server = MockServer::start().await;

        // 200 response with malformed JSON
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(200).set_body_string("{\"data\": [invalid json"))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().get_events("project123", "token_1").await;

        match result {
            Err(crate::Error::Parse(_)) => {
                // Expected parse error
            }
            other => panic!("Expected Parse error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_get_events_empty_response() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [],
                "sync": "token_2",
                "has_more": false
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let resp = client
            .events()
            .get_events("project123", "token_1")
            .await
            .unwrap();

        assert_eq!(resp.data.len(), 0);
        assert_eq!(resp.sync, "token_2");
        assert!(!resp.has_more);
    }

    #[tokio::test]
    async fn test_get_events_pagination_error_on_second_page() {
        let server = MockServer::start().await;

        // First page succeeds
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [
                    {
                        "resource": {"gid": "task1", "resource_type": "task"},
                        "action": "changed"
                    }
                ],
                "sync": "token_2",
                "has_more": true
            })))
            .mount(&server)
            .await;

        // Second page returns error
        Mock::given(method("GET"))
            .and(path("/events"))
            .and(query_param("resource", "project123"))
            .and(query_param("sync", "token_2"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "errors": [{"message": "Server error"}]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.events().get_events("project123", "token_1").await;

        match result {
            Err(crate::Error::Api { message }) => {
                assert!(message.contains("HTTP 500"));
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }
}