Skip to main content

agent_hub_runtime/core/task_browser/
runners.rs

1use super::{adapter::string, Binding, CliReader, Provider, TaskClient, TaskFailure};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::{collections::HashMap, sync::atomic::AtomicBool};
5
6const PAGE_SIZE: usize = 100;
7const MAX_PAGES: usize = 20;
8const RUNNER_PERMISSIONS: &str = "userPermissions { updateRunner deleteRunner }";
9
10#[derive(Debug, Serialize)]
11pub struct RunnerSummary {
12    pub id: u64,
13    pub short_id: Option<String>,
14    pub web_url: Option<String>,
15    pub name: String,
16    pub state: String,
17    pub paused: Option<bool>,
18    pub busy: Option<bool>,
19    pub job_status: Option<String>,
20    pub os: Option<String>,
21    pub scope: Option<&'static str>,
22    pub labels: Option<Vec<String>>,
23    pub contacted_at: Option<String>,
24    pub created_by: Option<String>,
25    pub created_at: Option<String>,
26    pub version: Option<String>,
27    pub manager_address: Option<String>,
28    pub owner_project: Option<String>,
29    pub project_count: Option<u64>,
30    pub job_count: Option<u64>,
31    pub locked: Option<bool>,
32    pub description: Option<String>,
33    pub run_untagged: Option<bool>,
34    pub protected: Option<bool>,
35    pub can_update: bool,
36    pub can_delete: bool,
37}
38
39#[derive(Clone, Copy, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum RunnerAction {
42    Pause,
43    Resume,
44    Delete,
45}
46
47#[derive(Deserialize)]
48pub struct RunnerEdit {
49    pub description: Option<String>,
50    pub labels: Option<Vec<String>>,
51    pub run_untagged: Option<bool>,
52    pub locked: Option<bool>,
53    pub protected: Option<bool>,
54}
55
56impl RunnerEdit {
57    fn fields(&self) -> Result<Vec<String>, TaskFailure> {
58        let mut fields = Vec::new();
59        if let Some(description) = &self.description {
60            if description.chars().count() > 255 || description.chars().any(char::is_control) {
61                return Err(TaskFailure::new(
62                    "invalid_input",
63                    "Invalid runner description",
64                ));
65            }
66            fields.push(format!("description: {}", serde_json::json!(description)));
67        }
68        if let Some(labels) = &self.labels {
69            if labels
70                .iter()
71                .any(|label| label.trim().is_empty() || label.chars().any(char::is_control))
72            {
73                return Err(TaskFailure::new("invalid_input", "Invalid runner label"));
74            }
75            fields.push(format!("tagList: {}", serde_json::json!(labels)));
76        }
77        if let Some(run_untagged) = self.run_untagged {
78            fields.push(format!("runUntagged: {run_untagged}"));
79        }
80        if let Some(locked) = self.locked {
81            fields.push(format!("locked: {locked}"));
82        }
83        if let Some(protected) = self.protected {
84            let level = if protected {
85                "REF_PROTECTED"
86            } else {
87                "NOT_PROTECTED"
88            };
89            fields.push(format!("accessLevel: {level}"));
90        }
91        Ok(fields)
92    }
93}
94
95#[derive(Debug, Serialize)]
96pub struct RunnerInventory {
97    pub items: Vec<RunnerSummary>,
98    pub identity: String,
99    pub limited: bool,
100    pub assignable: Option<Vec<RunnerSummary>>,
101    pub can_create_runner: bool,
102}
103
104pub(super) fn optional_string(item: &Value, field: &str) -> Option<String> {
105    item[field]
106        .as_str()
107        .filter(|value| !value.is_empty())
108        .map(str::to_owned)
109}
110
111#[derive(Default)]
112struct GitLabRunnerFields {
113    short_id: Option<String>,
114    web_url: Option<String>,
115    os: Option<String>,
116    labels: Option<Vec<String>>,
117    contacted_at: Option<String>,
118    created_by: Option<String>,
119    created_at: Option<String>,
120    version: Option<String>,
121    manager_address: Option<String>,
122    owner_project: Option<String>,
123    project_count: Option<u64>,
124    locked: Option<bool>,
125    can_update: bool,
126    can_delete: bool,
127}
128
129pub(super) fn runner_os(value: String) -> String {
130    match value.to_ascii_lowercase().as_str() {
131        "linux" => "Linux".into(),
132        "darwin" | "macos" | "osx" => "macOS".into(),
133        "windows" => "Windows".into(),
134        _ => value,
135    }
136}
137
138pub(super) fn summary(provider: Provider, item: &Value) -> Result<RunnerSummary, TaskFailure> {
139    let id = item["id"]
140        .as_u64()
141        .filter(|number| *number > 0)
142        .ok_or_else(|| TaskFailure::new("invalid_response", "Runner has no identifier"))?;
143    let gitlab = provider == Provider::Gitlab;
144    let labels = item[if gitlab { "tag_list" } else { "labels" }]
145        .as_array()
146        .map(|values| {
147            values
148                .iter()
149                .filter_map(|value| {
150                    if gitlab {
151                        value.as_str().map(str::to_owned)
152                    } else {
153                        optional_string(value, "name")
154                    }
155                })
156                .collect()
157        });
158    let reported_status = item["status"]
159        .as_str()
160        .filter(|status| !status.trim().is_empty());
161    let state = match reported_status {
162        Some("active" | "paused") | None if gitlab => item["online"]
163            .as_bool()
164            .map(|online| if online { "online" } else { "offline" })
165            .or(reported_status),
166        _ => reported_status,
167    }
168    .unwrap_or("unknown")
169    .to_owned();
170    Ok(RunnerSummary {
171        id,
172        short_id: None,
173        web_url: None,
174        name: optional_string(item, if gitlab { "description" } else { "name" })
175            .or_else(|| optional_string(item, "name"))
176            .unwrap_or_else(|| format!("#{id}")),
177        state,
178        paused: if gitlab {
179            item["paused"]
180                .as_bool()
181                .or_else(|| item["active"].as_bool().map(|active| !active))
182        } else {
183            None
184        },
185        busy: if gitlab {
186            match item["job_execution_status"].as_str() {
187                Some("active" | "running") => Some(true),
188                Some("idle") => Some(false),
189                _ => None,
190            }
191        } else {
192            item["busy"].as_bool()
193        },
194        job_status: optional_string(item, "job_execution_status"),
195        os: optional_string(item, if gitlab { "platform" } else { "os" }).map(runner_os),
196        scope: if gitlab {
197            match string(item, "runner_type").as_str() {
198                "project_type" => Some("project"),
199                "group_type" => Some("group"),
200                "instance_type" => Some("instance"),
201                _ => None,
202            }
203        } else {
204            None
205        },
206        labels,
207        contacted_at: optional_string(item, "contacted_at"),
208        created_by: None,
209        created_at: optional_string(item, "created_at"),
210        version: optional_string(item, "version"),
211        manager_address: None,
212        owner_project: None,
213        project_count: None,
214        job_count: None,
215        locked: item["locked"].as_bool(),
216        description: item["description"].as_str().map(str::to_owned),
217        run_untagged: item["run_untagged"].as_bool(),
218        protected: match item["access_level"].as_str() {
219            Some("ref_protected") => Some(true),
220            Some("not_protected") => Some(false),
221            _ => None,
222        },
223        can_update: false,
224        can_delete: false,
225    })
226}
227
228impl<R: CliReader> TaskClient<R> {
229    /// Read runners visible to the bound repository through the same CLI account as tasks.
230    pub fn runners(
231        &self,
232        binding: &Binding,
233        cancel: &AtomicBool,
234    ) -> Result<RunnerInventory, TaskFailure> {
235        binding.validate()?;
236        let mut items = Vec::new();
237        let mut limited = true;
238        for page in 1..=MAX_PAGES {
239            let (values, more) = self.runner_page(binding, page, cancel)?;
240            for item in &values {
241                items.push(summary(binding.provider, item)?);
242            }
243            if !more {
244                limited = false;
245                break;
246            }
247        }
248        if binding.provider == Provider::Gitlab && !items.is_empty() {
249            let mut fields = self.gitlab_runner_fields(binding, cancel);
250            for runner in &mut items {
251                if let Some(fields) = fields.remove(&runner.id) {
252                    runner.short_id = fields.short_id;
253                    runner.web_url = fields.web_url;
254                    runner.os = runner.os.take().or(fields.os);
255                    runner.labels = runner.labels.take().or(fields.labels);
256                    runner.contacted_at = runner.contacted_at.take().or(fields.contacted_at);
257                    runner.created_by = fields.created_by;
258                    runner.created_at = runner.created_at.take().or(fields.created_at);
259                    runner.version = fields.version.or(runner.version.take());
260                    runner.manager_address = fields.manager_address;
261                    runner.owner_project = fields.owner_project;
262                    runner.project_count = fields.project_count;
263                    runner.locked = fields.locked.or(runner.locked);
264                    runner.can_update = fields.can_update;
265                    runner.can_delete = fields.can_delete;
266                }
267            }
268        }
269        let (assignable, can_create_runner) = if binding.provider == Provider::Gitlab {
270            (
271                self.assignable_runners(binding, cancel).ok(),
272                self.runner_creation_project(binding, cancel).is_ok(),
273            )
274        } else {
275            (None, false)
276        };
277        Ok(RunnerInventory {
278            items,
279            identity: String::new(),
280            limited,
281            assignable,
282            can_create_runner,
283        })
284    }
285
286    // GitLab exposes its UI's short identifier in GraphQL. The REST inventory
287    // remains usable when a self-managed server does not expose that field.
288    fn gitlab_runner_fields(
289        &self,
290        binding: &Binding,
291        cancel: &AtomicBool,
292    ) -> HashMap<u64, GitLabRunnerFields> {
293        let mut fields = HashMap::new();
294        let mut after = Value::Null;
295        let repository = Value::String(binding.repository.clone());
296        let runner_fields = format!("id shortSha tagList contactedAt createdAt createdBy {{ name }} locked ownerProject {{ fullPath }} projectCount {RUNNER_PERMISSIONS} managers(first: 2) {{ nodes {{ platformName version ipAddress }} }}");
297        let mut edges = true;
298        for _ in 0..MAX_PAGES {
299            let read = |edges: bool| {
300                let selection = if edges {
301                    format!("edges {{ webUrl node {{ {runner_fields} }} }}")
302                } else {
303                    format!("nodes {{ {runner_fields} }}")
304                };
305                let query = format!("{{ project(fullPath: {repository}) {{ runners(first: {PAGE_SIZE}, after: {after}) {{ {selection} pageInfo {{ hasNextPage endCursor }} }} }} }}");
306                self.request(
307                    binding,
308                    "POST",
309                    "graphql".into(),
310                    &[("query", query)],
311                    cancel,
312                )
313            };
314            let response = read(edges).or_else(|error| {
315                if edges
316                    && after.is_null()
317                    && (error.kind == "network" || error.kind == "invalid_response")
318                {
319                    edges = false;
320                    read(false)
321                } else {
322                    Err(error)
323                }
324            });
325            let Ok(response) = response else { break };
326            let connection = &response["data"]["project"]["runners"];
327            let Some(nodes) = connection["edges"]
328                .as_array()
329                .or_else(|| connection["nodes"].as_array())
330            else {
331                break;
332            };
333            for entry in nodes {
334                let node = entry.get("node").unwrap_or(entry);
335                let id = node["id"].as_str().and_then(|id| {
336                    id.strip_prefix("gid://gitlab/Ci::Runner/")?
337                        .parse::<u64>()
338                        .ok()
339                });
340                let short_id = node["shortSha"].as_str().filter(|short_id| {
341                    short_id.len() == 8
342                        && short_id
343                            .bytes()
344                            .all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
345                });
346                let manager = match node["managers"]["nodes"].as_array().map(Vec::as_slice) {
347                    Some([manager]) => manager,
348                    _ => &Value::Null,
349                };
350                if let Some(id) = id {
351                    fields.insert(
352                        id,
353                        GitLabRunnerFields {
354                            short_id: short_id.map(str::to_owned),
355                            web_url: optional_string(entry, "webUrl"),
356                            os: optional_string(manager, "platformName").map(runner_os),
357                            labels: node["tagList"].as_array().map(|labels| {
358                                labels
359                                    .iter()
360                                    .filter_map(|label| label.as_str().map(str::to_owned))
361                                    .collect()
362                            }),
363                            contacted_at: optional_string(node, "contactedAt"),
364                            created_by: optional_string(&node["createdBy"], "name"),
365                            created_at: optional_string(node, "createdAt"),
366                            version: optional_string(manager, "version"),
367                            manager_address: optional_string(manager, "ipAddress"),
368                            owner_project: optional_string(&node["ownerProject"], "fullPath"),
369                            project_count: node["projectCount"].as_u64(),
370                            locked: node["locked"].as_bool(),
371                            can_update: node["userPermissions"]["updateRunner"].as_bool()
372                                == Some(true),
373                            can_delete: node["userPermissions"]["deleteRunner"].as_bool()
374                                == Some(true),
375                        },
376                    );
377                }
378            }
379            let next = &connection["pageInfo"]["endCursor"];
380            if connection["pageInfo"]["hasNextPage"].as_bool() != Some(true)
381                || !next.is_string()
382                || next == &after
383            {
384                break;
385            }
386            after = next.clone();
387        }
388        fields
389    }
390
391    fn runner_page(
392        &self,
393        binding: &Binding,
394        page: usize,
395        cancel: &AtomicBool,
396    ) -> Result<(Vec<Value>, bool), TaskFailure> {
397        let endpoint = match binding.provider {
398            Provider::Github => format!("repos/{}/actions/runners", binding.repository),
399            Provider::Gitlab => format!(
400                "projects/{}/runners",
401                urlencoding::encode(&binding.repository)
402            ),
403        };
404        let mut response = self.api(
405            binding,
406            format!("{endpoint}?per_page={PAGE_SIZE}&page={page}"),
407            cancel,
408        )?;
409        let more = match binding.provider {
410            Provider::Github => response["total_count"]
411                .as_u64()
412                .is_some_and(|total| total > (page * PAGE_SIZE) as u64),
413            Provider::Gitlab => response
414                .as_array()
415                .is_some_and(|values| values.len() == PAGE_SIZE),
416        };
417
418        let values = match binding.provider {
419            Provider::Github => response["runners"].as_array_mut(),
420            Provider::Gitlab => response.as_array_mut(),
421        }
422        .ok_or_else(|| TaskFailure::new("invalid_response", "Invalid runner list response"))?;
423        let more = more && !values.is_empty();
424        Ok((std::mem::take(values), more))
425    }
426
427    /// Read GitLab's optional fields for a runner visible through the repository binding.
428    pub fn runner_details(
429        &self,
430        binding: &Binding,
431        id: u64,
432        cancel: &AtomicBool,
433    ) -> Result<RunnerSummary, TaskFailure> {
434        self.require_project_runner(binding, id, cancel)?;
435        let item = self.api(binding, format!("runners/{id}"), cancel)?;
436        let mut details = summary(binding.provider, &item)?;
437        if details.id != id {
438            return Err(TaskFailure::new(
439                "invalid_response",
440                "Runner identity mismatch",
441            ));
442        }
443        let fields = format!("{RUNNER_PERMISSIONS} jobs(first: 1) {{ count }}");
444        if let Ok(runner) = self
445            .gitlab_runner_info(binding, id, &fields, cancel)
446            .or_else(|_| self.gitlab_runner_info(binding, id, RUNNER_PERMISSIONS, cancel))
447        {
448            details.can_update = runner["userPermissions"]["updateRunner"].as_bool() == Some(true);
449            details.can_delete = runner["userPermissions"]["deleteRunner"].as_bool() == Some(true);
450            details.job_count = runner["jobs"]["count"].as_u64();
451        }
452        Ok(details)
453    }
454
455    /// Manage a GitLab runner through the authenticated glab connection.
456    pub fn manage_runner(
457        &self,
458        binding: &Binding,
459        id: u64,
460        action: RunnerAction,
461        cancel: &AtomicBool,
462    ) -> Result<(), TaskFailure> {
463        let permissions = self.runner_permissions(binding, id, cancel)?;
464        let endpoint = format!("runners/{id}");
465        match action {
466            RunnerAction::Delete if permissions["deleteRunner"].as_bool() == Some(true) => {
467                self.request(binding, "DELETE", endpoint, &[], cancel)?;
468                Ok(())
469            }
470            RunnerAction::Pause | RunnerAction::Resume
471                if permissions["updateRunner"].as_bool() == Some(true) =>
472            {
473                let paused = matches!(action, RunnerAction::Pause);
474                let response = self.request(
475                    binding,
476                    "PUT",
477                    endpoint,
478                    &[("paused", paused.to_string())],
479                    cancel,
480                )?;
481                if response["id"].as_u64() != Some(id)
482                    || response["paused"].as_bool() != Some(paused)
483                {
484                    return Err(TaskFailure::new(
485                        "invalid_response",
486                        "Could not verify the runner's pause status",
487                    ));
488                }
489                Ok(())
490            }
491            _ => Err(TaskFailure::new(
492                "permission",
493                "The authenticated account cannot perform this runner action",
494            )),
495        }
496    }
497
498    /// Edit only the supplied fields through GitLab's official runner mutation.
499    pub fn edit_runner(
500        &self,
501        binding: &Binding,
502        id: u64,
503        edit: &RunnerEdit,
504        cancel: &AtomicBool,
505    ) -> Result<(), TaskFailure> {
506        let fields = edit.fields()?;
507        if fields.is_empty() {
508            return Err(TaskFailure::new(
509                "invalid_input",
510                "No runner changes supplied",
511            ));
512        }
513        if self.runner_permissions(binding, id, cancel)?["updateRunner"].as_bool() != Some(true) {
514            return Err(TaskFailure::new(
515                "permission",
516                "The authenticated account cannot edit this runner",
517            ));
518        }
519        let runner_id = format!("gid://gitlab/Ci::Runner/{id}");
520        let fields = fields.join(", ");
521        let query = format!(
522            r#"mutation {{ runnerUpdate(input: {{ id: "{runner_id}", {fields} }}) {{ errors runner {{ id }} }} }}"#
523        );
524        let data = self.request(
525            binding,
526            "POST",
527            "graphql".into(),
528            &[("query", query)],
529            cancel,
530        )?;
531        let result = &data["data"]["runnerUpdate"];
532        if let Some(error) = result["errors"]
533            .as_array()
534            .and_then(|errors| errors.first())
535            .and_then(Value::as_str)
536        {
537            return Err(TaskFailure::new("invalid_input", error));
538        }
539        if result["runner"]["id"].as_str() != Some(runner_id.as_str()) {
540            return Err(TaskFailure::new(
541                "invalid_response",
542                "Could not verify the edited runner",
543            ));
544        }
545        Ok(())
546    }
547
548    fn runner_permissions(
549        &self,
550        binding: &Binding,
551        id: u64,
552        cancel: &AtomicBool,
553    ) -> Result<Value, TaskFailure> {
554        self.require_project_runner(binding, id, cancel)?;
555        self.gitlab_runner_info(binding, id, RUNNER_PERMISSIONS, cancel)
556            .map(|mut runner| runner["userPermissions"].take())
557    }
558
559    fn gitlab_runner_info(
560        &self,
561        binding: &Binding,
562        id: u64,
563        fields: &str,
564        cancel: &AtomicBool,
565    ) -> Result<Value, TaskFailure> {
566        let query = format!(r#"{{ runner(id: "gid://gitlab/Ci::Runner/{id}") {{ {fields} }} }}"#);
567        self.request(
568            binding,
569            "POST",
570            "graphql".into(),
571            &[("query", query)],
572            cancel,
573        )
574        .map(|mut response| response["data"]["runner"].take())
575    }
576
577    fn require_project_runner(
578        &self,
579        binding: &Binding,
580        id: u64,
581        cancel: &AtomicBool,
582    ) -> Result<(), TaskFailure> {
583        if binding.provider != Provider::Gitlab || id == 0 {
584            return Err(TaskFailure::new("invalid_input", "Invalid GitLab runner"));
585        }
586        binding.validate()?;
587        for page in 1..=MAX_PAGES {
588            let (values, more) = self.runner_page(binding, page, cancel)?;
589            if values.iter().any(|value| value["id"].as_u64() == Some(id)) {
590                return Ok(());
591            }
592            if !more {
593                break;
594            }
595        }
596        Err(TaskFailure::new(
597            "permission",
598            "Runner is not visible to the repository",
599        ))
600    }
601}