Skip to main content

runnerd_core/
github.rs

1//! The GitHub REST API as the scheduler and the history need it: queued jobs, a job's steps, just-in-time runner
2//! configs, repository runners and cancelling a run. Owns the token, the pages of a listing, conditional requests and
3//! the answers kept for them, and rate-limit backoff. It must never put the token in a log line, a `Debug` output or
4//! an error, nor send it anywhere but its base URL, and it decides nothing about scheduling.
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant, SystemTime};
10
11use reqwest::header::{self, HeaderMap, HeaderValue};
12use reqwest::{Method, StatusCode};
13use serde::Deserialize;
14use serde::de::DeserializeOwned;
15
16use crate::api;
17use crate::docker::JitConfig;
18use crate::sync::lock;
19use crate::time;
20
21/// The public API's address.
22pub const API_URL: &str = "https://api.github.com";
23
24/// How long one request may take, connecting included. GitHub answers in well under a second; a request that hangs
25/// holds back the tick that made it.
26const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
27
28/// Items per page of a listing: GitHub's most.
29const PER_PAGE: u32 = 100;
30
31/// The most pages read of one listing: 1,000 runs, jobs of a run or runners, more than one machine serves at once
32/// and four times a matrix's 256 jobs. A listing that names a page past it is cut there, so a `Link` that never ends
33/// costs ten requests, not the rate limit.
34const MAX_PAGES: u32 = 10;
35
36/// How many requests for runs' jobs one poll of a repository starts: as many runs as a poll read before it followed
37/// pages, 100 queued and 100 in progress. A run whose first page is read is read to its last, so none of its queued
38/// jobs drops out of the listing for want of a page, and the listings of runs, however many pages they grow to, do
39/// not move where a poll stops. A repository with more active runs leaves the rest unread until earlier ones end,
40/// so following pages does not spend the rate limit faster than before.
41const JOB_REQUESTS: usize = 200;
42
43/// The most bytes of answers kept for conditional requests. A page of 100 runs is about 600 KB, a page of jobs with
44/// their steps about 350 KB, a job's details a few KB: room for what several busy repositories ask every poll.
45const CONDITIONAL_BYTES: usize = 32 * 1024 * 1024;
46
47/// An answer asked for within this long is not dropped to make room for another. Every poll asks the same paths in
48/// the same order; were the least recently used answer dropped, a poll that asks more than the limit holds would
49/// find each answer dropped just before asking for it again and pay for every request. Kept like this, the answers
50/// that fit stay conditional and only the rest cost the rate limit. It is far longer than a poll interval (15 s by
51/// default); polls further apart than this are rare enough that what they pay matters little.
52const CONDITIONAL_FRESH: Duration = Duration::from_secs(600);
53
54/// A GitHub token. Its `Debug` output never shows the value.
55#[derive(Clone)]
56pub struct Token(String);
57
58impl fmt::Debug for Token {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str("Token(<redacted>)")
61    }
62}
63
64/// Where the client gets a token: at start and again when GitHub answers 401.
65pub type TokenSource = Box<dyn Fn() -> Result<Token, Error> + Send + Sync>;
66
67/// The `gh` CLI's token for github.com (`gh auth token`).
68pub fn gh_token() -> Result<Token, Error> {
69    let output = std::process::Command::new("gh")
70        .args(["auth", "token", "--hostname", "github.com"])
71        .output()
72        .map_err(|error| Error::Token(format!("cannot run gh: {error}")))?;
73    if !output.status.success() {
74        return Err(Error::Token(format!(
75            "gh auth token failed: {}",
76            String::from_utf8_lossy(&output.stderr).trim()
77        )));
78    }
79    let token = String::from_utf8(output.stdout)
80        .map_err(|_| Error::Token("gh auth token printed a token that is not UTF-8".to_owned()))?;
81    Ok(Token(token.trim().to_owned()))
82}
83
84/// Makes ring the process's TLS crypto provider, which every `reqwest::Client` needs: reqwest is built without
85/// one. Calling it again does nothing.
86pub fn install_crypto_provider() {
87    // Fails only when a provider is installed already.
88    let _ = rustls::crypto::ring::default_provider().install_default();
89}
90
91/// What a GitHub request can fail with. No variant holds the token.
92#[derive(Debug, thiserror::Error)]
93pub enum Error {
94    /// GitHub's rate limit is used up; no request is sent before `until`.
95    #[error("GitHub's rate limit is used up until {}s after the epoch", secs(*until))]
96    RateLimited {
97        /// When the limit resets.
98        until: SystemTime,
99    },
100    /// GitHub answered with an error status.
101    #[error("GitHub answered {status} to {method} {path}: {message}")]
102    Status {
103        /// The request's method.
104        method: Method,
105        /// The request's path, without the host.
106        path: String,
107        /// What GitHub answered.
108        status: StatusCode,
109        /// GitHub's error message, or the body as text.
110        message: String,
111    },
112    /// The request did not get an answer.
113    #[error("{method} {path}: {source}")]
114    Http {
115        /// The request's method.
116        method: Method,
117        /// The request's path, without the host.
118        path: String,
119        /// What failed, without the URL.
120        source: reqwest::Error,
121    },
122    /// The answer is not the JSON expected.
123    #[error("{path}: unexpected response: {source}")]
124    Decode {
125        /// The request's path, without the host.
126        path: String,
127        /// What did not parse.
128        source: serde_json::Error,
129    },
130    /// No token could be read.
131    #[error("no GitHub token: {0}")]
132    Token(String),
133}
134
135fn secs(time: SystemTime) -> u64 {
136    time.duration_since(SystemTime::UNIX_EPOCH)
137        .unwrap_or_default()
138        .as_secs()
139}
140
141/// A job waiting for a runner.
142#[derive(Debug, Clone, Default, PartialEq, Eq)]
143pub struct QueuedJob {
144    /// The job's ID; IDs grow with time.
145    pub id: u64,
146    /// The workflow run it belongs to.
147    pub run_id: u64,
148    /// The job's name in the workflow.
149    pub name: String,
150    /// The workflow's `runs-on` labels.
151    pub labels: Vec<String>,
152    /// When GitHub queued it, in milliseconds since the epoch; 0 if GitHub's answer did not say.
153    pub created_at: u64,
154    /// 1 for the run's first attempt.
155    pub run_attempt: u32,
156    /// The workflow's name.
157    pub workflow: Option<String>,
158    /// The branch the run is for.
159    pub branch: Option<String>,
160    /// The job's page on GitHub.
161    pub url: Option<String>,
162}
163
164/// A job as `GET /repos/{owner}/{repo}/actions/jobs/{id}` describes it: its progress and steps.
165#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
166pub struct JobDetails {
167    /// The job's ID.
168    pub id: u64,
169    /// The workflow run it belongs to.
170    pub run_id: u64,
171    /// 1 for the run's first attempt.
172    #[serde(default = "first_attempt")]
173    pub run_attempt: u32,
174    /// The job's name in the workflow.
175    pub name: String,
176    /// The workflow's name.
177    pub workflow_name: Option<String>,
178    /// The branch the run is for.
179    pub head_branch: Option<String>,
180    /// The job's page on GitHub.
181    pub html_url: Option<String>,
182    /// The workflow's `runs-on` labels.
183    #[serde(default)]
184    pub labels: Vec<String>,
185    /// When GitHub queued it.
186    pub created_at: Option<String>,
187    /// `queued`, `in_progress`, `completed`, `waiting`, ….
188    pub status: String,
189    /// Once completed: `success`, `failure`, `cancelled`, ….
190    pub conclusion: Option<String>,
191    /// When the runner started it.
192    pub started_at: Option<String>,
193    /// When it completed.
194    pub completed_at: Option<String>,
195    /// The runner that took it, if one did.
196    pub runner_name: Option<String>,
197    /// Its steps so far.
198    #[serde(default)]
199    pub steps: Vec<JobStep>,
200}
201
202/// What started a workflow run, as `GET /repos/{owner}/{repo}/actions/runs/{id}` says.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct RunTrigger {
205    /// `push`, `pull_request`, `schedule`, `workflow_dispatch`, ….
206    pub event: String,
207    /// The branch it ran on: a pull request's head branch, which may be a fork's.
208    pub head_branch: Option<String>,
209    /// `owner/name` of the repository its commit came from: a fork's, for a pull request from one.
210    pub head_repository: Option<String>,
211    /// The commit it ran. A tag's run gives the tag's name as `head_branch`, so only this says whether the
212    /// branch has it.
213    pub head_sha: String,
214    /// Whether people, not bots or apps, started it: GitHub's `actor` and `triggering_actor`, who re-ran it, are
215    /// both of type `User`.
216    pub by_user: bool,
217    /// The pull requests into the repository it runs, by number. GitHub lists only those whose head branch is in
218    /// the repository itself, and may list none once they are closed; those it lists into another repository of a
219    /// fork network are left out.
220    pub pull_requests: Vec<u64>,
221}
222
223/// A pull request, as `GET /repos/{owner}/{repo}/pulls/{number}` says.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct PullRequest {
226    /// Whether a person, not a bot or an app, opened it: its `user` is of type `User`.
227    pub by_user: bool,
228    /// `owner/name` of the repository its head branch is in; `None` once that is deleted.
229    pub head_repository: Option<String>,
230    /// Its head branch.
231    pub head_branch: String,
232}
233
234/// A repository, as `GET /repos/{owner}/{repo}` says.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct RepositoryDetails {
237    /// Its default branch.
238    pub default_branch: String,
239    /// Whether it is public, private or internal.
240    pub visibility: api::Visibility,
241}
242
243fn first_attempt() -> u32 {
244    1
245}
246
247/// A step of `JobDetails`.
248#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
249pub struct JobStep {
250    /// GitHub's step number.
251    pub number: u32,
252    /// The name GitHub shows.
253    pub name: String,
254    /// `pending`, `queued`, `in_progress` or `completed`.
255    pub status: String,
256    /// Once completed: `success`, `failure`, `skipped`, ….
257    pub conclusion: Option<String>,
258    /// When it started.
259    pub started_at: Option<String>,
260    /// When it completed.
261    pub completed_at: Option<String>,
262}
263
264/// A runner registered on a repository.
265#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
266pub struct Runner {
267    /// The runner's ID.
268    pub id: u64,
269    /// Its name; runnerd's runners start with the host's prefix.
270    pub name: String,
271    /// `online` or `offline`.
272    pub status: String,
273    /// Whether it runs a job.
274    pub busy: bool,
275}
276
277/// What deleting a runner did.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum Deleted {
280    /// GitHub removed it.
281    Deleted,
282    /// It was gone already: an ephemeral runner removes itself after its job.
283    NotFound,
284    /// GitHub refused because the runner runs a job.
285    Busy,
286}
287
288/// The GitHub calls the scheduler makes. `Github` is the real client; the engine's tests use a fake.
289pub trait GithubApi: Send + Sync {
290    /// The repository's jobs waiting for a runner, in queued runs and in runs that started some of their jobs.
291    fn queued_jobs(
292        &self,
293        repository: &str,
294    ) -> impl Future<Output = Result<Vec<QueuedJob>, Error>> + Send;
295    /// The repository's self-hosted runners.
296    fn runners(&self, repository: &str) -> impl Future<Output = Result<Vec<Runner>, Error>> + Send;
297    /// Registers a runner for one job and returns it with the config the runner's listener takes.
298    fn jit_config(
299        &self,
300        repository: &str,
301        name: &str,
302        labels: &[String],
303    ) -> impl Future<Output = Result<(Runner, JitConfig), Error>> + Send;
304    /// Removes a runner from the repository.
305    fn delete_runner(
306        &self,
307        repository: &str,
308        id: u64,
309    ) -> impl Future<Output = Result<Deleted, Error>> + Send;
310    /// One job's progress and steps.
311    fn job(
312        &self,
313        repository: &str,
314        id: u64,
315    ) -> impl Future<Output = Result<JobDetails, Error>> + Send;
316    /// What started a workflow run.
317    fn run_trigger(
318        &self,
319        repository: &str,
320        run: u64,
321    ) -> impl Future<Output = Result<RunTrigger, Error>> + Send;
322    /// One pull request: who opened it and where its head branch is.
323    fn pull_request(
324        &self,
325        repository: &str,
326        number: u64,
327    ) -> impl Future<Output = Result<PullRequest, Error>> + Send;
328    /// The repository's default branch and visibility.
329    fn repository(
330        &self,
331        repository: &str,
332    ) -> impl Future<Output = Result<RepositoryDetails, Error>> + Send;
333    /// Whether `branch` of the repository has the commit `sha`: its head or an ancestor of it. A tag of the same
334    /// name, which git would take for it, does not count.
335    fn on_branch(
336        &self,
337        repository: &str,
338        branch: &str,
339        sha: &str,
340    ) -> impl Future<Output = Result<bool, Error>> + Send;
341    /// Cancels a workflow run, and so every job in it: GitHub cancels runs, not single jobs. A run that already
342    /// completed is left as it is.
343    fn cancel_run(
344        &self,
345        repository: &str,
346        run: u64,
347    ) -> impl Future<Output = Result<(), Error>> + Send;
348}
349
350/// A GitHub API client for one token. Requests on one URL are conditional on its last `ETag`, so an unchanged
351/// answer costs no rate limit.
352pub struct Github {
353    http: reqwest::Client,
354    base: String,
355    /// Run on Tokio's blocking pool: `gh` may wait on a keyring for seconds.
356    token_source: Arc<dyn Fn() -> Result<Token, Error> + Send + Sync>,
357    /// An async lock, held while the source runs: requests that need a token wait without blocking a worker, and
358    /// concurrent 401s read it once.
359    token: tokio::sync::Mutex<Option<Token>>,
360    // Locked with `sync::lock`: a panic while holding one of these locks leaves plain data behind, still usable.
361    etags: Mutex<Conditional>,
362    blocked_until: Mutex<Option<SystemTime>>,
363}
364
365impl fmt::Debug for Github {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        f.debug_struct("Github")
368            .field("base", &self.base)
369            .finish_non_exhaustive()
370    }
371}
372
373#[derive(Deserialize)]
374struct Runs {
375    workflow_runs: Vec<Run>,
376}
377
378#[derive(Deserialize)]
379struct Run {
380    id: u64,
381}
382
383/// Which listing of runs a run is in; queued ones order first.
384#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
385enum RunState {
386    Waiting,
387    Started,
388}
389
390#[derive(Deserialize)]
391struct Jobs {
392    jobs: Vec<Job>,
393}
394
395#[derive(Deserialize)]
396struct Job {
397    id: u64,
398    run_id: u64,
399    name: String,
400    status: String,
401    labels: Vec<String>,
402    created_at: Option<String>,
403    run_attempt: Option<u32>,
404    workflow_name: Option<String>,
405    head_branch: Option<String>,
406    html_url: Option<String>,
407}
408
409#[derive(Deserialize)]
410struct RunBody {
411    event: String,
412    head_branch: Option<String>,
413    head_repository: Option<RepositoryName>,
414    head_sha: String,
415    actor: Option<Account>,
416    triggering_actor: Option<Account>,
417    #[serde(default)]
418    pull_requests: Vec<PullRequestNumber>,
419}
420
421#[derive(Deserialize)]
422struct Account {
423    #[serde(rename = "type")]
424    kind: String,
425}
426
427impl Account {
428    /// Whether GitHub says `account` is a person's: `Bot` is a GitHub App's or a bot's.
429    fn is_user(account: Option<&Account>) -> bool {
430        account.is_some_and(|account| account.kind == "User")
431    }
432}
433
434#[derive(Deserialize)]
435struct PullRequestNumber {
436    number: u64,
437    base: Option<PullRequestBase>,
438}
439
440#[derive(Deserialize)]
441struct PullRequestBase {
442    repo: Option<RepositoryUrl>,
443}
444
445#[derive(Deserialize)]
446struct RepositoryUrl {
447    url: String,
448}
449
450impl PullRequestNumber {
451    /// Whether it is a pull request into `repository`: in a fork network, a run can also list one into another
452    /// repository whose head is the same branch.
453    fn targets(&self, repository: &str) -> bool {
454        let Some(url) = self
455            .base
456            .as_ref()
457            .and_then(|base| base.repo.as_ref())
458            .map(|repo| repo.url.to_ascii_lowercase())
459        else {
460            return false;
461        };
462        url.ends_with(&format!("/repos/{}", repository.to_ascii_lowercase()))
463    }
464}
465
466#[derive(Deserialize)]
467struct PullRequestBody {
468    user: Option<Account>,
469    head: PullRequestHead,
470}
471
472#[derive(Deserialize)]
473struct PullRequestHead {
474    #[serde(rename = "ref")]
475    branch: String,
476    repo: Option<RepositoryName>,
477}
478
479#[derive(Deserialize)]
480struct RepositoryName {
481    full_name: String,
482}
483
484#[derive(Deserialize)]
485struct CompareBody {
486    status: String,
487}
488
489#[derive(Deserialize)]
490struct BranchBody {
491    commit: CommitBody,
492}
493
494#[derive(Deserialize)]
495struct CommitBody {
496    sha: String,
497}
498
499#[derive(Deserialize)]
500struct RepositoryBody {
501    default_branch: String,
502    visibility: api::Visibility,
503}
504
505#[derive(Deserialize)]
506struct Runners {
507    runners: Vec<Runner>,
508}
509
510#[derive(Deserialize)]
511struct JitResponse {
512    runner: Runner,
513    encoded_jit_config: String,
514}
515
516#[derive(Deserialize)]
517struct ErrorBody {
518    message: String,
519}
520
521impl Github {
522    /// A client for `base` (`API_URL`, or a test server) that takes its token from `token_source`.
523    pub fn new(base: &str, token_source: TokenSource) -> Result<Github, Error> {
524        install_crypto_provider();
525        let mut headers = HeaderMap::new();
526        headers.insert(
527            header::ACCEPT,
528            HeaderValue::from_static("application/vnd.github+json"),
529        );
530        headers.insert(
531            "x-github-api-version",
532            HeaderValue::from_static("2022-11-28"),
533        );
534        let http = reqwest::Client::builder()
535            .user_agent(concat!("runnerd/", env!("CARGO_PKG_VERSION")))
536            .default_headers(headers)
537            .timeout(REQUEST_TIMEOUT)
538            .build()
539            .map_err(|source| Error::Http {
540                method: Method::GET,
541                path: base.to_owned(),
542                source,
543            })?;
544        Ok(Github {
545            http,
546            base: base.trim_end_matches('/').to_owned(),
547            token_source: Arc::from(token_source),
548            token: tokio::sync::Mutex::new(None),
549            etags: Mutex::new(Conditional::new(CONDITIONAL_BYTES, CONDITIONAL_FRESH)),
550            blocked_until: Mutex::new(None),
551        })
552    }
553
554    /// When the next request may be sent: `None` now, otherwise when the rate limit resets.
555    pub fn blocked_until(&self) -> Option<SystemTime> {
556        let blocked = *lock(&self.blocked_until);
557        blocked.filter(|until| *until > SystemTime::now())
558    }
559
560    async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, Error> {
561        self.get_page(path).await.map(|page| page.body)
562    }
563
564    /// One answer, conditional on the last one kept for `path`, and whether GitHub's `Link` names a next page.
565    async fn get_page<T: DeserializeOwned>(&self, path: &str) -> Result<Page<T>, Error> {
566        // Taken before the request, so an answer evicted meanwhile still serves a 304.
567        let cached = lock(&self.etags).get(path, Instant::now());
568        let etag = cached.as_ref().map(|cached| &cached.etag);
569        let response = self.send(Method::GET, path, None, etag).await?;
570        let (bytes, next) = if response.status == StatusCode::NOT_MODIFIED {
571            match cached {
572                Some(cached) => (cached.body, cached.next),
573                None => {
574                    return Err(Error::Status {
575                        method: Method::GET,
576                        path: path.to_owned(),
577                        status: response.status,
578                        message: "not modified, but nothing is cached".to_owned(),
579                    });
580                }
581            }
582        } else {
583            let etag = response.etag.clone();
584            let response = expect_success(Method::GET, path, response)?;
585            let body: Arc<[u8]> = response.bytes.into();
586            if let Some(etag) = etag {
587                lock(&self.etags).insert(
588                    path,
589                    Cached {
590                        etag,
591                        body: body.clone(),
592                        next: response.next,
593                    },
594                    Instant::now(),
595                );
596            }
597            (body, response.next)
598        };
599        Ok(Page {
600            body: decode(path, &bytes)?,
601            next,
602        })
603    }
604
605    /// The pages of the listing at `path`, a query without `page`, for as long as GitHub's `Link` names a next one,
606    /// at most `MAX_PAGES`. Each page is its own conditional request. The next page's address is built here, not
607    /// taken from the `Link`, so the token goes nowhere but `base`. Items move between pages while they are read: one
608    /// may show twice, which callers dedupe by ID, or not at all until the next poll.
609    async fn get_pages<T: DeserializeOwned>(&self, path: &str) -> Result<Vec<T>, Error> {
610        let mut pages = Vec::new();
611        for page in 1..=MAX_PAGES {
612            let path = if page == 1 {
613                path.to_owned()
614            } else {
615                format!("{path}&page={page}")
616            };
617            let answer: Page<T> = self.get_page(&path).await?;
618            pages.push(answer.body);
619            if !answer.next {
620                break;
621            }
622        }
623        Ok(pages)
624    }
625
626    /// Sends a request with the token, once more with a fresh token after a 401, conditional on `etag` if given.
627    /// Records the rate limit.
628    async fn send(
629        &self,
630        method: Method,
631        path: &str,
632        body: Option<&serde_json::Value>,
633        etag: Option<&HeaderValue>,
634    ) -> Result<Response, Error> {
635        if let Some(until) = self.blocked_until() {
636            return Err(Error::RateLimited { until });
637        }
638        // The token GitHub refused, once it did.
639        let mut refused: Option<Token> = None;
640        loop {
641            let token = self.token(refused.as_ref()).await?;
642            let mut request = self
643                .http
644                .request(method.clone(), format!("{}{path}", self.base))
645                .bearer_auth(&token.0);
646            if let Some(body) = body {
647                request = request
648                    .header(header::CONTENT_TYPE, "application/json")
649                    .body(body.to_string());
650            }
651            if let Some(etag) = etag {
652                request = request.header(header::IF_NONE_MATCH, etag.clone());
653            }
654            let response = request.send().await.map_err(|source| Error::Http {
655                method: method.clone(),
656                path: path.to_owned(),
657                source: source.without_url(),
658            })?;
659            let status = response.status();
660            if status == StatusCode::UNAUTHORIZED && refused.is_none() {
661                refused = Some(token);
662                continue;
663            }
664            if let Some(until) = rate_limited_until(status, response.headers(), SystemTime::now()) {
665                *lock(&self.blocked_until) = Some(until);
666                if matches!(
667                    status,
668                    StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
669                ) {
670                    return Err(Error::RateLimited { until });
671                }
672            }
673            let etag = response.headers().get(header::ETAG).cloned();
674            let next = names_next_page(response.headers());
675            let bytes = response.bytes().await.map_err(|source| Error::Http {
676                method: method.clone(),
677                path: path.to_owned(),
678                source: source.without_url(),
679            })?;
680            return Ok(Response {
681                status,
682                etag,
683                next,
684                bytes: bytes.to_vec(),
685            });
686        }
687    }
688
689    /// The token, read from the source if there is none yet or it is still the one GitHub `refused`: of several
690    /// requests refused at once, the first reads a new one and the others take it.
691    async fn token(&self, refused: Option<&Token>) -> Result<Token, Error> {
692        let mut token = self.token.lock().await;
693        let stale = match (&*token, refused) {
694            (None, _) => true,
695            (Some(current), Some(refused)) => current.0 == refused.0,
696            (Some(_), None) => false,
697        };
698        if stale {
699            let source = self.token_source.clone();
700            *token = Some(
701                tokio::task::spawn_blocking(move || source())
702                    .await
703                    .map_err(|error| {
704                        Error::Token(format!("the token source stopped: {error}"))
705                    })??,
706            );
707        }
708        token
709            .clone()
710            .ok_or_else(|| Error::Token("the token source returned nothing".to_owned()))
711    }
712}
713
714impl GithubApi for Github {
715    async fn queued_jobs(&self, repository: &str) -> Result<Vec<QueuedJob>, Error> {
716        // Each run once, `Started` if GitHub lists it in progress, `Waiting` if queued.
717        let mut runs = Vec::new();
718        for (state, status) in [
719            (RunState::Waiting, "queued"),
720            (RunState::Started, "in_progress"),
721        ] {
722            let pages: Vec<Runs> = self
723                .get_pages(&format!(
724                    "/repos/{repository}/actions/runs?status={status}&per_page={PER_PAGE}"
725                ))
726                .await?;
727            runs.extend(
728                pages
729                    .into_iter()
730                    .flat_map(|page| page.workflow_runs)
731                    .map(|run| (state, run.id)),
732            );
733        }
734        // A run listed under both, which moved while they were read, counts as queued.
735        runs.sort_unstable_by_key(|&(state, id)| (id, state));
736        runs.dedup_by_key(|&mut (_, id)| id);
737        // Queued runs first, whose jobs all wait, then those in progress, which may run on GitHub's own runners;
738        // oldest first within each. Should the requests run out, the runs left unread are the newest.
739        runs.sort_unstable();
740        let listed: HashSet<u64> = runs.iter().map(|&(_, id)| id).collect();
741        let mut jobs = Vec::new();
742        let mut requests = 0;
743        for &(_, run) in &runs {
744            if requests >= JOB_REQUESTS {
745                break;
746            }
747            let pages: Vec<Jobs> = self.get_pages(&jobs_path(repository, run)).await?;
748            requests += pages.len();
749            jobs.extend(
750                pages
751                    .into_iter()
752                    .flat_map(|page| page.jobs)
753                    .filter(|job| job.status == "queued")
754                    .map(|job| QueuedJob {
755                        id: job.id,
756                        run_id: job.run_id,
757                        name: job.name,
758                        labels: job.labels,
759                        created_at: job
760                            .created_at
761                            .as_deref()
762                            .and_then(time::parse_ms)
763                            .unwrap_or(0),
764                        run_attempt: job.run_attempt.unwrap_or(1),
765                        workflow: job.workflow_name,
766                        branch: job.head_branch,
767                        url: job.html_url,
768                    }),
769            );
770        }
771        // The cached pages of runs that ended: nothing asks for them again.
772        let runs_prefix = format!("/repos/{repository}/actions/runs/");
773        lock(&self.etags).retain(|path| {
774            match path
775                .strip_prefix(&runs_prefix)
776                .and_then(|rest| rest.split_once("/jobs?"))
777            {
778                Some((run, _)) => run.parse().is_ok_and(|run: u64| listed.contains(&run)),
779                None => true,
780            }
781        });
782        jobs.sort_by_key(|job| job.id);
783        jobs.dedup_by_key(|job| job.id);
784        Ok(jobs)
785    }
786
787    async fn runners(&self, repository: &str) -> Result<Vec<Runner>, Error> {
788        let pages: Vec<Runners> = self
789            .get_pages(&format!(
790                "/repos/{repository}/actions/runners?per_page={PER_PAGE}"
791            ))
792            .await?;
793        let mut seen = HashSet::new();
794        Ok(pages
795            .into_iter()
796            .flat_map(|page| page.runners)
797            .filter(|runner| seen.insert(runner.id))
798            .collect())
799    }
800
801    async fn jit_config(
802        &self,
803        repository: &str,
804        name: &str,
805        labels: &[String],
806    ) -> Result<(Runner, JitConfig), Error> {
807        let body = serde_json::json!({
808            "name": name,
809            // The repository's default runner group.
810            "runner_group_id": 1,
811            "labels": labels,
812            "work_folder": "_work",
813        });
814        let path = format!("/repos/{repository}/actions/runners/generate-jitconfig");
815        let response = self.send(Method::POST, &path, Some(&body), None).await?;
816        let response = expect_success(Method::POST, &path, response)?;
817        let jit: JitResponse = decode(&path, &response.bytes)?;
818        Ok((jit.runner, JitConfig(jit.encoded_jit_config)))
819    }
820
821    async fn delete_runner(&self, repository: &str, id: u64) -> Result<Deleted, Error> {
822        let path = format!("/repos/{repository}/actions/runners/{id}");
823        let response = self.send(Method::DELETE, &path, None, None).await?;
824        match response.status {
825            StatusCode::NOT_FOUND => Ok(Deleted::NotFound),
826            StatusCode::UNPROCESSABLE_ENTITY => Ok(Deleted::Busy),
827            _ => expect_success(Method::DELETE, &path, response).map(|_| Deleted::Deleted),
828        }
829    }
830
831    async fn job(&self, repository: &str, id: u64) -> Result<JobDetails, Error> {
832        let path = format!("/repos/{repository}/actions/jobs/{id}");
833        let job: JobDetails = self.get(&path).await?;
834        // A completed job does not change again, and the history stops asking for it.
835        if job.status == "completed" {
836            lock(&self.etags).remove(&path);
837        }
838        Ok(job)
839    }
840
841    async fn run_trigger(&self, repository: &str, run: u64) -> Result<RunTrigger, Error> {
842        let path = format!("/repos/{repository}/actions/runs/{run}");
843        let run: Result<RunBody, Error> = self.get(&path).await;
844        // Asked once per job: its large answer is not worth keeping for a conditional request.
845        lock(&self.etags).remove(&path);
846        let run = run?;
847        Ok(RunTrigger {
848            event: run.event,
849            head_branch: run.head_branch,
850            head_repository: run.head_repository.map(|head| head.full_name),
851            head_sha: run.head_sha,
852            by_user: Account::is_user(run.actor.as_ref())
853                && Account::is_user(run.triggering_actor.as_ref()),
854            pull_requests: run
855                .pull_requests
856                .into_iter()
857                .filter(|pull| pull.targets(repository))
858                .map(|pull| pull.number)
859                .collect(),
860        })
861    }
862
863    async fn pull_request(&self, repository: &str, number: u64) -> Result<PullRequest, Error> {
864        let path = format!("/repos/{repository}/pulls/{number}");
865        let pull: Result<PullRequestBody, Error> = self.get(&path).await;
866        lock(&self.etags).remove(&path);
867        let pull = pull?;
868        Ok(PullRequest {
869            by_user: Account::is_user(pull.user.as_ref()),
870            head_repository: pull.head.repo.map(|repo| repo.full_name),
871            head_branch: pull.head.branch,
872        })
873    }
874
875    async fn repository(&self, repository: &str) -> Result<RepositoryDetails, Error> {
876        let body: RepositoryBody = self.get(&format!("/repos/{repository}")).await?;
877        Ok(RepositoryDetails {
878            default_branch: body.default_branch,
879            visibility: body.visibility,
880        })
881    }
882
883    async fn on_branch(&self, repository: &str, branch: &str, sha: &str) -> Result<bool, Error> {
884        let commit =
885            |sha: &str| !sha.is_empty() && sha.bytes().all(|byte| byte.is_ascii_hexdigit());
886        if !commit(sha) {
887            return Ok(false);
888        }
889        // A branch name may hold `#`, `%` or `?`, which would end or change the path.
890        let base: String = branch
891            .bytes()
892            .map(|byte| {
893                if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'-' | b'_' | b'.') {
894                    char::from(byte).to_string()
895                } else {
896                    format!("%{byte:02X}")
897                }
898            })
899            .collect();
900        // Compare would read a bare name as git does, a tag before a branch: a tag `main` would pass for the
901        // branch. This endpoint knows only branches.
902        let path = format!("/repos/{repository}/branches/{base}");
903        let head: Result<BranchBody, Error> = self.get(&path).await;
904        lock(&self.etags).remove(&path);
905        let head = head?.commit.sha;
906        if !commit(&head) {
907            return Ok(false);
908        }
909        // The commits it lists are not needed: one is the fewest it sends.
910        let path = format!("/repos/{repository}/compare/{head}...{sha}?per_page=1");
911        let body: Result<CompareBody, Error> = self.get(&path).await;
912        lock(&self.etags).remove(&path);
913        // `behind`: the branch has moved on past it.
914        Ok(matches!(body?.status.as_str(), "identical" | "behind"))
915    }
916
917    async fn cancel_run(&self, repository: &str, run: u64) -> Result<(), Error> {
918        let path = format!("/repos/{repository}/actions/runs/{run}/cancel");
919        let response = self.send(Method::POST, &path, None, None).await?;
920        // 409: the run completed already.
921        if response.status == StatusCode::CONFLICT {
922            return Ok(());
923        }
924        expect_success(Method::POST, &path, response).map(|_| ())
925    }
926}
927
928fn jobs_path(repository: &str, run: u64) -> String {
929    format!("/repos/{repository}/actions/runs/{run}/jobs?filter=latest&per_page={PER_PAGE}")
930}
931
932struct Response {
933    status: StatusCode,
934    etag: Option<HeaderValue>,
935    /// Whether its `Link` names a next page.
936    next: bool,
937    bytes: Vec<u8>,
938}
939
940/// A decoded answer and whether a next page follows it.
941struct Page<T> {
942    body: T,
943    next: bool,
944}
945
946/// Whether a `Link` header names a next page: `<https://…&page=2>; rel="next", <…>; rel="last"`.
947fn names_next_page(headers: &HeaderMap) -> bool {
948    headers
949        .get_all(header::LINK)
950        .iter()
951        .filter_map(|value| value.to_str().ok())
952        .flat_map(|value| value.split(','))
953        .any(|link| {
954            link.split(';')
955                .skip(1)
956                .any(|param| param.trim() == r#"rel="next""#)
957        })
958}
959
960/// An answer kept for a conditional request on its path.
961#[derive(Clone)]
962struct Cached {
963    etag: HeaderValue,
964    body: Arc<[u8]>,
965    /// Whether its `Link` named a next page: a 304 does not say again.
966    next: bool,
967}
968
969/// The answers kept for conditional requests, by path, within `limit` bytes. Room is made only from answers unused
970/// for `fresh`, least recently used first; without enough of those, a new answer is not kept.
971struct Conditional {
972    entries: HashMap<String, Use>,
973    bytes: usize,
974    limit: usize,
975    fresh: Duration,
976}
977
978struct Use {
979    cached: Cached,
980    used: Instant,
981}
982
983impl Conditional {
984    fn new(limit: usize, fresh: Duration) -> Conditional {
985        Conditional {
986            entries: HashMap::new(),
987            bytes: 0,
988            limit,
989            fresh,
990        }
991    }
992
993    fn size(path: &str, cached: &Cached) -> usize {
994        path.len() + cached.body.len()
995    }
996
997    /// The answer kept for `path`, which counts as using it `now`.
998    fn get(&mut self, path: &str, now: Instant) -> Option<Cached> {
999        let entry = self.entries.get_mut(path)?;
1000        entry.used = now;
1001        Some(entry.cached.clone())
1002    }
1003
1004    /// Keeps `cached` for `path` in place of what was kept for it, if room can be made for it.
1005    fn insert(&mut self, path: &str, cached: Cached, now: Instant) {
1006        self.remove(path);
1007        let size = Conditional::size(path, &cached);
1008        if size > self.limit {
1009            return;
1010        }
1011        while self.bytes + size > self.limit {
1012            let stale = self
1013                .entries
1014                .iter()
1015                .filter(|(_, entry)| now.saturating_duration_since(entry.used) >= self.fresh)
1016                .min_by_key(|(_, entry)| entry.used)
1017                .map(|(path, _)| path.clone());
1018            let Some(stale) = stale else {
1019                return;
1020            };
1021            self.remove(&stale);
1022        }
1023        self.bytes += size;
1024        self.entries
1025            .insert(path.to_owned(), Use { cached, used: now });
1026    }
1027
1028    fn remove(&mut self, path: &str) {
1029        if let Some(entry) = self.entries.remove(path) {
1030            self.bytes -= Conditional::size(path, &entry.cached);
1031        }
1032    }
1033
1034    /// Keeps only the answers whose path `keep` accepts.
1035    fn retain(&mut self, mut keep: impl FnMut(&str) -> bool) {
1036        let bytes = &mut self.bytes;
1037        self.entries.retain(|path, entry| {
1038            let kept = keep(path);
1039            if !kept {
1040                *bytes -= Conditional::size(path, &entry.cached);
1041            }
1042            kept
1043        });
1044    }
1045}
1046
1047fn expect_success(method: Method, path: &str, response: Response) -> Result<Response, Error> {
1048    if response.status.is_success() {
1049        return Ok(response);
1050    }
1051    let message = serde_json::from_slice::<ErrorBody>(&response.bytes).map_or_else(
1052        |_| String::from_utf8_lossy(&response.bytes).into_owned(),
1053        |body| body.message,
1054    );
1055    Err(Error::Status {
1056        method,
1057        path: path.to_owned(),
1058        status: response.status,
1059        message,
1060    })
1061}
1062
1063fn decode<T: DeserializeOwned>(path: &str, bytes: &[u8]) -> Result<T, Error> {
1064    serde_json::from_slice(bytes).map_err(|source| Error::Decode {
1065        path: path.to_owned(),
1066        source,
1067    })
1068}
1069
1070/// When requests may resume, if this response says the rate limit is used up: the primary limit's reset time, or
1071/// a secondary limit's `retry-after`.
1072fn rate_limited_until(
1073    status: StatusCode,
1074    headers: &HeaderMap,
1075    now: SystemTime,
1076) -> Option<SystemTime> {
1077    let number = |name: &str| {
1078        headers
1079            .get(name)
1080            .and_then(|value| value.to_str().ok())
1081            .and_then(|value| value.trim().parse::<u64>().ok())
1082    };
1083    if number("x-ratelimit-remaining") == Some(0)
1084        && let Some(reset) = number("x-ratelimit-reset")
1085    {
1086        return Some(SystemTime::UNIX_EPOCH + Duration::from_secs(reset));
1087    }
1088    if matches!(
1089        status,
1090        StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
1091    ) && let Some(seconds) = number("retry-after")
1092    {
1093        return Some(now + Duration::from_secs(seconds));
1094    }
1095    None
1096}
1097
1098#[cfg(test)]
1099mod tests;