Skip to main content

agent_hub_runtime/core/task_browser/
runner_projects.rs

1use super::{
2    runners::{optional_string, runner_os, summary, RunnerSummary},
3    Binding, CliReader, Provider, TaskClient, TaskFailure,
4};
5use serde::Serialize;
6use serde_json::{json, Value};
7use std::{collections::HashSet, sync::atomic::AtomicBool};
8
9#[derive(Serialize)]
10pub struct CreatedProjectRunner {
11    pub id: u64,
12    pub token: String,
13}
14
15impl<R: CliReader> TaskClient<R> {
16    pub(super) fn assignable_runners(
17        &self,
18        binding: &Binding,
19        cancel: &AtomicBool,
20    ) -> Result<Vec<RunnerSummary>, TaskFailure> {
21        let repository = json!(binding.repository);
22        let mut after = Value::Null;
23        let mut ids = HashSet::new();
24        let mut runners = Vec::new();
25        for _ in 0..20 {
26            let query = format!(
27                "{{ currentUser {{ runners(type: PROJECT_TYPE, assignableToProjectPath: {repository}, first: 100, after: {after}) {{ nodes {{ id description shortSha status paused jobExecutionStatus tagList contactedAt createdAt createdBy {{ name }} ownerProject {{ fullPath }} managers(first: 2) {{ nodes {{ platformName }} }} }} pageInfo {{ hasNextPage endCursor }} }} }} }}"
28            );
29            let response = self.request(
30                binding,
31                "POST",
32                "graphql".into(),
33                &[("query", query)],
34                cancel,
35            )?;
36            let connection = &response["data"]["currentUser"]["runners"];
37            let nodes = connection["nodes"].as_array().ok_or_else(|| {
38                TaskFailure::new("invalid_response", "Assignable runners are unavailable")
39            })?;
40            for node in nodes {
41                let Some(id) = node["id"].as_str().and_then(|value| {
42                    value
43                        .strip_prefix("gid://gitlab/Ci::Runner/")?
44                        .parse::<u64>()
45                        .ok()
46                }) else {
47                    continue;
48                };
49                if !ids.insert(id) {
50                    continue;
51                }
52                let mut runner = summary(
53                    Provider::Gitlab,
54                    &json!({
55                        "id": id,
56                        "description": node["description"],
57                        "status": node["status"].as_str().map(str::to_ascii_lowercase),
58                        "paused": node["paused"],
59                        "job_execution_status": node["jobExecutionStatus"].as_str().map(str::to_ascii_lowercase),
60                        "runner_type": "project_type",
61                        "tag_list": node["tagList"],
62                        "contacted_at": node["contactedAt"],
63                        "created_at": node["createdAt"],
64                    }),
65                )?;
66                runner.short_id = optional_string(node, "shortSha").filter(|value| {
67                    value.len() == 8
68                        && value
69                            .bytes()
70                            .all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
71                });
72                runner.created_by = optional_string(&node["createdBy"], "name");
73                runner.owner_project = optional_string(&node["ownerProject"], "fullPath");
74                if let Some([manager]) = node["managers"]["nodes"].as_array().map(Vec::as_slice) {
75                    runner.os = optional_string(manager, "platformName").map(runner_os);
76                }
77                runners.push(runner);
78            }
79            let next = &connection["pageInfo"]["endCursor"];
80            if connection["pageInfo"]["hasNextPage"].as_bool() != Some(true)
81                || !next.is_string()
82                || next == &after
83            {
84                return Ok(runners);
85            }
86            after = next.clone();
87        }
88        Ok(runners)
89    }
90
91    /// Resolve a registered GitLab project and check its authenticated owner's role.
92    pub(super) fn runner_creation_project(
93        &self,
94        binding: &Binding,
95        cancel: &AtomicBool,
96    ) -> Result<u64, TaskFailure> {
97        if binding.provider != Provider::Gitlab {
98            return Err(TaskFailure::new(
99                "invalid_input",
100                "Creating project runners requires GitLab",
101            ));
102        }
103        binding.validate()?;
104        let path = urlencoding::encode(&binding.repository);
105        let project = self.api(binding, format!("projects/{path}"), cancel)?;
106        let id = project["id"]
107            .as_u64()
108            .filter(|id| *id > 0)
109            .ok_or_else(|| TaskFailure::new("invalid_response", "Project ID is unavailable"))?;
110        let owner = ["project_access", "group_access"].iter().any(|key| {
111            project["permissions"][key]["access_level"]
112                .as_u64()
113                .is_some_and(|level| level >= 50)
114        });
115        if owner {
116            return Ok(id);
117        }
118        let repository = json!(binding.repository);
119        let query = format!(
120            "{{ project(fullPath: {repository}) {{ userPermissions {{ adminAllResources }} }} }}"
121        );
122        let response = self.request(
123            binding,
124            "POST",
125            "graphql".into(),
126            &[("query", query)],
127            cancel,
128        )?;
129        if response["data"]["project"]["userPermissions"]["adminAllResources"].as_bool()
130            == Some(true)
131        {
132            Ok(id)
133        } else {
134            Err(TaskFailure::new(
135                "permission",
136                "The authenticated account cannot create a project runner",
137            ))
138        }
139    }
140
141    /// Create a project runner through glab. The one-time token is only returned to the caller.
142    pub fn create_project_runner(
143        &self,
144        binding: &Binding,
145        description: &str,
146        cancel: &AtomicBool,
147    ) -> Result<CreatedProjectRunner, TaskFailure> {
148        let name = description.trim();
149        if name.is_empty() || name.len() > 255 || name.chars().any(char::is_control) {
150            return Err(TaskFailure::new(
151                "invalid_input",
152                "Enter a valid runner name",
153            ));
154        }
155        let project_id = self.runner_creation_project(binding, cancel)?;
156        let result = self.request(
157            binding,
158            "POST",
159            "user/runners".into(),
160            &[
161                ("runner_type", "project_type".into()),
162                ("project_id", project_id.to_string()),
163                ("description", name.into()),
164            ],
165            cancel,
166        )?;
167        let (Some(id), Some(token)) = (
168            result["id"].as_u64().filter(|id| *id > 0),
169            optional_string(&result, "token"),
170        ) else {
171            return Err(TaskFailure::new("invalid_response", "The runner creation response could not be confirmed. Refresh the list before trying again."));
172        };
173        Ok(CreatedProjectRunner { id, token })
174    }
175}