Skip to main content

gitpoulpi_hosting/account/
mod.rs

1//! Account-wide lists: the requests waiting for my review, every open
2//! request of my namespaces and the issues assigned to me, across every
3//! repository of a host rather than the one folder a scope is about.
4//!
5//! One call, [`crate::HostingClient::account_items`], answers a whole
6//! [`AccountQuery`] for GitHub, GitLab, Gitea/Forgejo, Azure DevOps, Bitbucket Data Center and Gerrit (the other hosts keep
7//! the `Unsupported` default for now). The rows are the ordinary
8//! [`PullRequestSummary`] / [`IssueSummary`] plus the project they belong to
9//! and a clone URL, so a caller can tell a cloned repository from one that is
10//! not. Every list is bounded ([`DEFAULT_LIMIT`] rows per kind, a few pages and
11//! queries per round) because a token can see far more than anyone reads.
12//!
13//! Failure policy: a sub-query that fails for one namespace (a group the token
14//! cannot read, a 404) becomes a note and the others still run; a rejected
15//! token, a rate limit or a dead network fails the whole call, because every
16//! later sub-query would fail the same way.
17
18// The shared plumbing below serves six providers; a build with only some of
19// them leaves parts of it without a caller.
20#![cfg_attr(
21    not(all(
22        feature = "github",
23        feature = "gitlab",
24        feature = "gitea",
25        feature = "azure-devops",
26        feature = "bitbucket",
27        feature = "gerrit"
28    )),
29    allow(dead_code)
30)]
31
32use serde::{Deserialize, Serialize};
33
34use crate::http::{HttpRequest, HttpResponse, HttpTransport};
35use crate::model::{IssueSummary, PullRequestState, PullRequestSummary};
36use crate::{Error, Result};
37
38mod branches;
39mod cache;
40#[cfg(feature = "gitea")]
41pub(crate) mod gitea;
42#[cfg(feature = "github")]
43pub(crate) mod github;
44#[cfg(feature = "gitlab")]
45pub(crate) mod gitlab;
46mod namespace;
47#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
48mod tests;
49#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
50mod tests_branches;
51#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
52mod tests_namespaces;
53#[cfg(all(
54    test,
55    feature = "github",
56    feature = "gitlab",
57    feature = "gitea",
58    feature = "azure-devops",
59    feature = "bitbucket",
60    feature = "gerrit"
61))]
62mod tests_wave2;
63
64pub use cache::{
65    cache_path, AccountCache, CachedAccount, ACCOUNT_CACHE_FILE, ACCOUNT_TTL, ACCOUNT_TTL_SECS,
66};
67pub use namespace::{compile as compile_namespace_regex, first_regex_error, NamespaceFilter};
68
69/// Rows kept per kind (requests, issues) when the query names no limit.
70pub const DEFAULT_LIMIT: usize = 300;
71
72/// What to fetch for one integration.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct AccountQuery {
75    /// Open requests that wait for my review.
76    pub review_requests: bool,
77    /// Every open request of my namespaces.
78    pub open_requests: bool,
79    /// Open issues assigned to me.
80    pub assigned_issues: bool,
81    /// Keep draft requests too.
82    pub include_drafts: bool,
83    /// Orgs / groups to search for `open_requests`; empty = my own namespace
84    /// plus every one I am a member of.
85    pub namespaces: Vec<String>,
86    /// Read each namespace line as a regular expression over the full
87    /// repository path instead of a path prefix.
88    #[serde(default)]
89    pub namespaces_regex: bool,
90    /// Rows kept per kind; 0 = [`DEFAULT_LIMIT`].
91    pub limit: usize,
92}
93
94impl AccountQuery {
95    /// The effective per-kind row limit.
96    pub fn row_limit(&self) -> usize {
97        if self.limit == 0 {
98            DEFAULT_LIMIT
99        } else {
100            self.limit
101        }
102    }
103
104    /// The namespaces a host's own queries can be scoped to: the plain lines,
105    /// none in regex mode (a pattern is not a group name; the filter on the
106    /// results does the work).
107    pub fn search_namespaces(&self) -> &[String] {
108        if self.namespaces_regex {
109            &[]
110        } else {
111            &self.namespaces
112        }
113    }
114
115    /// Whether the query asks for nothing at all.
116    pub fn is_empty(&self) -> bool {
117        !(self.review_requests || self.open_requests || self.assigned_issues)
118    }
119
120    /// A short stable fingerprint, so a cache entry is only reused for the
121    /// same question (FNV-1a over a canonical spelling; not a security hash).
122    pub fn fingerprint(&self) -> String {
123        let mut spaces: Vec<String> = self.namespaces.iter().map(|n| n.to_lowercase()).collect();
124        spaces.sort();
125        let text = format!(
126            "v2r{}o{}i{}d{}l{}x{}|{}",
127            self.review_requests as u8,
128            self.open_requests as u8,
129            self.assigned_issues as u8,
130            self.include_drafts as u8,
131            self.row_limit(),
132            self.namespaces_regex as u8,
133            spaces.join(",")
134        );
135        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
136        for b in text.bytes() {
137            hash ^= u64::from(b);
138            hash = hash.wrapping_mul(0x0100_0000_01b3);
139        }
140        format!("{hash:016x}")
141    }
142}
143
144/// A request found account-wide.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct AccountPr {
147    /// `owner/name`, `group/sub/proj`: the repository it belongs to.
148    pub project: String,
149    /// Where to clone that repository from (HTTPS); empty when unknown.
150    #[serde(default)]
151    pub clone_url: String,
152    #[serde(flatten)]
153    pub pr: PullRequestSummary,
154}
155
156/// An issue found account-wide.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct AccountIssue {
159    pub project: String,
160    #[serde(default)]
161    pub clone_url: String,
162    #[serde(flatten)]
163    pub issue: IssueSummary,
164}
165
166/// The answer to an [`AccountQuery`].
167#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
168pub struct AccountItems {
169    #[serde(default)]
170    pub prs: Vec<AccountPr>,
171    #[serde(default)]
172    pub issues: Vec<AccountIssue>,
173    /// More rows existed than the limit kept.
174    #[serde(default)]
175    pub truncated: bool,
176    /// One line per sub-query that failed or was cut short.
177    #[serde(default)]
178    pub notes: Vec<String>,
179}
180
181/// Whether [`crate::HostingClient::account_items`] is implemented for `kind`
182/// (the other code hosts answer `Unsupported` until their queries land).
183pub fn supports(kind: crate::IntegrationKind) -> bool {
184    use gitpoulpi_config::ApiFamily;
185    match kind.family() {
186        ApiFamily::Github
187        | ApiFamily::Gitlab
188        | ApiFamily::Gitea
189        | ApiFamily::AzureDevops
190        | ApiFamily::Gerrit => true,
191        // Bitbucket Cloud has no account-wide endpoint.
192        ApiFamily::Bitbucket => kind == crate::IntegrationKind::BitbucketDataCenter,
193        _ => false,
194    }
195}
196
197/// Why Bitbucket Cloud answers `Unsupported` (shown by `hosting radar`).
198pub const NO_BITBUCKET_CLOUD: &str = "Bitbucket Cloud has no account-wide pull request \
199     endpoint (its lists are per repository); Bitbucket Data Center does";
200
201/// An error that makes the remaining sub-queries pointless.
202pub(crate) fn is_fatal(error: &Error) -> bool {
203    matches!(
204        error,
205        Error::Unauthorized { .. } | Error::RateLimited { .. } | Error::Http(_)
206    )
207}
208
209/// `https://host/owner/name.git`, or empty when the profile has no web root.
210pub(crate) fn clone_url(integration: &crate::Integration, project: &str) -> String {
211    crate::spec::web_base(integration)
212        .map(|base| format!("{base}/{project}.git"))
213        .unwrap_or_default()
214}
215
216/// Collects the rows of every sub-query, merges duplicates, applies the draft
217/// filter and the limit.
218#[derive(Default)]
219pub(crate) struct Collector {
220    prs: Vec<AccountPr>,
221    issues: Vec<AccountIssue>,
222    notes: Vec<String>,
223    /// A host said more rows exist than it returned.
224    cut: bool,
225}
226
227impl Collector {
228    pub(crate) fn note(&mut self, text: impl Into<String>) {
229        self.notes.push(text.into());
230    }
231
232    /// Records that the host holds more rows than it returned.
233    pub(crate) fn cut(&mut self, note: impl Into<String>) {
234        self.cut = true;
235        self.notes.push(note.into());
236    }
237
238    /// Records a failed sub-query as a note, or returns the error when it is
239    /// fatal for the whole call.
240    pub(crate) fn failed(&mut self, what: &str, error: Error) -> Result<()> {
241        if is_fatal(&error) {
242            return Err(error);
243        }
244        self.notes.push(format!("{what}: {error}"));
245        Ok(())
246    }
247
248    /// Adds a request; one already seen (same project and number) only gains
249    /// the "review requested" flag and the reviewers the newcomer knows.
250    pub(crate) fn add_pr(&mut self, row: AccountPr) {
251        let seen = self
252            .prs
253            .iter_mut()
254            .find(|p| p.project == row.project && p.pr.number == row.pr.number);
255        match seen {
256            Some(old) => {
257                old.pr.review_requested |= row.pr.review_requested;
258                for reviewer in row.pr.reviewers {
259                    if !old.pr.reviewers.contains(&reviewer) {
260                        old.pr.reviewers.push(reviewer);
261                    }
262                }
263            }
264            None => self.prs.push(row),
265        }
266    }
267
268    pub(crate) fn add_issue(&mut self, row: AccountIssue) {
269        let seen = self
270            .issues
271            .iter()
272            .any(|i| i.project == row.project && i.issue.number == row.issue.number);
273        if !seen {
274            self.issues.push(row);
275        }
276    }
277
278    pub(crate) fn finish(mut self, query: &AccountQuery) -> AccountItems {
279        let limit = query.row_limit();
280        // The namespaces apply to every list: the host's review and issue
281        // queries are global, so the filter runs here on the project path.
282        match NamespaceFilter::new(&query.namespaces, query.namespaces_regex) {
283            Ok(filter) if filter.is_empty() => {}
284            Ok(filter) => {
285                self.prs.retain(|p| filter.matches(&p.project));
286                self.issues.retain(|i| filter.matches(&i.project));
287            }
288            Err(why) => {
289                self.prs.clear();
290                self.issues.clear();
291                self.notes
292                    .push(format!("invalid namespace expression {why}"));
293            }
294        }
295        if !query.include_drafts {
296            self.prs.retain(|p| p.pr.state != PullRequestState::Draft);
297        }
298        // ISO-8601 strings sort chronologically; newest first, stable.
299        self.prs
300            .sort_by(|a, b| b.pr.updated_at.cmp(&a.pr.updated_at));
301        self.issues
302            .sort_by(|a, b| b.issue.updated_at.cmp(&a.issue.updated_at));
303        let mut truncated = self.cut;
304        if self.prs.len() > limit {
305            let more = self.prs.len() - limit;
306            self.prs.truncate(limit);
307            self.notes.push(format!(
308                "{more} more pull/merge requests are not listed (limit {limit})"
309            ));
310            truncated = true;
311        }
312        if self.issues.len() > limit {
313            let more = self.issues.len() - limit;
314            self.issues.truncate(limit);
315            self.notes
316                .push(format!("{more} more issues are not listed (limit {limit})"));
317            truncated = true;
318        }
319        AccountItems {
320            prs: self.prs,
321            issues: self.issues,
322            truncated,
323            notes: self.notes,
324        }
325    }
326}
327
328/// How one paged account query is bounded.
329pub(crate) struct Paging<'a> {
330    /// The query parameter that carries the page size (`per_page`, `limit`).
331    pub size_param: &'a str,
332    pub page_size: usize,
333    pub max_pages: usize,
334    /// Stop once this many rows are in hand.
335    pub max_rows: usize,
336}
337
338/// Fetches pages of `url` until a short page, the
339/// page cap or the row cap. `rows` pulls one page's rows out of the response.
340pub(crate) async fn get_rows<T>(
341    transport: &dyn HttpTransport,
342    request: &(dyn Fn(String) -> HttpRequest + Sync),
343    url: &str,
344    paging: &Paging<'_>,
345    what: &str,
346    rows: &(dyn Fn(&HttpResponse) -> Result<Vec<T>> + Sync),
347) -> Result<Vec<T>> {
348    let sep = if url.contains('?') { '&' } else { '?' };
349    let mut out = Vec::new();
350    for page in 1..=paging.max_pages {
351        let full = format!(
352            "{url}{sep}{}={}&page={page}",
353            paging.size_param, paging.page_size
354        );
355        let response = transport.send(request(full)).await?;
356        response.error_for_status(what)?;
357        let page_rows = rows(&response)?;
358        let count = page_rows.len();
359        out.extend(page_rows);
360        if count < paging.page_size || out.len() >= paging.max_rows {
361            break;
362        }
363    }
364    Ok(out)
365}