Skip to main content

subspace_client_github/
lib.rs

1//! The synchronous GitHub client: accounts, sections, detail, writes and pull
2//! request diffs. No GPUI; dashboards call it off the UI thread.
3//!
4//! Every call runs as one account. `login` is a signed-in or gh login from
5//! [`Client::accounts`]; with `GH_TOKEN`, `GITHUB_TOKEN` or `github.token`
6//! set, that token is used whatever the login (REQ-60).
7
8pub mod actions;
9mod bound;
10pub mod copilot_agents;
11pub use bound::{
12    BoundRead, Organization, PackageRelease, PackageRepository, ReleaseAsset, RepositoryRef,
13    ResolvedRepository, newest_package_release,
14};
15mod cache;
16pub mod copilot_agent_sessions;
17pub mod issue_report;
18pub mod model;
19mod queries;
20mod raw;
21pub mod scope;
22mod transport;
23pub mod validate;
24
25use std::sync::Arc;
26use std::thread;
27use std::time::Duration;
28
29use serde::Deserialize;
30use serde::de::DeserializeOwned;
31use serde_json::{Value, json};
32use subspace_core::credentials::{
33    Credential, CredentialError, Credentials, GitHubAccounts, Source,
34};
35use subspace_core::http::status as http_status;
36use subspace_core::http::{Error, send_with_retry};
37
38use crate::cache::{Lru, Ttl};
39use crate::model::{
40    AssignableResponse, DiffResponse, FileResponse, GhDiffFile, GhItemDetail, GhRepository, GhUser,
41    Image, ItemKind, ReviewEvent, SECTIONS, SectionResponse, image_type,
42};
43use crate::raw::{Nodes, RawActor, RawDetail, RawPrFile};
44use crate::transport::{JSON, RAW, not_found, unexpected};
45use crate::validate::{
46    ItemRef, check_key, check_login, check_logins, check_path, check_repo, check_review_body,
47    check_section, check_sha, invalid, is_sha,
48};
49
50pub const API_URL: &str = "https://api.github.com";
51/// Debug builds only: the GitHub API and Copilot API base to use instead of
52/// [`API_URL`], such as a local fixture server for screenshots.
53pub const API_URL_ENV: &str = "SUBSPACE_GITHUB_API_URL";
54const USER_RESPONSE_LIMIT: usize = 64 * 1024;
55/// The read limit for a JSON answer that can reach a few megabytes.
56pub(crate) const MAX_BODY_BYTES: usize = subspace_core::http::MAX_BODY_BYTES as usize;
57
58/// The login that owns `credential`, from `GET /user`. No retry, cache or
59/// fallback credential: the answer identifies exactly this token.
60pub fn credential_login(credential: &Credential) -> Result<String, Error> {
61    #[derive(Deserialize)]
62    struct User {
63        login: String,
64    }
65    let account = transport::account_label(credential, None);
66    let url = format!("{}/user", api_url());
67    let response = transport::get_rest(&url, credential, &account, JSON)?;
68    let bytes = transport::read_limited(response, USER_RESPONSE_LIMIT)?;
69    let user: User = serde_json::from_slice(&bytes).map_err(|_| unexpected("user"))?;
70    validate::check_login(&user.login).map(str::to_owned)
71}
72
73/// The [`API_URL_ENV`] override, in a debug build when it is set.
74fn debug_api_url() -> Option<String> {
75    let value = std::env::var(API_URL_ENV)
76        .ok()
77        .filter(|_| cfg!(debug_assertions))?;
78    let value = value.trim().trim_end_matches('/');
79    (!value.is_empty()).then(|| value.to_owned())
80}
81
82/// [`API_URL`], unless a debug build overrides it.
83fn api_url() -> String {
84    debug_api_url().unwrap_or_else(|| API_URL.to_owned())
85}
86
87/// The Copilot API base, known up front only when a debug build overrides
88/// the API URL; otherwise GraphQL names it on first use.
89fn copilot_api_override() -> std::sync::OnceLock<String> {
90    debug_api_url()
91        .map(std::sync::OnceLock::from)
92        .unwrap_or_default()
93}
94const ASSIGNABLE_TTL: Duration = Duration::from_secs(10 * 60);
95/// GitHub's limit for the pulls files API.
96pub const MAX_DIFF_FILES: u32 = 3000;
97const FILES_PER_PAGE: u32 = 100;
98const PAGE_CONCURRENCY: u32 = 6;
99pub const MAX_FILE_BYTES: usize = 1024 * 1024;
100pub const MAX_IMAGE_BYTES: usize = 10 * 1024 * 1024;
101const FILE_CACHE_BYTES: usize = 50 * 1024 * 1024;
102const DIFF_CACHE_ENTRIES: usize = 20;
103const MAX_AGENT_SEARCH_BYTES: usize = 200;
104const MAX_AGENT_SEARCH_ITEMS: u32 = 100;
105const REPOSITORIES_PER_PAGE: &str = "30";
106
107/// What one diff read needs: the account, the pull request, its commits
108/// and how many file pages to read.
109struct DiffRequest<'a> {
110    login: &'a str,
111    item: &'a ItemRef,
112    base_tip: &'a str,
113    head: &'a str,
114    pages: u32,
115}
116
117/// The head and merge-base commits of a pull request.
118fn pull_commits(pull: &RawPull) -> Result<(String, String), Error> {
119    let sha = |side: &Option<Sha>| {
120        side.as_ref()
121            .and_then(|side| side.sha.clone())
122            .unwrap_or_default()
123    };
124    let head = sha(&pull.head);
125    let base_tip = sha(&pull.base);
126    if !is_sha(&head) || !is_sha(&base_tip) {
127        return Err(Error::Status {
128            status: http_status::BAD_GATEWAY,
129            message: "GitHub returned no commits for this pull request.".into(),
130        });
131    }
132    Ok((head, base_tip))
133}
134
135// qual:allow(srp, god_struct) reason: "The bound-read delegate shares this account-scoped client but is counted as an independent cluster."
136pub struct Client {
137    credentials: Arc<Credentials>,
138    work_account: Option<String>,
139    api_url: String,
140    /// The Copilot API base GraphQL named, resolved at most once per run.
141    copilot_api: std::sync::OnceLock<String>,
142    assignable: Ttl<Vec<GhUser>>,
143    diffs: Lru<DiffResponse>,
144    files: Lru<String>,
145}
146
147#[derive(Deserialize)]
148#[serde(rename_all = "camelCase")]
149struct Search {
150    #[serde(default)]
151    issue_count: u32,
152    #[serde(default)]
153    nodes: Vec<Value>,
154}
155
156#[derive(Deserialize)]
157struct SearchData {
158    search: Search,
159}
160
161#[derive(Deserialize)]
162#[serde(rename_all = "camelCase")]
163struct Repository<T> {
164    issue_or_pull_request: Option<T>,
165}
166
167#[derive(Deserialize)]
168struct RepositoryData<T> {
169    repository: Option<Repository<T>>,
170}
171
172#[derive(Deserialize)]
173#[serde(rename_all = "camelCase")]
174struct Subject {
175    #[serde(rename = "__typename")]
176    typename: String,
177    id: String,
178}
179
180#[derive(Deserialize)]
181struct Sha {
182    sha: Option<String>,
183}
184
185#[derive(Deserialize)]
186struct RawPull {
187    head: Option<Sha>,
188    base: Option<Sha>,
189    changed_files: Option<u32>,
190}
191
192#[derive(Deserialize)]
193struct RawCompare {
194    merge_base_commit: Option<Sha>,
195}
196
197fn valid_agent_search(query: &str, limit: u32) -> bool {
198    let lower = query.to_ascii_lowercase();
199    query.len() <= MAX_AGENT_SEARCH_BYTES
200        && (1..=MAX_AGENT_SEARCH_ITEMS).contains(&limit)
201        && !["repo:", "org:", "user:"]
202            .iter()
203            .any(|scope| lower.contains(scope))
204        && !query.chars().any(char::is_control)
205        && !query.contains(['(', ')'])
206        && !query
207            .split_whitespace()
208            .any(|word| word.eq_ignore_ascii_case("OR"))
209}
210
211fn agent_mutation(action: &str, kind: &str) -> Result<(&'static str, &'static str), &'static str> {
212    match (action, kind) {
213        ("comment", _) => Ok((
214            "mutation($input:AddCommentInput!) { addComment(input:$input) { commentEdge { node { id url } } } }",
215            "subjectId",
216        )),
217        ("review", "PullRequest") => Ok((
218            "mutation($input:AddPullRequestReviewInput!) { addPullRequestReview(input:$input) { pullRequestReview { id url } } }",
219            "pullRequestId",
220        )),
221        ("update_pr", "PullRequest") => Ok((
222            "mutation($input:UpdatePullRequestInput!) { updatePullRequest(input:$input) { pullRequest { id url title state } } }",
223            "pullRequestId",
224        )),
225        _ => Err("Unsupported action or target is not a pull request."),
226    }
227}
228
229fn agent_mutation_body(
230    mutation: (&str, &str),
231    subject: &str,
232    mut fields: Value,
233) -> Result<String, &'static str> {
234    fields
235        .as_object_mut()
236        .ok_or("Mutation fields must be an object.")?
237        .insert(mutation.1.into(), json!(subject));
238    Ok(json!({"query":mutation.0,"variables":{"input":fields}}).to_string())
239}
240
241#[cfg(test)]
242mod agent_tools_tests {
243    use super::{agent_mutation, agent_mutation_body, valid_agent_search};
244    use serde_json::{Value, json};
245    #[test]
246    fn search_cannot_override_repo_scope_or_bounds() {
247        assert!(valid_agent_search("is:pr merged:>=2026-10-01", 100));
248        for query in [
249            "repo:outside/repo",
250            "org:outside",
251            "user:outside",
252            "is:pr OR is:issue",
253            "(is:pr)",
254            "is:pr\n",
255        ] {
256            assert!(!valid_agent_search(query, 50), "{query}");
257        }
258        assert!(!valid_agent_search("is:pr", 101));
259        assert!(!valid_agent_search("is:pr", 0));
260    }
261    #[test]
262    fn writes_use_only_named_mutations_and_verified_subject() {
263        assert!(agent_mutation("review", "Issue").is_err());
264        assert!(agent_mutation("merge", "PullRequest").is_err());
265        let mutation = agent_mutation("comment", "Issue").unwrap();
266        let body = agent_mutation_body(
267            mutation,
268            "verified-id",
269            json!({"subjectId":"untrusted-id","body":"exact comment"}),
270        )
271        .unwrap();
272        let body: Value = serde_json::from_str(&body).unwrap();
273        assert_eq!(body["variables"]["input"]["subjectId"], "verified-id");
274        assert_eq!(body["variables"]["input"]["body"], "exact comment");
275        assert!(agent_mutation_body(mutation, "id", json!("not an object")).is_err());
276        assert_eq!(
277            agent_mutation("review", "PullRequest").unwrap().1,
278            "pullRequestId"
279        );
280        assert_eq!(
281            agent_mutation("update_pr", "PullRequest").unwrap().1,
282            "pullRequestId"
283        );
284    }
285}
286
287impl Client {
288    /// Capture one credential and verify that it owns the requested login.
289    // qual:api
290    pub fn bind_read(&self, login: &str) -> Result<BoundRead, Error> {
291        BoundRead::bind(self, login)
292    }
293
294    pub fn new(credentials: Arc<Credentials>) -> Self {
295        Self {
296            credentials,
297            work_account: None,
298            api_url: api_url(),
299            copilot_api: copilot_api_override(),
300            assignable: Ttl::new(ASSIGNABLE_TTL),
301            diffs: Lru::new(DIFF_CACHE_ENTRIES, |_| 1),
302            files: Lru::new(FILE_CACHE_BYTES, String::len),
303        }
304    }
305
306    /// One bounded repository search. Scope is part of the GraphQL repository,
307    /// so user search text cannot widen it to other repositories.
308    // qual:api
309    pub fn agent_search(
310        &self,
311        login: &str,
312        repo: &str,
313        query: &str,
314        limit: u32,
315    ) -> Result<Value, Error> {
316        check_login(login)?;
317        check_repo(repo)?;
318        valid_agent_search(query, limit).then_some(()).ok_or_else(|| invalid("Use at most 200 characters of search terms without scope qualifiers, OR, parentheses or control characters; limit is 1..100."))?;
319        self.graphql_value(Some(login), "query($query:String!, $limit:Int!) { search(query:$query,type:ISSUE,first:$limit) { issueCount pageInfo { hasNextPage endCursor } nodes { ... on Issue { number title body state url updatedAt repository { nameWithOwner } author { login } } ... on PullRequest { number title body state url updatedAt mergedAt repository { nameWithOwner } author { login } } } } }", json!({"query":format!("repo:{repo} {query}"),"limit":limit}), false)
320    }
321
322    /// Named GraphQL writes, each sent once. Never offers a raw HTTP surface.
323    // qual:api
324    pub fn agent_write(
325        &self,
326        login: &str,
327        key: &str,
328        action: &str,
329        fields: Value,
330    ) -> Result<Value, Error> {
331        check_login(login)?;
332        let item = check_key(key)?;
333        let subject = self.subject(login, &item)?;
334        let mutation = agent_mutation(action, &subject.typename).map_err(invalid)?;
335        let body = agent_mutation_body(mutation, &subject.id, fields).map_err(invalid)?;
336        let credential = self.credentials.github(Some(login))?;
337        let account = transport::account_label(&credential, Some(login));
338        let response = transport::post_graphql(
339            &format!("{}/graphql", self.api_url),
340            &credential,
341            &account,
342            &body,
343        )?;
344        transport::graphql_data(&account, response, false)
345    }
346
347    /// Sends every request to `api_url` instead of api.github.com (tests).
348    pub fn with_api_url(mut self, api_url: impl Into<String>) -> Self {
349        self.api_url = api_url.into().trim_end_matches('/').to_owned();
350        self
351    }
352
353    /// Prefer this configured gh account for Copilot work, before EMU detection.
354    // qual:api
355    pub fn with_work_account(mut self, login: Option<String>) -> Self {
356        self.work_account = login;
357        self
358    }
359
360    /// The accounts to offer: the signed-in and gh accounts for github.com;
361    /// but when the token comes from the environment or the config file, the
362    /// one account that token belongs to (REQ-60).
363    pub fn accounts(&self) -> Result<GitHubAccounts, Error> {
364        let (hosts, credential) = match self.credentials.github_accounts() {
365            Ok(hosts) => {
366                let login = hosts
367                    .active
368                    .clone()
369                    .or_else(|| hosts.logins.first().cloned());
370                let credential = self.credentials.github(login.as_deref())?;
371                (Some(hosts), credential)
372            }
373            Err(_) => (None, self.credentials.github(None)?),
374        };
375        if let (Some(hosts), Source::GhCli { .. } | Source::SignedIn { .. }) =
376            (hosts, &credential.source)
377        {
378            return Ok(hosts);
379        }
380        let login = self.viewer_login(None)?;
381        Ok(GitHubAccounts {
382            logins: vec![login.clone()],
383            active: Some(login),
384            signed_in: Vec::new(),
385        })
386    }
387
388    /// The login of the token for `login` (or the default token).
389    pub fn viewer_login(&self, login: Option<&str>) -> Result<String, Error> {
390        #[derive(Deserialize)]
391        struct Viewer {
392            login: String,
393        }
394        #[derive(Deserialize)]
395        struct Data {
396            viewer: Viewer,
397        }
398        let data: Data = self.graphql(login, queries::VIEWER_QUERY, json!({}), false)?;
399        Ok(data.viewer.login)
400    }
401
402    /// Selects the chosen gh account, else the first enterprise (EMU) login,
403    /// and verifies that the selected credential really belongs to it.
404    /// Environment tokens belonging to another account are rejected.
405    pub fn work_login(&self) -> Result<String, Error> {
406        let accounts = self
407            .credentials
408            .github_accounts()
409            .map_err(|_| Error::Status {
410                status: http_status::BAD_GATEWAY,
411                message: "No GitHub accounts are configured for the work account.".into(),
412            })?;
413        let login =
414            pick_work_login(&accounts.logins, self.work_account.as_ref()).ok_or_else(|| {
415                Error::Status {
416                    status: http_status::BAD_GATEWAY,
417                    message: "No work (EMU) or chosen GitHub account is configured.".into(),
418                }
419            })?;
420        let actual = self.viewer_login(Some(login))?;
421        verified_work_login(login, &actual)
422    }
423
424    /// The credential for `login` (REQ-21), for callers that only need to
425    /// know whether one exists.
426    pub fn credential(&self, login: Option<&str>) -> Result<Credential, CredentialError> {
427        self.credentials.github(login)
428    }
429
430    fn graphql_value(
431        &self,
432        login: Option<&str>,
433        query: &str,
434        variables: Value,
435        partial: bool,
436    ) -> Result<Value, Error> {
437        let url = format!("{}/graphql", self.api_url);
438        let body = json!({ "query": query, "variables": variables }).to_string();
439        send_with_retry(
440            &self.credentials,
441            |credentials| credentials.github(login),
442            |credential| {
443                let account = transport::account_label(credential, login);
444                let response = transport::post_graphql(&url, credential, &account, &body)?;
445                transport::graphql_data(&account, response, partial)
446            },
447        )
448    }
449
450    fn graphql<T: DeserializeOwned>(
451        &self,
452        login: Option<&str>,
453        query: &str,
454        variables: Value,
455        partial: bool,
456    ) -> Result<T, Error> {
457        let data = self.graphql_value(login, query, variables, partial)?;
458        serde_json::from_value(data).map_err(|_| unexpected("response"))
459    }
460
461    /// A REST URL: `segments` are percent-encoded one by one.
462    fn rest_url<'a>(
463        &self,
464        segments: impl IntoIterator<Item = &'a str>,
465        query: &[(&str, &str)],
466    ) -> Result<String, Error> {
467        let mut url = url::Url::parse(&self.api_url)
468            .map_err(|_| invalid("The GitHub API URL is not valid."))?;
469        url.path_segments_mut()
470            .map_err(|()| invalid("The GitHub API URL is not valid."))?
471            .pop_if_empty()
472            .extend(segments);
473        if !query.is_empty() {
474            url.query_pairs_mut().extend_pairs(query);
475        }
476        Ok(url.into())
477    }
478
479    fn rest_bytes(
480        &self,
481        login: &str,
482        url: &str,
483        accept: &str,
484        max: usize,
485    ) -> Result<Vec<u8>, Error> {
486        send_with_retry(
487            &self.credentials,
488            |credentials| credentials.github(Some(login)),
489            |credential| {
490                let account = transport::account_label(credential, Some(login));
491                let response = transport::get_rest(url, credential, &account, accept)?;
492                transport::read_limited(response, max)
493            },
494        )
495    }
496
497    fn rest_json<T: DeserializeOwned>(&self, login: &str, url: &str) -> Result<T, Error> {
498        // JSON answers of the pulls files API reach a few MB with patches.
499        let bytes = self.rest_bytes(login, url, JSON, MAX_BODY_BYTES)?;
500        serde_json::from_slice(&bytes).map_err(|_| unexpected("response"))
501    }
502
503    /// One section: up to 50 items, most recently updated first. `repos`
504    /// limits it to those repositories (`None`: everything the account can
505    /// see); a [`repos_only`](model::SectionDef::repos_only) section without
506    /// repositories is empty and sends nothing. Long repository lists run as
507    /// several searches in parallel, merged by update time.
508    pub fn section(
509        &self,
510        login: &str,
511        section_id: &str,
512        repos: Option<&[String]>,
513    ) -> Result<SectionResponse, Error> {
514        check_login(login)?;
515        let section = check_section(section_id)?;
516        let repos = if section.repos_only {
517            Some(repos.unwrap_or_default())
518        } else {
519            repos
520        };
521        let searches = scope::searches(section.query, repos)?;
522        let results: Vec<Result<(u32, Vec<model::GhItem>), Error>> = thread::scope(|scope| {
523            let handles: Vec<_> = searches
524                .iter()
525                .map(|query| scope.spawn(|| self.section_search(login, section.kind, query)))
526                .collect();
527            handles
528                .into_iter()
529                .map(|handle| {
530                    handle
531                        .join()
532                        .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())))
533                })
534                .collect()
535        });
536        let (total, items) = scope::merge(results.into_iter().collect::<Result<_, _>>()?);
537        Ok(SectionResponse {
538            account: login.to_owned(),
539            section: section.id.to_owned(),
540            total,
541            items,
542        })
543    }
544
545    /// One search of a section. Populated PR searches run two optional
546    /// enrichment searches in parallel after the row query. Empty or failed
547    /// row queries do not launch enrichment requests.
548    fn section_search(
549        &self,
550        login: &str,
551        kind: ItemKind,
552        query: &str,
553    ) -> Result<(u32, Vec<model::GhItem>), Error> {
554        let variables = json!({ "query": query });
555        // partial: items in SSO-protected organisations come back as null.
556        let search =
557            |query: &str| self.graphql::<SearchData>(Some(login), query, variables.clone(), true);
558        let main_query = queries::section_query();
559        let main = search(&main_query)?.search;
560        let extra_queries =
561            if kind == ItemKind::Pr && !raw::section_items(&main.nodes, &[]).is_empty() {
562                queries::pr_extra_queries().to_vec()
563            } else {
564                Vec::new()
565            };
566        let extras: Vec<SearchData> = thread::scope(|scope| {
567            let handles: Vec<_> = extra_queries
568                .iter()
569                .map(|query| scope.spawn(|| search(query)))
570                .collect();
571            handles
572                .into_iter()
573                .filter_map(|handle| handle.join().ok()?.ok())
574                .collect()
575        });
576        let extra_nodes: Vec<Value> = extras
577            .into_iter()
578            .flat_map(|extra| extra.search.nodes)
579            .collect();
580        let items = raw::section_items(&main.nodes, &raw::extras(&extra_nodes));
581        Ok((main.issue_count, items))
582    }
583
584    /// Repositories the account can see for `text`: GitHub's repository
585    /// search, or with no text the account's own and member repositories,
586    /// most recently pushed first. At most 30.
587    pub fn repositories(&self, login: &str, text: &str) -> Result<Vec<GhRepository>, Error> {
588        #[derive(Deserialize)]
589        struct Found {
590            items: Vec<GhRepository>,
591        }
592        check_login(login)?;
593        let text = scope::check_search_text(text)?;
594        if text.is_empty() {
595            let url = self.rest_url(
596                ["user", "repos"],
597                &[
598                    ("sort", "pushed"),
599                    ("per_page", REPOSITORIES_PER_PAGE),
600                    ("affiliation", "owner,collaborator,organization_member"),
601                ],
602            )?;
603            return self.rest_json(login, &url);
604        }
605        let url = self.rest_url(
606            ["search", "repositories"],
607            &[("q", text), ("per_page", REPOSITORIES_PER_PAGE)],
608        )?;
609        Ok(self.rest_json::<Found>(login, &url)?.items)
610    }
611
612    /// Every section, account-wide, in [`SECTIONS`] order, in parallel.
613    pub fn sections(&self, login: &str) -> Vec<(&'static str, Result<SectionResponse, Error>)> {
614        thread::scope(|scope| {
615            let handles: Vec<_> = SECTIONS
616                .iter()
617                .map(|section| {
618                    (
619                        section.id,
620                        scope.spawn(|| self.section(login, section.id, None)),
621                    )
622                })
623                .collect();
624            handles
625                .into_iter()
626                .map(|(id, handle)| {
627                    let result = handle
628                        .join()
629                        .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())));
630                    (id, result)
631                })
632                .collect()
633        })
634    }
635
636    fn load_detail(&self, login: &str, item: &ItemRef) -> Result<GhItemDetail, Error> {
637        let variables = json!({ "owner": item.owner, "name": item.name, "number": item.number });
638        let data: RepositoryData<RawDetail> =
639            self.graphql(Some(login), &queries::detail_query(), variables, false)?;
640        detail_from_data(data)
641    }
642
643    /// The detail of `key` (`owner/name#number`).
644    pub fn item(&self, login: &str, key: &str) -> Result<GhItemDetail, Error> {
645        check_login(login)?;
646        self.load_detail(login, &check_key(key)?)
647    }
648
649    /// The people who can be assigned in `repo`, cached for 10 minutes.
650    // qual:api
651    pub fn assignable(&self, login: &str, repo: &str) -> Result<AssignableResponse, Error> {
652        check_login(login)?;
653        let (owner, name) = check_repo(repo)?;
654        #[derive(Deserialize)]
655        #[serde(rename_all = "camelCase")]
656        struct Assignable {
657            assignable_users: Nodes<RawActor>,
658        }
659        #[derive(Deserialize)]
660        struct Data {
661            repository: Option<Assignable>,
662        }
663        let key = format!("gh-assignable:{login}:{owner}/{name}").to_lowercase();
664        let users = self.assignable.get_or_load(&key, || {
665            let variables = json!({ "owner": owner, "name": name });
666            let data: Data =
667                self.graphql(Some(login), queries::ASSIGNABLE_QUERY, variables, false)?;
668            let repository = data.repository.ok_or_else(|| Error::Status {
669                status: http_status::NOT_FOUND,
670                message: "Repository not found on GitHub.".into(),
671            })?;
672            Ok::<_, Error>(raw::assignable_users(&repository.assignable_users))
673        })?;
674        Ok(AssignableResponse { users })
675    }
676
677    fn subject(&self, login: &str, item: &ItemRef) -> Result<Subject, Error> {
678        let variables = json!({ "owner": item.owner, "name": item.name, "number": item.number });
679        let data: RepositoryData<Subject> =
680            self.graphql(Some(login), queries::SUBJECT_QUERY, variables, false)?;
681        data.repository
682            .and_then(|repository| repository.issue_or_pull_request)
683            .ok_or_else(not_found)
684    }
685
686    /// Approves, requests changes or comments as a review; returns the
687    /// fresh detail. The body is required except for an approval.
688    pub fn review(
689        &self,
690        login: &str,
691        key: &str,
692        event: ReviewEvent,
693        body: &str,
694    ) -> Result<GhItemDetail, Error> {
695        check_login(login)?;
696        let item = check_key(key)?;
697        let body = check_review_body(event, body)?;
698        let subject = self.subject(login, &item)?;
699        if subject.typename != "PullRequest" {
700            return Err(invalid("Reviews apply only to pull requests."));
701        }
702        let body = (!body.is_empty()).then_some(body);
703        let variables = json!({ "id": subject.id, "event": event.as_str(), "body": body });
704        self.graphql_value(Some(login), queries::REVIEW_MUTATION, variables, false)?;
705        self.load_detail(login, &item)
706    }
707
708    /// The repository's default branch, which a cloud agent task branches
709    /// from when the caller names none.
710    pub fn default_branch(&self, login: &str, repo: &str) -> Result<String, Error> {
711        check_login(login)?;
712        check_repo(repo)?;
713        let value: Value = self.rest_json(login, &format!("{}/repos/{repo}", self.api_url))?;
714        value
715            .get("default_branch")
716            .and_then(Value::as_str)
717            .map(str::to_owned)
718            .ok_or_else(|| invalid("The repository reports no default branch."))
719    }
720
721    /// Comments on an issue or pull request; returns the fresh detail.
722    // qual:api
723    pub fn comment(&self, login: &str, key: &str, body: &str) -> Result<GhItemDetail, Error> {
724        check_login(login)?;
725        let item = check_key(key)?;
726        let body = validate::check_body(body, true)?;
727        let subject = self.subject(login, &item)?;
728        let variables = json!({ "id": subject.id, "body": body });
729        self.graphql_value(Some(login), queries::COMMENT_MUTATION, variables, false)?;
730        self.load_detail(login, &item)
731    }
732
733    /// Adds and removes assignees (at most 10 each, at least one in all);
734    /// returns the fresh detail.
735    // qual:api
736    pub fn set_assignees(
737        &self,
738        login: &str,
739        key: &str,
740        add: &[String],
741        remove: &[String],
742    ) -> Result<GhItemDetail, Error> {
743        check_login(login)?;
744        let item = check_key(key)?;
745        let add = check_logins("add", add)?;
746        let remove = check_logins("remove", remove)?;
747        if add.is_empty() && remove.is_empty() {
748            return Err(invalid("add or remove must name at least one login."));
749        }
750        let mut all: Vec<&String> = Vec::new();
751        for user in add.iter().chain(&remove) {
752            if !all.contains(&user) {
753                all.push(user);
754            }
755        }
756        let mut variables =
757            json!({ "owner": item.owner, "name": item.name, "number": item.number });
758        for (index, user) in all.iter().enumerate() {
759            variables[format!("l{index}")] = json!(user);
760        }
761        // partial: an unknown login is reported by name, not as GitHub's
762        // generic error.
763        let data = self.graphql_value(
764            Some(login),
765            &queries::assignee_lookup_query(all.len()),
766            variables,
767            true,
768        )?;
769        let id = data["repository"]["issueOrPullRequest"]["id"]
770            .as_str()
771            .ok_or_else(not_found)?
772            .to_owned();
773        let user_id = |user: &String| -> Result<String, Error> {
774            let index = all
775                .iter()
776                .position(|known| *known == user)
777                .unwrap_or_default();
778            data[format!("u{index}")]["id"]
779                .as_str()
780                .map(str::to_owned)
781                .ok_or_else(|| invalid(format!("Unknown GitHub user: {user}.")))
782        };
783        let add_ids = add.iter().map(user_id).collect::<Result<Vec<_>, _>>()?;
784        let remove_ids = remove.iter().map(user_id).collect::<Result<Vec<_>, _>>()?;
785        let mut variables = json!({ "id": id });
786        if !add_ids.is_empty() {
787            variables["add"] = json!(add_ids);
788        }
789        if !remove_ids.is_empty() {
790            variables["remove"] = json!(remove_ids);
791        }
792        let mutation = queries::assignee_mutation(!add_ids.is_empty(), !remove_ids.is_empty());
793        self.graphql_value(Some(login), &mutation, variables, false)?;
794        self.load_detail(login, &item)
795    }
796
797    /// A pull request's changed files, with the merge base as the old side
798    /// of every patch. Cached per base and head SHA.
799    pub fn diff(&self, login: &str, key: &str) -> Result<DiffResponse, Error> {
800        check_login(login)?;
801        let item = check_key(key)?;
802        let number = item.number.to_string();
803        let repo = item.repo();
804        let pull_url = self.rest_url(["repos", &item.owner, &item.name, "pulls", &number], &[])?;
805        let pull: RawPull = self.rest_json(login, &pull_url)?;
806        let (head, base_tip) = pull_commits(&pull)?;
807        let cache_key = format!("{login}\n{repo}#{number}@{base_tip}..{head}");
808        if let Some(hit) = self.diffs.get(&cache_key) {
809            return Ok(hit);
810        }
811        let changed_files = pull.changed_files.unwrap_or(0);
812        let (base, mut files) = self.diff_files(&DiffRequest {
813            login,
814            item: &item,
815            base_tip: &base_tip,
816            head: &head,
817            pages: file_pages(changed_files),
818        })?;
819        files.truncate(MAX_DIFF_FILES as usize);
820        let result = DiffResponse {
821            repo,
822            number: item.number,
823            base_sha: base,
824            head_sha: head,
825            total: pull.changed_files.unwrap_or(files.len() as u32),
826            files,
827        };
828        self.diffs.set(cache_key, result.clone());
829        Ok(result)
830    }
831
832    /// The merge base and the changed files of one pull request, read in
833    /// parallel. Paging stops at the first short page.
834    fn diff_files(&self, request: &DiffRequest<'_>) -> Result<(String, Vec<GhDiffFile>), Error> {
835        let DiffRequest {
836            login,
837            item,
838            base_tip,
839            head,
840            pages,
841        } = *request;
842        let number = item.number.to_string();
843        let files_url = |page: u32| {
844            let page = page.to_string();
845            let per_page = FILES_PER_PAGE.to_string();
846            self.rest_url(
847                ["repos", &item.owner, &item.name, "pulls", &number, "files"],
848                &[("per_page", &per_page), ("page", &page)],
849            )
850        };
851        thread::scope(|scope| {
852            let base = scope.spawn(|| self.merge_base(login, item, base_tip, head));
853            let mut files: Vec<GhDiffFile> = Vec::new();
854            let mut first = 1;
855            while first <= pages {
856                let last = (first + PAGE_CONCURRENCY - 1).min(pages);
857                let handles: Vec<_> = (first..=last)
858                    .map(|page| {
859                        let url = files_url(page);
860                        scope.spawn(move || self.rest_json::<Vec<RawPrFile>>(login, &url?))
861                    })
862                    .collect();
863                let mut short_page = false;
864                for handle in handles {
865                    let list = handle
866                        .join()
867                        .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())))?;
868                    short_page |= list.len() < FILES_PER_PAGE as usize;
869                    files.extend(list.into_iter().map(raw::to_diff_file));
870                }
871                if short_page {
872                    break;
873                }
874                first = last + 1;
875            }
876            let base = base.join().unwrap_or_else(|_| base_tip.to_owned());
877            Ok((base, files))
878        })
879    }
880
881    /// The merge base of `base` and `head`, else `base` when the compare
882    /// call fails. Page 2 with one commit per page: GitHub lists the
883    /// changed files on the first page only.
884    fn merge_base(&self, login: &str, item: &ItemRef, base: &str, head: &str) -> String {
885        let range = format!("{base}...{head}");
886        let compare = self
887            .rest_url(
888                ["repos", &item.owner, &item.name, "compare", &range],
889                &[("per_page", "1"), ("page", "2")],
890            )
891            .and_then(|url| self.rest_json::<RawCompare>(login, &url));
892        compare
893            .ok()
894            .and_then(|compare| compare.merge_base_commit?.sha)
895            .filter(|sha| is_sha(sha))
896            .unwrap_or_else(|| base.to_owned())
897    }
898
899    fn contents_url(
900        &self,
901        owner: &str,
902        name: &str,
903        sha: &str,
904        path: &str,
905    ) -> Result<String, Error> {
906        let segments = ["repos", owner, name, "contents"]
907            .into_iter()
908            .chain(path.split('/'));
909        self.rest_url(segments, &[("ref", sha)])
910    }
911
912    /// One file's text at a commit, up to 1 MB (else 413); a binary file is
913    /// a 415. Cached per account, up to 50 MB.
914    pub fn file(
915        &self,
916        login: &str,
917        repo: &str,
918        sha: &str,
919        path: &str,
920    ) -> Result<FileResponse, Error> {
921        check_login(login)?;
922        let (owner, name) = check_repo(repo)?;
923        let sha = check_sha(sha)?;
924        let path = check_path(path)?;
925        // The key holds the account: a text must not reach an account
926        // without access to it.
927        let key = format!("{login}\n{owner}/{name}@{sha}:{path}");
928        if let Some(text) = self.files.get(&key) {
929            return Ok(FileResponse { text });
930        }
931        let url = self.contents_url(&owner, &name, sha, path)?;
932        let bytes = self.rest_bytes(login, &url, RAW, MAX_FILE_BYTES)?;
933        if bytes.contains(&0) {
934            return Err(Error::Status {
935                status: http_status::UNSUPPORTED_MEDIA_TYPE,
936                message: "The file is binary.".into(),
937            });
938        }
939        let text = String::from_utf8_lossy(&bytes).into_owned();
940        self.files.set(key, text.clone());
941        Ok(FileResponse { text })
942    }
943
944    /// One image at a commit, up to 10 MB. Only the extensions of
945    /// [`image_type`]; other paths are a 415. Not cached.
946    pub fn image(&self, login: &str, repo: &str, sha: &str, path: &str) -> Result<Image, Error> {
947        check_login(login)?;
948        let (owner, name) = check_repo(repo)?;
949        let sha = check_sha(sha)?;
950        let path = check_path(path)?;
951        let content_type = image_type(path).ok_or_else(|| Error::Status {
952            status: http_status::UNSUPPORTED_MEDIA_TYPE,
953            message: "The file is not a supported image.".into(),
954        })?;
955        let url = self.contents_url(&owner, &name, sha, path)?;
956        let bytes = self.rest_bytes(login, &url, RAW, MAX_IMAGE_BYTES)?;
957        Ok(Image {
958            content_type,
959            bytes,
960        })
961    }
962}
963
964fn detail_from_data(data: RepositoryData<RawDetail>) -> Result<GhItemDetail, Error> {
965    let node = data
966        .repository
967        .and_then(|repository| repository.issue_or_pull_request)
968        .ok_or_else(not_found)?;
969    Ok(raw::to_detail(&node))
970}
971
972/// Match a saved account using gh's spelling, else detect the first EMU login.
973fn pick_work_login<'a>(logins: &'a [String], chosen: Option<&String>) -> Option<&'a String> {
974    chosen
975        .and_then(|chosen| {
976            logins
977                .iter()
978                .find(|login| login.eq_ignore_ascii_case(chosen))
979        })
980        .or_else(|| {
981            logins.iter().find(|login| {
982                login.rsplit_once('_').is_some_and(|(_, code)| {
983                    !code.is_empty() && code.bytes().all(|byte| byte.is_ascii_alphanumeric())
984                })
985            })
986        })
987}
988
989/// A preference never permits a token owned by another account.
990fn verified_work_login(login: &str, actual: &str) -> Result<String, Error> {
991    if actual != login {
992        return Err(Error::Status {
993            status: http_status::BAD_GATEWAY,
994            message: "The selected work GitHub credential belongs to another account.".into(),
995        });
996    }
997    Ok(login.to_owned())
998}
999
1000/// Pages of the pulls files API to request: at least one, at most GitHub's
1001/// 3,000-file limit.
1002pub fn file_pages(changed_files: u32) -> u32 {
1003    changed_files
1004        .clamp(1, MAX_DIFF_FILES)
1005        .div_ceil(FILES_PER_PAGE)
1006}
1007
1008#[cfg(test)]
1009mod tests;