linear-api 0.1.0

Unofficial async Rust client for the Linear GraphQL API (API-key auth)
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
//! Wiremock tests for the labels module: list/create/update/delete wire
//! formats, error mapping, pagination, and the `ensure` find-or-create flow.

mod support;

use futures::TryStreamExt;
use linear_api::labels::{LabelCreateInput, LabelUpdateInput, ListLabelsRequest};
use linear_api::{Error, LabelId, LinearErrorType, TeamId, Undefinable};
use support::{Operation, client_for, graphql_errors, graphql_ok};
use wiremock::matchers::{any, body_partial_json};
use wiremock::{Mock, MockServer};

const TEAM_ID: &str = "5c9d1a4e-2e6f-4b8a-8c1d-7a6b5c4d3e2f";

fn fixture(raw: &str) -> serde_json::Value {
    serde_json::from_str(raw).expect("fixture parses")
}

fn label_node(name: &str, team: Option<&str>) -> serde_json::Value {
    serde_json::json!({
        "id": format!("label-{}", name.to_lowercase()),
        "name": name,
        "color": "#EB5757",
        "description": null,
        "isGroup": false,
        "parent": null,
        "team": team.map(|id| serde_json::json!({ "id": id, "key": "ENG", "name": "Engineering" })),
    })
}

fn label_page(nodes: Vec<serde_json::Value>, end_cursor: Option<&str>) -> serde_json::Value {
    serde_json::json!({
        "issueLabels": {
            "nodes": nodes,
            "pageInfo": {
                "hasNextPage": end_cursor.is_some(),
                "hasPreviousPage": false,
                "startCursor": null,
                "endCursor": end_cursor,
            }
        }
    })
}

// (a) Happy-path deserialization of a realistic three-shape fixture: a team
// label, a workspace label (team: null), and a group with a parent.
#[tokio::test]
async fn list_deserializes() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelList"))
        .respond_with(graphql_ok(fixture(include_str!(
            "fixtures/labels/label_list.json"
        ))))
        .mount(&server)
        .await;

    let page = client_for(&server)
        .labels()
        .list(ListLabelsRequest::default())
        .await
        .unwrap();

    assert_eq!(page.nodes.len(), 3);
    assert!(!page.page_info.has_next_page);
    assert_eq!(page.page_info.end_cursor.as_deref(), Some("cursor-end"));

    let team_label = &page.nodes[0];
    assert_eq!(team_label.name, "Bug");
    assert_eq!(team_label.color, "#EB5757");
    assert_eq!(
        team_label.description.as_deref(),
        Some("Something is broken")
    );
    assert!(!team_label.is_group);
    assert!(team_label.parent.is_none());
    assert_eq!(team_label.team.as_ref().unwrap().key, "ENG");

    let workspace_label = &page.nodes[1];
    assert_eq!(workspace_label.name, "Roadmap");
    assert!(
        workspace_label.team.is_none(),
        "team: null ⇒ workspace label"
    );
    assert!(workspace_label.description.is_none());

    let group = &page.nodes[2];
    assert!(group.is_group);
    let parent = group.parent.as_ref().unwrap();
    assert_eq!(parent.name, "Areas");
    assert_eq!(parent.color, "#F2C94C");
}

#[tokio::test]
async fn list_api_error_maps_to_typed_error() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_errors(
            400,
            serde_json::json!([{
                "message": "Argument Validation Error",
                "extensions": { "type": "invalid input" }
            }]),
        ))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .labels()
        .list(ListLabelsRequest::default())
        .await
        .unwrap_err();

    assert!(matches!(
        err,
        Error::Api {
            operation: "LabelList",
            ..
        }
    ));
    assert_eq!(err.error_types(), vec![LinearErrorType::InvalidInput]);
}

// Pagination: page two is requested with the first page's end cursor.
#[tokio::test]
async fn list_stream_walks_pages() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelList"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "after": "cursor-1" }
        })))
        .respond_with(graphql_ok(label_page(
            vec![label_node("Feature", Some(TEAM_ID))],
            None,
        )))
        .mount(&server)
        .await;
    Mock::given(Operation("LabelList"))
        .respond_with(graphql_ok(label_page(
            vec![
                label_node("Bug", Some(TEAM_ID)),
                label_node("Chore", Some(TEAM_ID)),
            ],
            Some("cursor-1"),
        )))
        .mount(&server)
        .await;
    let client = client_for(&server);
    let labels = client.labels();

    let names: Vec<String> = labels
        .list_stream(ListLabelsRequest::builder().first(2).build())
        .map_ok(|label| label.name)
        .try_collect()
        .await
        .unwrap();

    assert_eq!(names, vec!["Bug", "Chore", "Feature"]);
    assert_eq!(server.received_requests().await.unwrap().len(), 2);
}

// (b) Wire format of the create input, then a full wiremock roundtrip.
#[tokio::test]
async fn create_wire_format() {
    let input = LabelCreateInput::builder()
        .name("Bug")
        .color("#BB87FC")
        .team_id(TeamId::new(TEAM_ID))
        .build();
    insta::assert_json_snapshot!(serde_json::to_value(&input).unwrap(), @r##"
    {
      "color": "#BB87FC",
      "name": "Bug",
      "teamId": "5c9d1a4e-2e6f-4b8a-8c1d-7a6b5c4d3e2f"
    }
    "##);

    let server = MockServer::start().await;
    Mock::given(Operation("LabelCreate"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "input": { "name": "Bug", "color": "#BB87FC", "teamId": TEAM_ID } }
        })))
        .respond_with(graphql_ok(fixture(include_str!(
            "fixtures/labels/label_create.json"
        ))))
        .mount(&server)
        .await;

    let label = client_for(&server).labels().create(input).await.unwrap();

    assert_eq!(label.id.as_str(), "9f8e7d6c-5b4a-4c3d-8e2f-4d5e6f7a8b9c");
    assert_eq!(label.name, "Bug");
    assert_eq!(label.color, "#BB87FC");
    assert_eq!(label.team.as_ref().unwrap().id.as_str(), TEAM_ID);
}

// (c) Undefinable tri-state on update inputs: Null serializes as `null`,
// Undefined is omitted entirely.
#[test]
fn update_undefinable() {
    let input = LabelUpdateInput::builder()
        .name("x")
        .description(Undefinable::Null)
        .build();
    let value = serde_json::to_value(&input).unwrap();
    insta::assert_json_snapshot!(value, @r#"
    {
      "description": null,
      "name": "x"
    }
    "#);
    assert!(value.get("description").is_some_and(|v| v.is_null()));
    assert!(
        value.get("parentId").is_none(),
        "Undefined fields are omitted"
    );
}

#[tokio::test]
async fn update_roundtrip() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelUpdate"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "id": "label-bug", "input": { "color": "#26B5CE" } }
        })))
        .respond_with(graphql_ok(serde_json::json!({
            "issueLabelUpdate": {
                "success": true,
                "issueLabel": {
                    "id": "label-bug",
                    "name": "Bug",
                    "color": "#26B5CE",
                    "description": null,
                    "isGroup": false,
                    "parent": null,
                    "team": null
                }
            }
        })))
        .mount(&server)
        .await;

    let label = client_for(&server)
        .labels()
        .update(
            &LabelId::new("label-bug"),
            LabelUpdateInput::builder().color("#26B5CE").build(),
        )
        .await
        .unwrap();

    assert_eq!(label.color, "#26B5CE");
}

#[tokio::test]
async fn update_api_error() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_errors(
            400,
            serde_json::json!([{
                "message": "You don't have permission to update this label",
                "extensions": { "type": "forbidden" }
            }]),
        ))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .labels()
        .update(
            &LabelId::new("label-bug"),
            LabelUpdateInput::builder().name("nope").build(),
        )
        .await
        .unwrap_err();

    assert!(matches!(
        err,
        Error::Api {
            operation: "LabelUpdate",
            ..
        }
    ));
    assert_eq!(err.error_types(), vec![LinearErrorType::Forbidden]);
}

// (d) ensure() finds an existing label case-insensitively and never creates.
#[tokio::test]
async fn ensure_finds_existing() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelCreate"))
        .respond_with(graphql_ok(serde_json::json!({})))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(Operation("LabelList"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "filter": {
                "name": { "eqIgnoreCase": "bug" },
                "team": { "id": { "eq": TEAM_ID } }
            } }
        })))
        .respond_with(graphql_ok(label_page(
            vec![label_node("Bug", Some(TEAM_ID))],
            None,
        )))
        .mount(&server)
        .await;
    let team = TeamId::new(TEAM_ID);

    let label = client_for(&server)
        .labels()
        .ensure(Some(&team), "bug")
        .await
        .unwrap();

    assert_eq!(label.name, "Bug");
    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

// (e) ensure() creates when the lookup comes back empty.
#[tokio::test]
async fn ensure_creates_when_missing() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelList"))
        .respond_with(graphql_ok(label_page(vec![], None)))
        .mount(&server)
        .await;
    Mock::given(Operation("LabelCreate"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "input": { "name": "infra" } }
        })))
        .respond_with(graphql_ok(serde_json::json!({
            "issueLabelCreate": {
                "success": true,
                "issueLabel": label_node("infra", None),
            }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let label = client_for(&server)
        .labels()
        .ensure(None, "infra")
        .await
        .unwrap();

    assert_eq!(label.name, "infra");
    assert!(label.team.is_none(), "no team ⇒ workspace label");
}

// (f) Race tolerance: a concurrent creator wins the duplicate check, our
// create fails with InvalidInput/duplicate, and ensure() relists once.
#[tokio::test]
async fn ensure_create_race_falls_back_to_relist() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelList"))
        .respond_with(graphql_ok(label_page(vec![], None)))
        .up_to_n_times(1)
        .mount(&server)
        .await;
    Mock::given(Operation("LabelList"))
        .respond_with(graphql_ok(label_page(
            vec![label_node("Bug", Some(TEAM_ID))],
            None,
        )))
        .up_to_n_times(1)
        .mount(&server)
        .await;
    Mock::given(Operation("LabelCreate"))
        .respond_with(graphql_errors(
            400,
            serde_json::json!([{
                "message": "duplicate label name",
                "extensions": { "type": "invalid input" }
            }]),
        ))
        .expect(1)
        .mount(&server)
        .await;
    let team = TeamId::new(TEAM_ID);

    let label = client_for(&server)
        .labels()
        .ensure(Some(&team), "Bug")
        .await
        .unwrap();

    assert_eq!(label.name, "Bug");
    assert_eq!(server.received_requests().await.unwrap().len(), 3);
}

#[tokio::test]
async fn delete_success() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelDelete"))
        .and(body_partial_json(serde_json::json!({
            "variables": { "id": "label-bug" }
        })))
        .respond_with(graphql_ok(serde_json::json!({
            "issueLabelDelete": { "success": true }
        })))
        .mount(&server)
        .await;

    client_for(&server)
        .labels()
        .delete(&LabelId::new("label-bug"))
        .await
        .unwrap();
}

// (g) A delete payload with success=false and no GraphQL errors.
#[tokio::test]
async fn delete_success_false_is_mutation_failed() {
    let server = MockServer::start().await;
    Mock::given(Operation("LabelDelete"))
        .respond_with(graphql_ok(serde_json::json!({
            "issueLabelDelete": { "success": false }
        })))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .labels()
        .delete(&LabelId::new("label-bug"))
        .await
        .unwrap_err();

    assert!(matches!(
        err,
        Error::MutationFailed {
            operation: "LabelDelete"
        }
    ));
}

// (h) Read-only live smoke test; runs only under `-- --ignored` with a key.
#[tokio::test]
#[ignore = "hits the live Linear API; requires LINEAR_API_KEY"]
async fn live_labels_smoke() {
    if std::env::var("LINEAR_API_KEY").is_err() {
        eprintln!("LINEAR_API_KEY not set; skipping live smoke test");
        return;
    }
    let client = linear_api::LinearClient::from_env().expect("client from env");

    let page = client
        .labels()
        .list(ListLabelsRequest::builder().first(1).build())
        .await
        .expect("live label list");

    assert!(page.nodes.len() <= 1);
}