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