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