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