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
//! Issue relations — the blocks/blocked-by DAG edges between issues.
//!
//! # Direction semantics
//!
//! Linear's `IssueRelationType` enum has **no** `blockedBy` value — direction
//! is positional. `type: blocks` means *`issueId` **blocks**
//! `relatedIssueId`*. To express "X is blocked by Y", create the relation as
//! `create(issue = Y, related = X, Blocks)`, or read it from X's
//! `inverseRelations`.
//!
//! On an issue, `Issue.relations` holds the **outgoing** edges (this issue →
//! related issue) and `Issue.inverseRelations` holds the **incoming** edges
//! (other issue → this issue). [`RelationsService::of_issue`] returns both
//! sides as an [`IssueRelations`], whose [`blocks`](IssueRelations::blocks)
//! and [`blocked_by`](IssueRelations::blocked_by) views apply these rules so
//! callers never have to.

use serde::{Deserialize, Serialize};

use crate::client::LinearClient;
use crate::error::{Error, Result};
use crate::ids::{IssueRef, IssueRelationId};
use crate::types::{IssueRelationType, IssueStub, ensure_success};

/// Appends the canonical fragments to an operation. Documents must be
/// self-contained: each one that spreads `...RelationFields` carries the
/// fragment definitions itself. The field sets MUST stay in sync with
/// [`IssueRelation`] and [`IssueStub`].
macro_rules! with_fragments {
    ($doc:literal) => {
        concat!(
            $doc,
            " fragment RelationFields on IssueRelation",
            " { id type issue { ...IssueStubFields } relatedIssue { ...IssueStubFields } }",
            " fragment IssueStubFields on Issue { id identifier title }"
        )
    };
}

const ISSUE_RELATION_CREATE: &str = with_fragments!(
    "mutation IssueRelationCreate($input: IssueRelationCreateInput!) \
     { issueRelationCreate(input: $input) { success issueRelation { ...RelationFields } } }"
);

const ISSUE_RELATION_DELETE: &str =
    "mutation IssueRelationDelete($id: String!) { issueRelationDelete(id: $id) { success } }";

const ISSUE_RELATIONS_OF: &str = with_fragments!(
    "query IssueRelationsOf($id: String!) \
     { issue(id: $id) \
     { relations(first: 50) { nodes { ...RelationFields } } \
     inverseRelations(first: 50) { nodes { ...RelationFields } } } }"
);

pub(crate) const DOCUMENTS: &[(&str, &str)] = &[
    ("IssueRelationCreate", ISSUE_RELATION_CREATE),
    ("IssueRelationDelete", ISSUE_RELATION_DELETE),
    ("IssueRelationsOf", ISSUE_RELATIONS_OF),
];

/// One directed relation edge between two issues.
///
/// Direction is positional: for [`IssueRelationType::Blocks`], [`issue`]
/// blocks [`related_issue`] — there is no `blockedBy` relation type.
///
/// [`issue`]: IssueRelation::issue
/// [`related_issue`]: IssueRelation::related_issue
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssueRelation {
    /// Relation ID.
    pub id: IssueRelationId,
    /// How [`issue`](IssueRelation::issue) relates to
    /// [`related_issue`](IssueRelation::related_issue).
    #[serde(rename = "type")]
    pub relation_type: IssueRelationType,
    /// The source issue the relation originates from.
    pub issue: IssueStub,
    /// The target issue the relation points at.
    pub related_issue: IssueStub,
}

/// Both directions of an issue's relation edges, as returned by
/// [`RelationsService::of_issue`].
///
/// `outgoing` mirrors `Issue.relations` (this issue is the source);
/// `incoming` mirrors `Issue.inverseRelations` (this issue is the target).
/// With `type: blocks` meaning *source blocks target*: the issues this one
/// blocks live in `outgoing`, and the issues blocking this one live in
/// `incoming` — use [`blocks`](Self::blocks) / [`blocked_by`](Self::blocked_by)
/// instead of filtering by hand.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct IssueRelations {
    /// Edges where this issue is the source (`Issue.relations`).
    pub outgoing: Vec<IssueRelation>,
    /// Edges where this issue is the target (`Issue.inverseRelations`).
    pub incoming: Vec<IssueRelation>,
}

impl IssueRelations {
    /// The issues this issue **blocks**: outgoing edges with
    /// [`IssueRelationType::Blocks`], yielding each edge's target.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let relations = client
    ///     .relations()
    ///     .of_issue(linear_api::IssueRef::identifier("ENG-3"))
    ///     .await?;
    /// for blocked in relations.blocks() {
    ///     println!("ENG-3 blocks {}", blocked.identifier);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn blocks(&self) -> Vec<&IssueStub> {
        self.outgoing
            .iter()
            .filter(|r| r.relation_type == IssueRelationType::Blocks)
            .map(|r| &r.related_issue)
            .collect()
    }

    /// The issues this issue is **blocked by**: incoming edges with
    /// [`IssueRelationType::Blocks`], yielding each edge's source.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let relations = client
    ///     .relations()
    ///     .of_issue(linear_api::IssueRef::identifier("ENG-3"))
    ///     .await?;
    /// for blocker in relations.blocked_by() {
    ///     println!("ENG-3 is blocked by {}", blocker.identifier);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn blocked_by(&self) -> Vec<&IssueStub> {
        self.incoming
            .iter()
            .filter(|r| r.relation_type == IssueRelationType::Blocks)
            .map(|r| &r.issue)
            .collect()
    }
}

/// Wire shape of `IssueRelationCreateInput`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateVarsInput {
    issue_id: String,
    related_issue_id: String,
    #[serde(rename = "type")]
    relation_type: IssueRelationType,
}

/// Issue-relation operations: the blocks/blocked-by DAG edges between
/// issues. Obtain via [`LinearClient::relations`].
///
/// # Direction semantics
///
/// The relation type enum has **no** `blockedBy` value; direction is
/// positional. `type: blocks` means the **source** issue (`issueId`) blocks
/// the **target** issue (`relatedIssueId`). "X is blocked by Y" is therefore
/// created as `create(Y, X, Blocks)` — or with
/// [`create_blocks`](Self::create_blocks), which names its parameters — and
/// read from X's incoming edges via
/// [`IssueRelations::blocked_by`].
#[derive(Clone, Copy)]
pub struct RelationsService<'a> {
    client: &'a LinearClient,
}

impl LinearClient {
    /// Issue-relation operations (blocks/blocked-by DAG edges).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let relations = client
    ///     .relations()
    ///     .of_issue(linear_api::IssueRef::identifier("ENG-3"))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub fn relations(&self) -> RelationsService<'_> {
        RelationsService { client: self }
    }
}

impl RelationsService<'_> {
    /// Creates a relation edge: `issue` → `related` with the given type.
    ///
    /// **Direction matters**: for [`IssueRelationType::Blocks`], `issue`
    /// blocks `related` (there is no `blockedBy` type). To record "X is
    /// blocked by Y", call `create(Y, X, Blocks)`. Both sides accept a UUID
    /// [`IssueId`](crate::IssueId) or a human identifier via
    /// [`IssueRef::identifier`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::{IssueRef, IssueRelationType, LinearClient};
    ///
    /// let client = LinearClient::from_env()?;
    /// // ENG-1 blocks ENG-2:
    /// let relation = client
    ///     .relations()
    ///     .create(
    ///         IssueRef::identifier("ENG-1"),
    ///         IssueRef::identifier("ENG-2"),
    ///         IssueRelationType::Blocks,
    ///     )
    ///     .await?;
    /// assert_eq!(relation.issue.identifier, "ENG-1");
    /// # Ok(()) }
    /// ```
    pub async fn create(
        &self,
        issue: impl Into<IssueRef>,
        related: impl Into<IssueRef>,
        relation_type: IssueRelationType,
    ) -> Result<IssueRelation> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Payload {
            success: bool,
            issue_relation: Option<IssueRelation>,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_relation_create: Payload,
        }

        let input = CreateVarsInput {
            issue_id: issue.into().api_string().to_owned(),
            related_issue_id: related.into().api_string().to_owned(),
            relation_type,
        };
        let payload = self
            .client
            .mutation::<_, Data>(
                "IssueRelationCreate",
                ISSUE_RELATION_CREATE,
                serde_json::json!({ "input": input }),
            )
            .await?
            .issue_relation_create;
        ensure_success("IssueRelationCreate", payload.success)?;
        payload.issue_relation.ok_or(Error::MissingData {
            operation: "IssueRelationCreate",
        })
    }

    /// Records that `blocker` **blocks** `blocked` — shorthand for
    /// [`create(blocker, blocked, Blocks)`](Self::create) with the direction
    /// spelled out in the parameter names.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::{IssueRef, LinearClient};
    ///
    /// let client = LinearClient::from_env()?;
    /// // ENG-2 cannot start until ENG-1 is done:
    /// client
    ///     .relations()
    ///     .create_blocks(
    ///         IssueRef::identifier("ENG-1"), // blocker
    ///         IssueRef::identifier("ENG-2"), // blocked
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn create_blocks(
        &self,
        blocker: impl Into<IssueRef>,
        blocked: impl Into<IssueRef>,
    ) -> Result<IssueRelation> {
        self.create(blocker, blocked, IssueRelationType::Blocks)
            .await
    }

    /// Deletes a relation edge by its ID.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::{IssueRef, LinearClient};
    ///
    /// let client = LinearClient::from_env()?;
    /// let relations = client
    ///     .relations()
    ///     .of_issue(IssueRef::identifier("ENG-3"))
    ///     .await?;
    /// if let Some(edge) = relations.outgoing.first() {
    ///     client.relations().delete(&edge.id).await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn delete(&self, id: &IssueRelationId) -> Result<()> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_relation_delete: Payload,
        }

        let data = self
            .client
            .mutation::<_, Data>(
                "IssueRelationDelete",
                ISSUE_RELATION_DELETE,
                serde_json::json!({ "id": id }),
            )
            .await?;
        ensure_success("IssueRelationDelete", data.issue_relation_delete.success)
    }

    /// Fetches both directions of an issue's relation edges: `outgoing` =
    /// `Issue.relations` (this issue is the source), `incoming` =
    /// `Issue.inverseRelations` (this issue is the target).
    ///
    /// Fetches up to 50 edges per direction and does **not** paginate —
    /// far beyond any sane card's edge count. Accepts a UUID or a human
    /// identifier via [`IssueRef::identifier`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let relations = client
    ///     .relations()
    ///     .of_issue(linear_api::IssueRef::identifier("ENG-3"))
    ///     .await?;
    /// println!(
    ///     "blocks {} issue(s), blocked by {}",
    ///     relations.blocks().len(),
    ///     relations.blocked_by().len(),
    /// );
    /// # Ok(()) }
    /// ```
    pub async fn of_issue(&self, issue: impl Into<IssueRef>) -> Result<IssueRelations> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct IssueNode {
            #[serde(deserialize_with = "crate::types::nodes")]
            relations: Vec<IssueRelation>,
            #[serde(deserialize_with = "crate::types::nodes")]
            inverse_relations: Vec<IssueRelation>,
        }
        #[derive(Deserialize)]
        struct Data {
            issue: IssueNode,
        }

        let data = self
            .client
            .query::<_, Data>(
                "IssueRelationsOf",
                ISSUE_RELATIONS_OF,
                serde_json::json!({ "id": issue.into().api_string() }),
            )
            .await?;
        Ok(IssueRelations {
            outgoing: data.issue.relations,
            incoming: data.issue.inverse_relations,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::IssueId;

    #[test]
    fn create_input_wire_shape() {
        let input = CreateVarsInput {
            issue_id: IssueRef::identifier("ENG-1").api_string().to_owned(),
            related_issue_id: IssueRef::from(IssueId::new("uuid-2"))
                .api_string()
                .to_owned(),
            relation_type: IssueRelationType::Blocks,
        };
        assert_eq!(
            serde_json::to_value(&input).unwrap(),
            serde_json::json!({
                "issueId": "ENG-1",
                "relatedIssueId": "uuid-2",
                "type": "blocks"
            })
        );
    }

    #[test]
    fn blocks_and_blocked_by_filter_by_type_and_direction() {
        let stub = |identifier: &str| IssueStub {
            id: IssueId::new(format!("uuid-{identifier}")),
            identifier: identifier.to_owned(),
            title: format!("Issue {identifier}"),
        };
        let edge = |relation_type: IssueRelationType, from: &str, to: &str| IssueRelation {
            id: IssueRelationId::new(format!("rel-{from}-{to}")),
            relation_type,
            issue: stub(from),
            related_issue: stub(to),
        };
        let relations = IssueRelations {
            outgoing: vec![
                edge(IssueRelationType::Blocks, "ENG-3", "ENG-4"),
                edge(IssueRelationType::Related, "ENG-3", "ENG-5"),
            ],
            incoming: vec![
                edge(IssueRelationType::Blocks, "ENG-2", "ENG-3"),
                edge(IssueRelationType::Duplicate, "ENG-6", "ENG-3"),
            ],
        };

        let blocks: Vec<&str> = relations
            .blocks()
            .iter()
            .map(|s| s.identifier.as_str())
            .collect();
        assert_eq!(blocks, vec!["ENG-4"]);

        let blocked_by: Vec<&str> = relations
            .blocked_by()
            .iter()
            .map(|s| s.identifier.as_str())
            .collect();
        assert_eq!(blocked_by, vec!["ENG-2"]);
    }
}