xbp 10.26.3

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
501
502
503
504
505
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value as JsonValue};

const LINEAR_GRAPHQL_ENDPOINT: &str = "https://api.linear.app/graphql";
const LINEAR_USER_AGENT: &str = "xbp-cli/1.0";

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LinearInitiativeSummary {
    pub(crate) id: String,
    pub(crate) name: String,
    pub(crate) status: Option<String>,
    pub(crate) health: Option<String>,
    pub(crate) archived_at: Option<String>,
    pub(crate) target_date: Option<String>,
    pub(crate) owner_name: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct GraphqlTypeRef {
    pub(crate) name: Option<String>,
    #[serde(rename = "ofType")]
    pub(crate) of_type: Option<Box<GraphqlTypeRef>>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct GraphqlFieldArg {
    pub(crate) name: String,
    #[serde(rename = "type")]
    pub(crate) type_ref: GraphqlTypeRef,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct GraphqlField {
    pub(crate) name: String,
    pub(crate) args: Vec<GraphqlFieldArg>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct GraphqlTypeData {
    pub(crate) fields: Option<Vec<GraphqlField>>,
    #[serde(rename = "inputFields")]
    pub(crate) input_fields: Option<Vec<GraphqlFieldArg>>,
    #[serde(rename = "enumValues")]
    pub(crate) enum_values: Option<Vec<GraphqlEnumValue>>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct GraphqlEnumValue {
    pub(crate) name: String,
}

#[derive(Debug, Clone, Deserialize)]
struct LinearInitiativesPage {
    nodes: Vec<LinearInitiativeNode>,
    #[serde(rename = "pageInfo")]
    page_info: LinearPageInfo,
}

#[derive(Debug, Clone, Deserialize)]
struct LinearPageInfo {
    #[serde(rename = "hasNextPage")]
    has_next_page: bool,
    #[serde(rename = "endCursor")]
    end_cursor: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
struct LinearInitiativeNode {
    id: String,
    name: String,
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    health: Option<String>,
    #[serde(default, rename = "archivedAt")]
    archived_at: Option<String>,
    #[serde(default, rename = "targetDate")]
    target_date: Option<String>,
    #[serde(default)]
    owner: Option<LinearOwner>,
}

#[derive(Debug, Clone, Deserialize)]
struct LinearOwner {
    #[serde(default)]
    name: Option<String>,
}

#[async_trait]
trait LinearGraphqlExecutor {
    async fn execute(&mut self, body: &JsonValue) -> Result<JsonValue, String>;
}

struct ReqwestLinearGraphqlExecutor<'a> {
    api_key: &'a str,
}

#[async_trait]
impl LinearGraphqlExecutor for ReqwestLinearGraphqlExecutor<'_> {
    async fn execute(&mut self, body: &JsonValue) -> Result<JsonValue, String> {
        linear_graphql_request(self.api_key, body).await
    }
}

pub(crate) async fn fetch_available_initiatives(
    api_key: &str,
) -> Result<Vec<LinearInitiativeSummary>, String> {
    let mut executor = ReqwestLinearGraphqlExecutor { api_key };
    fetch_available_initiatives_with(&mut executor).await
}

pub(crate) async fn fetch_graphql_type(
    api_key: &str,
    type_name: &str,
) -> Result<GraphqlTypeData, String> {
    let body = linear_graphql_request(
        api_key,
        &json!({
            "query": r#"
                query XbpLinearType($name: String!) {
                  __type(name: $name) {
                    fields {
                      name
                      args {
                        name
                        type {
                          name
                          ofType {
                            name
                            ofType {
                              name
                              ofType {
                                name
                                ofType {
                                  name
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                    inputFields {
                      name
                      type {
                        name
                        ofType {
                          name
                          ofType {
                            name
                            ofType {
                              name
                              ofType {
                                name
                              }
                            }
                          }
                        }
                      }
                    }
                    enumValues {
                      name
                    }
                  }
                }
            "#,
            "variables": {
                "name": type_name
            }
        }),
    )
    .await?;

    if let Some(errors) = body.get("errors").and_then(JsonValue::as_array) {
        let message = errors
            .first()
            .and_then(|error| error.get("message"))
            .and_then(JsonValue::as_str)
            .unwrap_or("unknown Linear API error");
        return Err(message.to_string());
    }

    let type_value = body
        .get("data")
        .and_then(|data| data.get("__type"))
        .cloned()
        .ok_or_else(|| {
            format!(
                "Linear schema type lookup for `{}` returned no data.",
                type_name
            )
        })?;
    serde_json::from_value(type_value)
        .map_err(|e| format!("Failed to decode Linear schema for `{}`: {}", type_name, e))
}

pub(crate) async fn linear_graphql_request(
    api_key: &str,
    body: &JsonValue,
) -> Result<JsonValue, String> {
    let response = reqwest::Client::new()
        .post(LINEAR_GRAPHQL_ENDPOINT)
        .header("Authorization", api_key.trim())
        .header("Content-Type", "application/json")
        .header("User-Agent", LINEAR_USER_AGENT)
        .json(body)
        .send()
        .await
        .map_err(|e| format!("Linear API request failed: {}", e))?;
    let status = response.status();
    let body: JsonValue = response
        .json()
        .await
        .map_err(|e| format!("Failed to decode Linear API response: {}", e))?;
    if !status.is_success() {
        let detail = body
            .get("errors")
            .and_then(JsonValue::as_array)
            .and_then(|errors| errors.first())
            .and_then(|error| error.get("message"))
            .and_then(JsonValue::as_str)
            .unwrap_or("unknown Linear API error");
        return Err(format!("Linear API returned {}: {}", status, detail));
    }

    Ok(body)
}

pub(crate) fn named_type_name(type_ref: &GraphqlTypeRef) -> Option<String> {
    let mut current = Some(type_ref);
    while let Some(value) = current {
        if let Some(name) = &value.name {
            return Some(name.clone());
        }
        current = value.of_type.as_deref();
    }
    None
}

async fn fetch_available_initiatives_with<E>(
    executor: &mut E,
) -> Result<Vec<LinearInitiativeSummary>, String>
where
    E: LinearGraphqlExecutor + Send,
{
    let mut initiatives = Vec::new();
    let mut after: Option<String> = None;

    loop {
        let page = fetch_initiatives_page(executor, after.as_deref()).await?;
        initiatives.extend(
            page.nodes
                .into_iter()
                .filter(|initiative| initiative.archived_at.is_none())
                .map(Into::into),
        );

        if !page.page_info.has_next_page {
            break;
        }

        after = page.page_info.end_cursor;
        if after.is_none() {
            return Err(
                "Linear initiatives pagination returned `hasNextPage=true` without an end cursor."
                    .to_string(),
            );
        }
    }

    Ok(initiatives)
}

async fn fetch_initiatives_page<E>(
    executor: &mut E,
    after: Option<&str>,
) -> Result<LinearInitiativesPage, String>
where
    E: LinearGraphqlExecutor + Send,
{
    let body = executor
        .execute(&json!({
            "query": r#"
                query XbpLinearInitiatives($after: String) {
                  initiatives(first: 50, after: $after, includeArchived: false, orderBy: updatedAt) {
                    nodes {
                      id
                      name
                      status
                      health
                      archivedAt
                      targetDate
                      owner {
                        name
                      }
                    }
                    pageInfo {
                      hasNextPage
                      endCursor
                    }
                  }
                }
            "#,
            "variables": {
                "after": after
            }
        }))
        .await?;

    parse_linear_initiatives_page(body)
}

fn parse_linear_initiatives_page(body: JsonValue) -> Result<LinearInitiativesPage, String> {
    if let Some(errors) = body.get("errors").and_then(JsonValue::as_array) {
        let message = errors
            .first()
            .and_then(|error| error.get("message"))
            .and_then(JsonValue::as_str)
            .unwrap_or("unknown Linear API error");
        return Err(message.to_string());
    }

    let initiatives = body
        .get("data")
        .and_then(|data| data.get("initiatives"))
        .cloned()
        .ok_or_else(|| "Linear initiatives query returned no data.".to_string())?;

    serde_json::from_value(initiatives)
        .map_err(|e| format!("Failed to decode Linear initiatives response: {}", e))
}

impl From<LinearInitiativeNode> for LinearInitiativeSummary {
    fn from(value: LinearInitiativeNode) -> Self {
        Self {
            id: value.id,
            name: value.name,
            status: value.status,
            health: value.health,
            archived_at: value.archived_at,
            target_date: value.target_date,
            owner_name: value.owner.and_then(|owner| owner.name),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{fetch_available_initiatives_with, LinearGraphqlExecutor, LinearInitiativeSummary};
    use async_trait::async_trait;
    use serde_json::{json, Value as JsonValue};
    use std::collections::VecDeque;

    struct MockExecutor {
        responses: VecDeque<Result<JsonValue, String>>,
        requests: Vec<JsonValue>,
    }

    #[async_trait]
    impl LinearGraphqlExecutor for MockExecutor {
        async fn execute(&mut self, body: &JsonValue) -> Result<JsonValue, String> {
            self.requests.push(body.clone());
            self.responses
                .pop_front()
                .expect("mock response should exist")
        }
    }

    #[tokio::test]
    async fn paginates_available_initiatives_and_skips_archived_rows() {
        let mut executor = MockExecutor {
            responses: VecDeque::from(vec![
                Ok(json!({
                    "data": {
                        "initiatives": {
                            "nodes": [
                                {
                                    "id": "init-1",
                                    "name": "First",
                                    "status": "Active",
                                    "health": "onTrack",
                                    "archivedAt": null,
                                    "targetDate": "2026-06-30",
                                    "owner": { "name": "floris" }
                                },
                                {
                                    "id": "init-archived",
                                    "name": "Archived",
                                    "status": "Completed",
                                    "health": "offTrack",
                                    "archivedAt": "2026-05-01T00:00:00.000Z",
                                    "targetDate": null,
                                    "owner": null
                                }
                            ],
                            "pageInfo": {
                                "hasNextPage": true,
                                "endCursor": "cursor-1"
                            }
                        }
                    }
                })),
                Ok(json!({
                    "data": {
                        "initiatives": {
                            "nodes": [
                                {
                                    "id": "init-2",
                                    "name": "Second",
                                    "status": "Planned",
                                    "health": null,
                                    "archivedAt": null,
                                    "targetDate": null,
                                    "owner": { "name": "suits" }
                                }
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": "cursor-2"
                            }
                        }
                    }
                })),
            ]),
            requests: Vec::new(),
        };

        let initiatives = fetch_available_initiatives_with(&mut executor)
            .await
            .expect("initiatives");

        assert_eq!(
            initiatives,
            vec![
                LinearInitiativeSummary {
                    id: "init-1".to_string(),
                    name: "First".to_string(),
                    status: Some("Active".to_string()),
                    health: Some("onTrack".to_string()),
                    archived_at: None,
                    target_date: Some("2026-06-30".to_string()),
                    owner_name: Some("floris".to_string()),
                },
                LinearInitiativeSummary {
                    id: "init-2".to_string(),
                    name: "Second".to_string(),
                    status: Some("Planned".to_string()),
                    health: None,
                    archived_at: None,
                    target_date: None,
                    owner_name: Some("suits".to_string()),
                },
            ]
        );
        assert_eq!(executor.requests.len(), 2);
        assert_eq!(executor.requests[0]["variables"]["after"], JsonValue::Null);
        assert_eq!(
            executor.requests[1]["variables"]["after"],
            JsonValue::String("cursor-1".to_string())
        );
    }

    #[tokio::test]
    async fn returns_empty_list_when_workspace_has_no_initiatives() {
        let mut executor = MockExecutor {
            responses: VecDeque::from(vec![Ok(json!({
                "data": {
                    "initiatives": {
                        "nodes": [],
                        "pageInfo": {
                            "hasNextPage": false,
                            "endCursor": null
                        }
                    }
                }
            }))]),
            requests: Vec::new(),
        };

        let initiatives = fetch_available_initiatives_with(&mut executor)
            .await
            .expect("initiatives");
        assert!(initiatives.is_empty());
    }

    #[tokio::test]
    async fn surfaces_graphql_errors_from_initiative_query() {
        let mut executor = MockExecutor {
            responses: VecDeque::from(vec![Ok(json!({
                "errors": [
                    {
                        "message": "Linear said no"
                    }
                ]
            }))]),
            requests: Vec::new(),
        };

        let err = fetch_available_initiatives_with(&mut executor)
            .await
            .expect_err("should fail");
        assert_eq!(err, "Linear said no");
    }
}