fix(issues): Gitea issue sync lists once per scan and keeps at most two requests in flight per instance #548

Merged
sharang merged 1 commits from fix/gitea-issue-sync-load into main 2026-10-09 14:25:30 +00:00
7 changed files with 768 additions and 252 deletions

No files matched your search

+5
View File
@@ -112,6 +112,11 @@ impl RepoLister for SourceClient {
self.base_url,
urlencoding::encode(org)
);
// One of the instance's two request slots, shared with the issue
// tracker, held until the page has been read.
let _permit = crate::trackers::gitea_limit::acquire(&self.base_url)
.await
.map_err(|e| AgentError::Other(format!("Gitea request slot: {e}")))?;
let resp = self
.http
.get(&url)
+9 -1
View File
@@ -421,7 +421,15 @@ mod tests {
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
async fn labels(
axum::extract::Query(page): axum::extract::Query<
std::collections::HashMap<String, String>,
>,
) -> Json<serde_json::Value> {
// One page of labels: a later page is empty, as Gitea ends a list.
if page.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
+212 -24
View File
@@ -1,6 +1,9 @@
use std::collections::HashMap;
use mongodb::bson::doc;
use crate::pipeline::repo_view::RepoView;
use crate::trackers::gitea::GiteaIssue;
use compliance_core::models::*;
use super::orchestrator::{extract_base_url, PipelineOrchestrator};
@@ -58,7 +61,9 @@ impl PipelineOrchestrator {
}
/// Create tracker issues for new findings (severity >= Medium).
/// Checks for duplicates via fingerprint search before creating.
/// Skips a finding whose issue exists (by fingerprint, then title): on
/// Gitea matched against one listing of the repository's issues, on other
/// trackers by a search per finding.
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub(super) async fn create_tracker_issues(
&self,
@@ -115,6 +120,18 @@ impl PipelineOrchestrator {
tracker.name()
);
// A Gitea lists its issues once and the findings are matched here, not
// searched one by one (a burst of searches took a small instance
// down). A listing that fails stops the sync for this repository;
// the next scan tries again.
let mut existing = match &tracker {
TrackerDispatch::Gitea(gitea) => {
let issues = gitea.list_issues(owner, tracker_repo_name).await?;
Some(ExistingIssues::new(&issues))
}
_ => None,
};
// A managed repository (#439) gets its labels created once per run
// and attached by id. If that fails (no permission), the issues are
// still opened, with the label names in the body as before.
@@ -142,28 +159,17 @@ impl PipelineOrchestrator {
let title = issue_title(finding);
// Check if an issue already exists by fingerprint first, then by title
let mut found_existing = false;
for search_term in issue_search_terms(finding, &title) {
match tracker
.find_existing_issue(owner, tracker_repo_name, search_term)
let found_existing = match &existing {
Some(index) => index.find(finding, &title).map(str::to_string),
None => search_existing(&tracker, owner, tracker_repo_name, finding, &title)
.await
{
Ok(Some(existing)) => {
tracing::debug!(
"[{repo_id}] Issue already exists for '{}': {}",
search_term,
existing.external_url
);
found_existing = true;
break;
}
Ok(None) => {}
Err(e) => {
tracing::warn!("[{repo_id}] Failed to search for existing issue: {e}");
}
}
}
if found_existing {
.map(|issue| issue.external_url),
};
if let Some(url) = found_existing {
tracing::debug!(
"[{repo_id}] Issue already exists for '{}': {url}",
finding.fingerprint
);
continue;
}
let mut body = format_issue_body(finding);
@@ -222,6 +228,11 @@ impl PipelineOrchestrator {
.await;
}
// Later findings of this run with the same title find it.
if let Some(index) = existing.as_mut() {
index.insert(&finding.fingerprint, &title, &issue.external_url);
}
// Store the tracker issue record
if let Err(e) = self.db.tracker_issues().insert_one(&issue).await {
tracing::warn!("[{repo_id}] Failed to store tracker issue: {e}");
@@ -324,6 +335,95 @@ pub(crate) fn build_tracker(
}
}
/// Search the tracker for a finding's issue, one search per term of
/// [`issue_search_terms`] (trackers other than Gitea). A failed search is
/// logged and counts as not found.
async fn search_existing(
tracker: &TrackerDispatch,
owner: &str,
repo: &str,
finding: &Finding,
title: &str,
) -> Option<TrackerIssue> {
for search_term in issue_search_terms(finding, title) {
match tracker.find_existing_issue(owner, repo, search_term).await {
Ok(Some(existing)) => return Some(existing),
Ok(None) => {}
Err(e) => tracing::warn!("Failed to search for existing issue: {e}"),
}
}
None
}
/// The marker a finding issue's body carries its fingerprint in, right
/// before the fingerprint and its closing backtick.
const FINGERPRINT_MARKER: &str = "*Fingerprint:* `";
/// The fingerprint in an issue body written by [`format_issue_body`].
fn body_fingerprint(body: &str) -> Option<&str> {
let start = body.find(FINGERPRINT_MARKER)? + FINGERPRINT_MARKER.len();
let rest = &body[start..];
rest.find('`')
.map(|end| &rest[..end])
.filter(|fp| !fp.is_empty())
}
/// The issues a repository already has, by fingerprint and by title, built
/// from one listing so each finding is matched without a request.
#[derive(Debug, Default)]
struct ExistingIssues {
/// Fingerprint (from the body's marker) to issue URL.
by_fingerprint: HashMap<String, String>,
/// Exact title to issue URL.
by_title: HashMap<String, String>,
}
impl ExistingIssues {
/// Index `issues`; where two share a fingerprint or title, the first
/// listed (Gitea lists the newest first) wins.
fn new(issues: &[GiteaIssue]) -> Self {
let mut index = Self::default();
for issue in issues {
if let Some(fp) = issue.body.as_deref().and_then(body_fingerprint) {
index
.by_fingerprint
.entry(fp.to_string())
.or_insert_with(|| issue.html_url.clone());
}
index
.by_title
.entry(issue.title.clone())
.or_insert_with(|| issue.html_url.clone());
}
index
}
/// The URL of `finding`'s issue: by fingerprint, then by `title` (not
/// for a group, see [`issue_search_terms`]).
fn find(&self, finding: &Finding, title: &str) -> Option<&str> {
self.by_fingerprint
.get(&finding.fingerprint)
.or_else(|| {
finding
.occurrences
.is_empty()
.then(|| self.by_title.get(title))
.flatten()
})
.map(String::as_str)
}
/// Add an issue opened during this run.
fn insert(&mut self, fingerprint: &str, title: &str, url: &str) {
self.by_fingerprint
.entry(fingerprint.to_string())
.or_insert_with(|| url.to_string());
self.by_title
.entry(title.to_string())
.or_insert_with(|| url.to_string());
}
}
/// What to search the tracker for to find a finding's issue: its
/// fingerprint, then its title. A group (#464) only by fingerprint: it has
/// the title of its rule's single findings, whose issues are being closed as
@@ -403,7 +503,7 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
}
body.push_str(&format!(
"\n---\n*Fingerprint:* `{}`\n*Generated by compliance-scanner*",
"\n---\n{FINGERPRINT_MARKER}{}`\n*Generated by compliance-scanner*",
finding.fingerprint
));
@@ -442,7 +542,7 @@ fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
/// The ids of `names` among the ensured labels; a name without an id is left
/// out.
fn label_ids(ids: &std::collections::HashMap<String, i64>, names: &[String]) -> Vec<i64> {
fn label_ids(ids: &HashMap<String, i64>, names: &[String]) -> Vec<i64> {
names.iter().filter_map(|n| ids.get(n).copied()).collect()
}
@@ -531,6 +631,94 @@ mod tests {
);
}
fn listed(number: i64, title: &str, body: Option<&str>) -> GiteaIssue {
GiteaIssue {
number,
title: title.into(),
body: body.map(str::to_string),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
}
}
fn high(fingerprint: &str, title: &str) -> Finding {
Finding::new(
"r".into(),
fingerprint.into(),
"semgrep".into(),
ScanType::Sast,
title.into(),
"desc".into(),
Severity::High,
)
}
#[test]
fn the_fingerprint_is_read_back_from_the_body() {
let body = format_issue_body(&high("fp-abc", "SQL injection"));
assert_eq!(body_fingerprint(&body), Some("fp-abc"));
assert_eq!(body_fingerprint("no marker"), None);
assert_eq!(body_fingerprint("*Fingerprint:* `"), None);
}
#[test]
fn an_issue_is_matched_by_its_fingerprint_marker() {
let finding = high("fp-1", "SQL injection");
let body = format_issue_body(&finding);
// Another title: the scanner renamed the rule since.
let index = ExistingIssues::new(&[
listed(3, "something else", Some("text")),
listed(7, "[high] semgrep: old name", Some(&body)),
]);
assert_eq!(
index.find(&finding, &issue_title(&finding)),
Some("https://gitea.invalid/o/r/issues/7")
);
}
#[test]
fn an_issue_without_the_marker_is_matched_by_title_unless_grouped() {
let finding = high("fp-2", "SQL injection");
let title = issue_title(&finding);
let index = ExistingIssues::new(&[listed(4, &title, None)]);
assert_eq!(
index.find(&finding, &title),
Some("https://gitea.invalid/o/r/issues/4")
);
// A group is found by its fingerprint only.
let mut group = finding.clone();
group.occurrences = (1..=2)
.map(|line| Occurrence {
file: "a.rs".into(),
line: Some(line),
variant: None,
decision: None,
})
.collect();
assert_eq!(index.find(&group, &title), None);
}
#[test]
fn no_match_means_a_new_issue_and_it_is_found_afterwards() {
let first = high("fp-3", "Hardcoded key");
let title = issue_title(&first);
let mut index = ExistingIssues::new(&[listed(1, "[high] semgrep: other", Some("x"))]);
assert_eq!(index.find(&first, &title), None);
// Opened during this run: the next finding with that title (or the
// same fingerprint) is not opened twice.
index.insert(
&first.fingerprint,
&title,
"https://gitea.invalid/o/r/issues/9",
);
let same_title = high("fp-4", "Hardcoded key");
assert_eq!(
index.find(&same_title, &title),
Some("https://gitea.invalid/o/r/issues/9")
);
assert!(index.find(&first, "another title").is_some());
}
#[test]
fn a_variant_is_in_the_title_and_the_body() {
let mut finding = Finding::new(
+90 -14
View File
@@ -7,6 +7,9 @@
//! reopens its issue. The sync reads each finding's status when it runs, so a
//! change made in between is the one carried over.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::models::{
@@ -78,8 +81,9 @@ impl IssueSync {
return;
}
tokio::spawn(async move {
let mut risk_labels = RiskLabels::new();
for id in ids {
if let Err(e) = self.sync_one(id).await {
if let Err(e) = self.sync_one(id, &mut risk_labels).await {
tracing::warn!(finding = %id, error = %e, "issue status not synced");
}
}
@@ -87,7 +91,10 @@ impl IssueSync {
}
/// Carry the status of finding `id` over to its issue, if it has one.
async fn sync_one(&self, id: ObjectId) -> Result<(), String> {
/// `risk_labels` keeps the `risk:accepted` label id of each target this
/// run has resolved, so the labels are listed once per target, not once
/// per issue.
async fn sync_one(&self, id: ObjectId, risk_labels: &mut RiskLabels) -> Result<(), String> {
let Some(issue) = self
.db
.tracker_issues()
@@ -138,7 +145,14 @@ impl IssueSync {
accepted_risk: true,
} = action
{
label_accepted_risk(&tracker, owner, name, number).await;
label_accepted_risk(
&tracker,
owner,
name,
number,
risk_labels.entry(finding.repo_id.clone()),
)
.await;
}
let (state, status) = match action {
IssueAction::Close { .. } => ("closed", IssueStatus::Closed),
@@ -169,17 +183,34 @@ impl IssueSync {
}
}
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
/// resolved; `None` for a target whose repository has no such label.
type RiskLabels = HashMap<String, Option<i64>>;
/// Put the `risk:accepted` label on a Gitea issue. Other trackers keep only
/// the comment; a label that cannot be set does not stop the close.
async fn label_accepted_risk(tracker: &TrackerDispatch, owner: &str, repo: &str, number: &str) {
/// the comment; a label that cannot be set does not stop the close. The
/// label id is resolved once per target and kept in `cached`.
async fn label_accepted_risk(
tracker: &TrackerDispatch,
owner: &str,
repo: &str,
number: &str,
cached: Entry<'_, String, Option<i64>>,
) {
let TrackerDispatch::Gitea(gitea) = tracker else {
return;
};
let labelled = async {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
let label: Vec<i64> = ids.get(LABEL_ACCEPTED_RISK).copied().into_iter().collect();
let label = match cached {
Entry::Occupied(known) => *known.get(),
Entry::Vacant(slot) => {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
*slot.insert(ids.get(LABEL_ACCEPTED_RISK).copied())
}
};
let label: Vec<i64> = label.into_iter().collect();
gitea.add_labels(owner, repo, number, &label).await
};
if let Err(e) = labelled.await {
@@ -261,7 +292,17 @@ mod tests {
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
async fn labels(
State(calls): State<Calls>,
axum::extract::Query(page): axum::extract::Query<
std::collections::HashMap<String, String>,
>,
) -> Json<serde_json::Value> {
// One page of labels: a later page is empty, as Gitea ends a list.
if page.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
calls.lock().unwrap().push("list labels".into());
// Every Prüfwerk label exists already; risk:accepted is id 42.
Json(serde_json::json!(pruefwerk_labels()
.iter()
@@ -395,7 +436,9 @@ mod tests {
};
// Act + assert: the scan closed it, so the issue closes with a comment.
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Closed);
{
let calls = calls.lock().unwrap();
@@ -405,7 +448,9 @@ mod tests {
}
// Synced again with no change: nothing more is sent.
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(calls.lock().unwrap().len(), 2);
// It comes back: the issue reopens.
@@ -416,7 +461,9 @@ mod tests {
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 12: \"open\"");
@@ -428,7 +475,9 @@ mod tests {
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
{
let calls = calls.lock().unwrap();
let tail: Vec<&str> = calls.iter().rev().take(2).map(String::as_str).collect();
@@ -438,6 +487,33 @@ mod tests {
pool.drop_tenant("issue-sync").await.ok();
}
#[tokio::test]
async fn the_risk_label_is_resolved_once_per_target() {
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
let tracker = TrackerDispatch::Gitea(
crate::trackers::gitea::GiteaTracker::new(
base,
secrecy::SecretString::from("t"),
NetGuard::allow_private(),
)
.unwrap(),
);
let mut cache = RiskLabels::new();
for number in ["5", "6"] {
label_accepted_risk(&tracker, "kunde", "fw", number, cache.entry("t1".into())).await;
}
let calls = calls.lock().unwrap();
assert_eq!(
*calls,
["list labels", "labels 5: [42]", "labels 6: [42]"],
"the labels are listed once"
);
assert_eq!(cache["t1"], Some(42));
}
fn by_scan(status: FindingStatus, kind: ScanChangeKind) -> StatusChange {
StatusChange::by_scan(status, kind, "run-1")
}
+356 -213
View File
@@ -5,7 +5,11 @@ use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::models::{TrackerIssue, TrackerType};
use compliance_core::traits::issue_tracker::{IssueTracker, ReviewComment};
use compliance_core::NetGuard;
use reqwest::StatusCode;
use secrecy::{ExposeSecret, SecretString};
use serde::de::DeserializeOwned;
use crate::trackers::gitea_limit;
pub struct GiteaTracker {
base_url: String,
@@ -42,6 +46,104 @@ impl GiteaTracker {
format!("token {}", self.token.expose_secret())
}
/// Send `request` with the bot token once the instance has a free slot
/// (see [`gitea_limit`]), and read the whole answer before giving the slot
/// back: Gitea is still working while it streams the body.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] naming `what` if Gitea cannot be reached.
/// An error status is returned as the status, not as an error.
async fn send_raw(
&self,
what: &str,
request: reqwest::RequestBuilder,
) -> Result<(StatusCode, String), CoreError> {
let _permit = gitea_limit::acquire(&self.base_url)
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what}: {e}")))?;
let resp = request
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what} failed: {e}")))?;
let status = resp.status();
let text = resp
.text()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what} failed: {e}")))?;
Ok((status, text))
}
/// [`Self::send_raw`], with an error status turned into an error.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if Gitea cannot be reached or answers with
/// an error status.
async fn send(
&self,
what: &str,
request: reqwest::RequestBuilder,
) -> Result<String, CoreError> {
let (status, text) = self.send_raw(what, request).await?;
if status.is_success() {
Ok(text)
} else {
Err(CoreError::IssueTracker(format!(
"Gitea {what} returned {status}: {text}"
)))
}
}
/// [`Self::send`], with the answer parsed as JSON.
///
/// # Errors
///
/// As [`Self::send`], and [`CoreError::IssueTracker`] if the answer is not
/// the expected JSON.
async fn send_json<T: DeserializeOwned>(
&self,
what: &str,
request: reqwest::RequestBuilder,
) -> Result<T, CoreError> {
let text = self.send(what, request).await?;
serde_json::from_str(&text)
.map_err(|e| CoreError::IssueTracker(format!("Failed to parse Gitea {what}: {e}")))
}
/// Every page of a list endpoint, `path` being the URL without `page` and
/// `limit`. Only an empty page ends the list: an instance may cap the page
/// size below ours (`[api] MAX_RESPONSE_ITEMS`).
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if a page cannot be fetched or parsed, or
/// the list has more than `max_pages` pages (a partial list would let a
/// caller take a missing entry for an absent one).
async fn list_all<T: DeserializeOwned>(
&self,
what: &str,
path: &str,
max_pages: usize,
) -> Result<Vec<T>, CoreError> {
let separator = if path.contains('?') { '&' } else { '?' };
let mut all = Vec::new();
for page in 1..=max_pages {
let url = self.api_url(&format!(
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
));
let batch: Vec<T> = self.send_json(what, self.http.get(&url)).await?;
if batch.is_empty() {
return Ok(all);
}
all.extend(batch);
}
Err(CoreError::IssueTracker(format!(
"Gitea {what}: more than {max_pages} pages"
)))
}
/// Every label of a repository, all pages.
///
/// # Errors
@@ -49,35 +151,29 @@ impl GiteaTracker {
/// [`CoreError::IssueTracker`] if Gitea cannot be asked or answers with an
/// error.
pub async fn list_labels(&self, owner: &str, repo: &str) -> Result<Vec<GiteaLabel>, CoreError> {
let mut labels = Vec::new();
for page in 1..=MAX_LABEL_PAGES {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/labels?page={page}&limit={LABEL_PAGE_SIZE}"
));
let resp = self
.http
.get(&url)
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea list labels failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
return Err(CoreError::IssueTracker(format!(
"Gitea list labels returned {status}"
)));
}
let batch: Vec<GiteaLabel> = resp.json().await.map_err(|e| {
CoreError::IssueTracker(format!("Failed to parse Gitea labels: {e}"))
})?;
// Only an empty page ends the list (the instance may cap the
// page size below ours).
if batch.is_empty() {
break;
}
labels.extend(batch);
}
Ok(labels)
self.list_all(
"list labels",
&format!("/repos/{owner}/{repo}/labels"),
MAX_LABEL_PAGES,
)
.await
}
/// Every issue of a repository, open and closed, all pages: one listing
/// per sync, matched locally, instead of a search per finding.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if any page cannot be fetched (the caller
/// must not take a failed listing for an empty one) or the repository has
/// more than `MAX_ISSUE_PAGES` pages of issues.
pub async fn list_issues(&self, owner: &str, repo: &str) -> Result<Vec<GiteaIssue>, CoreError> {
self.list_all(
"list issues",
&format!("/repos/{owner}/{repo}/issues?type=issues&state=all"),
MAX_ISSUE_PAGES,
)
.await
}
/// Make sure the repository has every label in `wanted`, creating the
@@ -99,29 +195,16 @@ impl GiteaTracker {
existing.iter().map(|l| (l.name.clone(), l.id)).collect();
for spec in missing_labels(&existing, wanted) {
let url = self.api_url(&format!("/repos/{owner}/{repo}/labels"));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&serde_json::json!({
"name": spec.name,
"color": spec.color,
"description": spec.description,
}))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea create label failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
return Err(CoreError::IssueTracker(format!(
"Gitea create label '{}' returned {status}",
spec.name
)));
}
let label: GiteaLabel = resp.json().await.map_err(|e| {
CoreError::IssueTracker(format!("Failed to parse Gitea label: {e}"))
})?;
let request = self.http.post(&url).json(&serde_json::json!({
"name": spec.name,
"color": spec.color,
"description": spec.description,
}));
let label: GiteaLabel = self
.send_json(&format!("create label '{}'", spec.name), request)
.await?;
ids.insert(label.name, label.id);
tokio::time::sleep(gitea_limit::CREATE_PAUSE).await;
}
Ok(ids)
}
@@ -141,21 +224,14 @@ impl GiteaTracker {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{external_id}/labels"
));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&serde_json::json!({ "labels": label_ids }))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea add labels failed: {e}")))?;
if !resp.status().is_success() {
return Err(CoreError::IssueTracker(format!(
"Gitea add labels returned {}",
resp.status()
)));
}
Ok(())
self.send(
"add labels",
self.http
.post(&url)
.json(&serde_json::json!({ "labels": label_ids })),
)
.await
.map(drop)
}
/// Create an issue with the given labels attached by id (see
@@ -181,6 +257,8 @@ impl GiteaTracker {
.await
}
/// Create an issue from `payload`, then pause for
/// [`gitea_limit::CREATE_PAUSE`] (after giving the request slot back).
async fn post_issue(
&self,
owner: &str,
@@ -189,28 +267,10 @@ impl GiteaTracker {
payload: serde_json::Value,
) -> Result<TrackerIssue, CoreError> {
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues"));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&payload)
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea create issue failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
return Err(CoreError::IssueTracker(format!(
"Gitea returned {status}: {text}"
)));
}
let issue: serde_json::Value = resp
.json()
.await
.map_err(|e| CoreError::IssueTracker(format!("Failed to parse Gitea response: {e}")))?;
let issue: serde_json::Value = self
.send_json("create issue", self.http.post(&url).json(&payload))
.await?;
tokio::time::sleep(gitea_limit::CREATE_PAUSE).await;
Ok(TrackerIssue::new(
String::new(),
TrackerType::Gitea,
@@ -221,10 +281,24 @@ impl GiteaTracker {
}
}
/// Labels per page when listing a repository's labels.
const LABEL_PAGE_SIZE: usize = 50;
/// Entries per page when listing labels or issues.
const LIST_PAGE_SIZE: usize = 50;
/// Upper bound on label pages, so a misbehaving server cannot loop us.
const MAX_LABEL_PAGES: usize = 20;
/// Upper bound on issue pages (10 000 issues).
const MAX_ISSUE_PAGES: usize = 200;
/// An issue as Gitea lists it, with what an issue is matched by.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct GiteaIssue {
pub number: i64,
pub title: String,
/// Gitea sends `null` or leaves it out for an issue without text.
#[serde(default)]
pub body: Option<String>,
#[serde(default)]
pub html_url: String,
}
/// A repository label as Gitea returns it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
@@ -355,33 +429,18 @@ impl IssueTracker for GiteaTracker {
status: &str,
) -> Result<(), CoreError> {
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues/{external_id}"));
let state = match status {
"closed" | "resolved" => "closed",
_ => "open",
};
let resp = self
.http
.patch(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.json(&serde_json::json!({ "state": state }))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea update issue failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
return Err(CoreError::IssueTracker(format!(
"Gitea update issue returned {status}: {text}"
)));
}
Ok(())
self.send(
"update issue",
self.http
.patch(&url)
.json(&serde_json::json!({ "state": state })),
)
.await
.map(drop)
}
async fn add_comment(
@@ -394,28 +453,14 @@ impl IssueTracker for GiteaTracker {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{external_id}/comments"
));
let resp = self
.http
.post(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.json(&serde_json::json!({ "body": body }))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea add comment failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
return Err(CoreError::IssueTracker(format!(
"Gitea add comment returned {status}: {text}"
)));
}
Ok(())
self.send(
"add comment",
self.http
.post(&url)
.json(&serde_json::json!({ "body": body })),
)
.await
.map(drop)
}
async fn create_pr_review(
@@ -439,65 +484,40 @@ impl IssueTracker for GiteaTracker {
})
.collect();
let resp = self
.http
.post(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
let (status, text) = self
.send_raw(
"PR review",
self.http.post(&url).json(&serde_json::json!({
"body": body,
"event": "COMMENT",
"comments": review_comments,
})),
)
.json(&serde_json::json!({
"body": body,
"event": "COMMENT",
"comments": review_comments,
}))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea PR review failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
// If inline comments caused the failure, retry with just the summary body
if !comments.is_empty() {
tracing::warn!(
"Gitea PR review with inline comments failed ({status}): {text}, retrying as plain comment"
);
let fallback_url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{pr_number}/comments"
));
let fallback_resp = self
.http
.post(&fallback_url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.json(&serde_json::json!({ "body": body }))
.send()
.await
.map_err(|e| {
CoreError::IssueTracker(format!("Gitea PR comment fallback failed: {e}"))
})?;
if !fallback_resp.status().is_success() {
let fb_status = fallback_resp.status();
let fb_text = fallback_resp.text().await.unwrap_or_default();
return Err(CoreError::IssueTracker(format!(
"Gitea PR comment fallback returned {fb_status}: {fb_text}"
)));
}
return Ok(());
}
.await?;
if status.is_success() {
return Ok(());
}
if comments.is_empty() {
return Err(CoreError::IssueTracker(format!(
"Gitea PR review returned {status}: {text}"
)));
}
Ok(())
// If inline comments caused the failure, retry with just the summary body
tracing::warn!(
"Gitea PR review with inline comments failed ({status}): {text}, retrying as plain comment"
);
let fallback_url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{pr_number}/comments"
));
self.send(
"PR comment fallback",
self.http
.post(&fallback_url)
.json(&serde_json::json!({ "body": body })),
)
.await
.map(drop)
}
async fn find_existing_issue(
@@ -506,33 +526,23 @@ impl IssueTracker for GiteaTracker {
repo: &str,
fingerprint: &str,
) -> Result<Option<TrackerIssue>, CoreError> {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues?type=issues&state=all&q={fingerprint}"
));
let resp = self
.http
.get(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea search failed: {e}")))?;
let issues: Vec<serde_json::Value> = resp.json().await.unwrap_or_default();
if let Some(issue) = issues.first() {
Ok(Some(TrackerIssue::new(
// The finding issues are matched against `list_issues` instead; this
// search stays for the trait.
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues"));
let request =
self.http
.get(&url)
.query(&[("type", "issues"), ("state", "all"), ("q", fingerprint)]);
let issues: Vec<GiteaIssue> = self.send_json("search issues", request).await?;
Ok(issues.into_iter().next().map(|issue| {
TrackerIssue::new(
String::new(),
TrackerType::Gitea,
issue["number"].to_string(),
issue["html_url"].as_str().unwrap_or("").to_string(),
issue["title"].as_str().unwrap_or("").to_string(),
)))
} else {
Ok(None)
}
issue.number.to_string(),
issue.html_url,
issue.title,
)
}))
}
}
@@ -597,7 +607,14 @@ mod tests {
async fn list(
State(labels): State<Labels>,
Path((_o, _r)): Path<(String, String)>,
axum::extract::Query(page): axum::extract::Query<
std::collections::HashMap<String, String>,
>,
) -> Json<serde_json::Value> {
// One page of labels: a later page is empty, as Gitea ends a list.
if page.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
let all = labels.lock().unwrap().clone();
Json(serde_json::json!(all
.iter()
@@ -649,4 +666,130 @@ mod tests {
assert_eq!(again, ids);
assert_eq!(labels.lock().unwrap().len(), 8);
}
/// The query strings a fake Gitea saw.
type Seen = Arc<Mutex<Vec<String>>>;
/// A fake Gitea whose repository has `total` issues, served in pages of
/// at most `cap` (an instance may cap the page size below ours).
async fn fake_issues(total: i64, cap: i64, seen: Seen) -> String {
async fn list(
State((total, cap, seen)): State<(i64, i64, Seen)>,
Path((_o, _r)): Path<(String, String)>,
axum::extract::RawQuery(query): axum::extract::RawQuery,
axum::extract::Query(params): axum::extract::Query<HashMap<String, String>>,
) -> Json<serde_json::Value> {
seen.lock().unwrap().push(query.unwrap_or_default());
let page: i64 = params["page"].parse().unwrap();
let limit: i64 = params["limit"].parse::<i64>().unwrap().min(cap);
let first = (page - 1) * limit + 1;
Json(serde_json::json!((first..=(first + limit - 1).min(total))
.map(|n| serde_json::json!({
"number": n,
"title": format!("issue {n}"),
"body": if n % 2 == 0 { serde_json::Value::Null } else { format!("body {n}").into() },
"html_url": format!("https://gitea.invalid/o/r/issues/{n}"),
}))
.collect::<Vec<_>>()))
}
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/issues", get(list))
.with_state((total, cap, seen));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn list_issues_reads_every_page_of_open_and_closed_issues() {
let seen: Seen = Arc::default();
let base = fake_issues(103, 50, seen.clone()).await;
let tracker =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let issues = tracker.list_issues("kunde", "fw").await.unwrap();
assert_eq!(issues.len(), 103);
assert_eq!(issues[0].body.as_deref(), Some("body 1"));
assert_eq!(issues[1].body, None);
assert_eq!(issues[102].number, 103);
let seen = seen.lock().unwrap();
assert_eq!(seen.len(), 4, "three pages and the empty one: {seen:?}");
assert_eq!(seen[0], "type=issues&state=all&page=1&limit=50");
assert_eq!(seen[3], "type=issues&state=all&page=4&limit=50");
}
#[tokio::test]
async fn list_issues_does_not_stop_at_a_capped_page() {
let seen: Seen = Arc::default();
let base = fake_issues(45, 20, seen.clone()).await;
let tracker =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
assert_eq!(tracker.list_issues("kunde", "fw").await.unwrap().len(), 45);
assert_eq!(seen.lock().unwrap().len(), 4);
}
#[tokio::test]
async fn a_failed_listing_is_an_error_not_an_empty_list() {
let app = Router::new().route(
"/api/v1/repos/{owner}/{repo}/issues",
get(|| async { axum::http::StatusCode::INTERNAL_SERVER_ERROR }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let tracker = GiteaTracker::new(
format!("http://{addr}"),
SecretString::from("t"),
NetGuard::allow_private(),
)
.unwrap();
assert!(tracker.list_issues("kunde", "fw").await.is_err());
}
#[tokio::test]
async fn never_more_than_two_requests_in_flight_per_instance() {
use std::sync::atomic::{AtomicUsize, Ordering};
/// Requests being served now, and the most at any one time.
type Gauge = Arc<(AtomicUsize, AtomicUsize)>;
async fn slow(State(gauge): State<Gauge>) -> Json<serde_json::Value> {
let now = gauge.0.fetch_add(1, Ordering::SeqCst) + 1;
gauge.1.fetch_max(now, Ordering::SeqCst);
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
gauge.0.fetch_sub(1, Ordering::SeqCst);
Json(serde_json::json!([]))
}
let gauge: Gauge = Arc::default();
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/labels", get(slow))
.with_state(gauge.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let base = format!("http://{addr}");
// Two trackers of the same instance, as two scans would build them.
let trackers: Vec<GiteaTracker> = (0..2)
.map(|_| {
GiteaTracker::new(
base.clone(),
SecretString::from("t"),
NetGuard::allow_private(),
)
.unwrap()
})
.collect();
let calls = (0..10).map(|i| trackers[i % 2].list_labels("kunde", "fw"));
let results = futures_util::future::join_all(calls).await;
assert!(results.iter().all(Result::is_ok));
let most = gauge.1.load(Ordering::SeqCst);
assert_eq!(
most,
gitea_limit::MAX_IN_FLIGHT,
"at most two, and two did run at once"
);
}
}
@@ -0,0 +1,95 @@
//! At most [`MAX_IN_FLIGHT`] requests in flight per Gitea instance.
//!
//! A managed Gitea is often small (one with 1 GiB was OOM-killed by a burst
//! of issue searches, K-00001). Every request the agent makes to a Gitea, from
//! the issue tracker and from the managed git source alike, first takes a
//! permit of its instance here, so all scans of one instance in this process
//! share the same two slots.
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use dashmap::DashMap;
use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore};
/// Requests one Gitea instance gets from this process at the same time.
pub const MAX_IN_FLIGHT: usize = 2;
/// The pause after creating something (an issue, a label), so a sync that
/// opens many issues does not hit the instance back to back.
pub const CREATE_PAUSE: Duration = Duration::from_millis(250);
/// One semaphore per instance, keyed by [`instance_key`]. A `LazyLock` is
/// initialised on first use, like a module-level singleton in Python.
static LIMITERS: LazyLock<DashMap<String, Arc<Semaphore>>> = LazyLock::new(DashMap::new);
/// The instance a base URL points at: `host:port`, lower case, so
/// `https://Git.example.com` and `https://git.example.com:443/sub` share one
/// limit while two instances on one host with different ports do not. A URL
/// that cannot be parsed is its own key.
pub fn instance_key(base_url: &str) -> String {
match reqwest::Url::parse(base_url) {
Ok(url) => match url.host_str() {
Some(host) => format!(
"{}:{}",
host.to_ascii_lowercase(),
url.port_or_known_default().unwrap_or_default()
),
None => base_url.to_ascii_lowercase(),
},
Err(_) => base_url.trim_end_matches('/').to_ascii_lowercase(),
}
}
/// Wait for a request slot at the instance of `base_url`. Hold the permit
/// until the response body has been read; dropping it frees the slot.
///
/// # Errors
///
/// [`AcquireError`] only if the semaphore was closed, which this module never
/// does.
pub async fn acquire(base_url: &str) -> Result<OwnedSemaphorePermit, AcquireError> {
// Clone the `Arc` out of the map first: the map's entry guard must not be
// held across the `.await` below.
let semaphore = LIMITERS
.entry(instance_key(base_url))
.or_insert_with(|| Arc::new(Semaphore::new(MAX_IN_FLIGHT)))
.clone();
semaphore.acquire_owned().await
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn one_key_per_host_and_port() {
assert_eq!(
instance_key("https://Git.Example.com"),
"git.example.com:443"
);
assert_eq!(
instance_key("https://git.example.com:443/sub/"),
"git.example.com:443"
);
assert_eq!(instance_key("http://127.0.0.1:3000"), "127.0.0.1:3000");
assert_ne!(
instance_key("http://127.0.0.1:3000"),
instance_key("http://127.0.0.1:3001")
);
assert_eq!(instance_key("not a url/"), "not a url");
}
#[tokio::test]
async fn a_third_permit_waits_for_one_of_the_first_two() {
let base = "https://limit-test.invalid";
let first = acquire(base).await.unwrap();
let _second = acquire(base).await.unwrap();
let third = tokio::time::timeout(Duration::from_millis(50), acquire(base)).await;
assert!(third.is_err(), "a third request must wait");
drop(first);
let third = tokio::time::timeout(Duration::from_millis(50), acquire(base)).await;
assert!(third.is_ok(), "a freed slot is taken");
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod gitea;
pub mod gitea_limit;
pub mod github;
pub mod gitlab;
pub mod jira;