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
//! Wiremock tests for the comments module: thread reads (single page,
//! pagination, the "last 5 comments" call shape), create/update/delete,
//! wire-format pinning, and typed error mapping.

mod support;

use futures::TryStreamExt;
use linear_api::comments::{Comment, CommentCreateInput, CommentListRequest};
use linear_api::{CommentId, Error, IssueRef, LinearErrorType};
use serde_json::json;
use support::{Operation, client_for, graphql_errors, graphql_ok};
use time::macros::datetime;
use wiremock::matchers::{any, body_partial_json};
use wiremock::{Mock, MockServer, ResponseTemplate};

const PAGE1: &str = include_str!("fixtures/comments/comments_page1.json");
const PAGE2: &str = include_str!("fixtures/comments/comments_page2.json");
const CREATE: &str = include_str!("fixtures/comments/comment_create.json");

/// Serves a fixture file verbatim as the full GraphQL response body.
fn fixture(body: &'static str) -> ResponseTemplate {
    ResponseTemplate::new(200).set_body_raw(body, "application/json")
}

/// Matches request bodies whose `variables` object has NO `after` key —
/// the shape of a first-page request (`after: None` is skip-serialized).
struct NoAfterVar;

impl wiremock::Match for NoAfterVar {
    fn matches(&self, request: &wiremock::Request) -> bool {
        serde_json::from_slice::<serde_json::Value>(&request.body)
            .map(|body| body["variables"].get("after").is_none())
            .unwrap_or(false)
    }
}

// (a) Happy-path deserialization from a realistic fixture.
#[tokio::test]
async fn list_for_issue_deserializes() {
    let server = MockServer::start().await;
    Mock::given(Operation("CommentsForIssue"))
        .respond_with(fixture(PAGE1))
        .mount(&server)
        .await;

    let page = client_for(&server)
        .comments()
        .list_for_issue(
            IssueRef::identifier("ENG-8123"),
            CommentListRequest::builder().build(),
        )
        .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("c1"));

    // Human-authored comment: user present, RFC3339 createdAt parsed.
    let first = &page.nodes[0];
    assert_eq!(first.id.as_str(), "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601");
    assert_eq!(first.user.as_ref().unwrap().display_name, "ada");
    assert_eq!(first.created_at, datetime!(2026-07-01 12:00:00.000 UTC));
    assert!(first.edited_at.is_none());
    assert!(first.resolved_at.is_none());
    assert!(first.parent.is_none());

    // Integration-authored comment: user is null.
    assert!(page.nodes[1].user.is_none());

    // Threaded reply: parent id points at the first comment; editedAt set.
    let reply = &page.nodes[2];
    assert_eq!(
        reply.parent.as_ref().unwrap().id.as_str(),
        "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601"
    );
    assert_eq!(
        reply.edited_at.unwrap(),
        datetime!(2026-07-02 09:06:10.000 UTC)
    );
}

// (d, pagination half) Stream walks both pages in order, passing the
// first page's end cursor as `after`.
#[tokio::test]
async fn list_paginates_two_pages() {
    let server = MockServer::start().await;
    Mock::given(Operation("CommentsForIssue"))
        .and(NoAfterVar)
        .respond_with(fixture(PAGE1))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(Operation("CommentsForIssue"))
        .and(body_partial_json(json!({ "variables": { "after": "c1" } })))
        .respond_with(fixture(PAGE2))
        .expect(1)
        .mount(&server)
        .await;

    let comments: Vec<Comment> = client_for(&server)
        .comments()
        .list_for_issue_stream(
            IssueRef::identifier("ENG-8123"),
            CommentListRequest::builder().build(),
        )
        .try_collect()
        .await
        .unwrap();

    assert_eq!(comments.len(), 4);
    let ids: Vec<&str> = comments.iter().map(|c| c.id.as_str()).collect();
    assert_eq!(
        ids,
        vec![
            "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601",
            "6a0b2d3f-9e4c-4b70-af12-c3d4e5f60712",
            "7b1c3e40-af5d-4c81-b023-d4e5f6071823",
            "8c2d4f51-b06e-4d92-c134-e5f607182934",
        ]
    );
    assert_eq!(server.received_requests().await.unwrap().len(), 2);
}

// (c) The deep-view call shape: "last 5 comments" sends first: 5.
#[tokio::test]
async fn last_five_pattern() {
    let server = MockServer::start().await;
    Mock::given(Operation("CommentsForIssue"))
        .and(body_partial_json(
            json!({ "variables": { "id": "ENG-8123", "first": 5 } }),
        ))
        .respond_with(fixture(PAGE2))
        .expect(1)
        .mount(&server)
        .await;

    client_for(&server)
        .comments()
        .list_for_issue(
            IssueRef::identifier("ENG-8123"),
            CommentListRequest::builder().first(5).build(),
        )
        .await
        .unwrap();

    // .expect(1) verifies the matcher (variables.first == 5) on drop.
}

// (d) Wire-format pin for CommentCreateInput + full create roundtrip.
#[tokio::test]
async fn create_wire_format() {
    let input = CommentCreateInput::builder()
        .issue_id("ENG-8123")
        .body("Run finished: all green. Patch attached to the PR.".to_owned())
        .parent_id(CommentId::new("5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601"))
        .build();

    let wire = serde_json::to_value(&input).unwrap();
    insta::assert_json_snapshot!(wire, @r#"
    {
      "body": "Run finished: all green. Patch attached to the PR.",
      "issueId": "ENG-8123",
      "parentId": "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601"
    }
    "#);
    assert!(wire.get("createAsUser").is_none());

    let server = MockServer::start().await;
    Mock::given(Operation("CommentCreate"))
        .and(body_partial_json(json!({
            "variables": { "input": {
                "issueId": "ENG-8123",
                "parentId": "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601"
            } }
        })))
        .respond_with(fixture(CREATE))
        .expect(1)
        .mount(&server)
        .await;

    let comment = client_for(&server).comments().create(input).await.unwrap();

    assert_eq!(comment.id.as_str(), "9d3e5062-c17f-4ea3-d245-f60718293a45");
    assert_eq!(
        comment.body,
        "Run finished: all green. Patch attached to the PR."
    );
    assert_eq!(
        comment.parent.unwrap().id.as_str(),
        "5f9a1c2e-8d3b-4a6f-9e01-b2c3d4e5f601"
    );
    assert_eq!(comment.created_at, datetime!(2026-07-04 10:00:00.000 UTC));
}

// Convenience wrapper builds the input from the issue ref.
#[tokio::test]
async fn create_on_builds_input_from_ref() {
    let server = MockServer::start().await;
    Mock::given(Operation("CommentCreate"))
        .and(body_partial_json(json!({
            "variables": { "input": { "issueId": "ENG-8123", "body": "On it." } }
        })))
        .respond_with(fixture(CREATE))
        .expect(1)
        .mount(&server)
        .await;

    let comment = client_for(&server)
        .comments()
        .create_on(IssueRef::identifier("ENG-8123"), "On it.")
        .await
        .unwrap();

    assert_eq!(comment.user.unwrap().display_name, "ada");
}

// (e) A `success: false` payload maps to Error::MutationFailed.
#[tokio::test]
async fn create_success_false_maps_to_mutation_failed() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_ok(
            json!({ "commentCreate": { "success": false, "comment": null } }),
        ))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .comments()
        .create_on(IssueRef::identifier("ENG-8123"), "hello")
        .await
        .unwrap_err();

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

// (f) A GraphQL error body maps to Error::Api with the typed extension.
#[tokio::test]
async fn graphql_error_typed() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_errors(
            400,
            json!([{
                "message": "Authentication required, not authenticated",
                "extensions": { "type": "authentication error" }
            }]),
        ))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .comments()
        .list_for_issue(
            IssueRef::identifier("ENG-8123"),
            CommentListRequest::builder().first(5).build(),
        )
        .await
        .unwrap_err();

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

// (g) Update happy path: body replaced, updated comment returned.
#[tokio::test]
async fn update_happy_path() {
    let server = MockServer::start().await;
    let id = CommentId::new("9d3e5062-c17f-4ea3-d245-f60718293a45");
    Mock::given(Operation("CommentUpdate"))
        .and(body_partial_json(json!({
            "variables": {
                "id": "9d3e5062-c17f-4ea3-d245-f60718293a45",
                "input": { "body": "Edited: rollout done." }
            }
        })))
        .respond_with(graphql_ok(json!({
            "commentUpdate": {
                "success": true,
                "comment": {
                    "id": "9d3e5062-c17f-4ea3-d245-f60718293a45",
                    "body": "Edited: rollout done.",
                    "url": "https://linear.app/acme/issue/ENG-8123#comment-9d3e5062",
                    "user": {
                        "id": "9c2c88a6-99d3-4a63-a201-8ee5c7dcc374",
                        "name": "Ada Lovelace",
                        "displayName": "ada"
                    },
                    "createdAt": "2026-07-04T10:00:00.000Z",
                    "editedAt": "2026-07-04T11:30:00.000Z",
                    "resolvedAt": null,
                    "parent": null
                }
            }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let comment = client_for(&server)
        .comments()
        .update(&id, "Edited: rollout done.")
        .await
        .unwrap();

    assert_eq!(comment.body, "Edited: rollout done.");
    assert_eq!(
        comment.edited_at.unwrap(),
        datetime!(2026-07-04 11:30:00.000 UTC)
    );
}

// Update error path: a typed invalid-input GraphQL error.
#[tokio::test]
async fn update_graphql_error() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_errors(
            400,
            json!([{
                "message": "body must not be empty",
                "extensions": { "type": "invalid input", "userError": true }
            }]),
        ))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .comments()
        .update(&CommentId::new("9d3e5062"), "")
        .await
        .unwrap_err();

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

// (g) Delete happy path: success true maps to Ok(()).
#[tokio::test]
async fn delete_happy_path() {
    let server = MockServer::start().await;
    Mock::given(Operation("CommentDelete"))
        .and(body_partial_json(
            json!({ "variables": { "id": "9d3e5062-c17f-4ea3-d245-f60718293a45" } }),
        ))
        .respond_with(graphql_ok(json!({ "commentDelete": { "success": true } })))
        .expect(1)
        .mount(&server)
        .await;

    client_for(&server)
        .comments()
        .delete(&CommentId::new("9d3e5062-c17f-4ea3-d245-f60718293a45"))
        .await
        .unwrap();
}

// Delete error path: success false maps to Error::MutationFailed.
#[tokio::test]
async fn delete_success_false_maps_to_mutation_failed() {
    let server = MockServer::start().await;
    Mock::given(any())
        .respond_with(graphql_ok(json!({ "commentDelete": { "success": false } })))
        .mount(&server)
        .await;

    let err = client_for(&server)
        .comments()
        .delete(&CommentId::new("9d3e5062"))
        .await
        .unwrap_err();

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

// (h) Env-gated, read-only live smoke: find any issue, list its last 5
// comments. Run with `cargo test --test comments -- --ignored`.
#[tokio::test]
#[ignore = "live API smoke; requires LINEAR_API_KEY"]
async fn live_comments_smoke() {
    let Ok(key) = std::env::var("LINEAR_API_KEY") else {
        eprintln!("LINEAR_API_KEY not set; skipping live smoke");
        return;
    };
    let client = linear_api::LinearClient::new(key).expect("client builds");

    let data = client
        .execute_raw(
            "query { issues(first: 1) { nodes { id } } }",
            serde_json::json!({}),
        )
        .await
        .expect("issues query succeeds");
    let id = data["issues"]["nodes"][0]["id"]
        .as_str()
        .expect("workspace has at least one issue")
        .to_owned();

    let page = client
        .comments()
        .list_for_issue(
            linear_api::IssueId::new(id),
            CommentListRequest::builder().first(5).build(),
        )
        .await;
    assert!(page.is_ok(), "live list_for_issue failed: {page:?}");
}