Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/actuator/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod github;
pub mod ntfy;
pub mod revue;
75 changes: 75 additions & 0 deletions src/actuator/revue.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use anyhow::{Context, Result};
use reqwest::Url;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;
use tracing::{info, warn};

const MAX_INFLIGHT_TRIGGERS: usize = 16;

#[derive(Clone)]
pub struct RevueClient {
client: reqwest::Client,
base_url: String,
token: Option<String>,
permits: Arc<Semaphore>,
}

fn is_loopback_host(host: &str) -> bool {
matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]")
}

impl RevueClient {
pub fn new(base_url: String, token: Option<String>) -> Result<Self> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let parsed = Url::parse(&base_url)
.with_context(|| format!("invalid CR_STEWARD_REVUE_URL: {base_url}"))?;
let host = parsed.host_str().unwrap_or("");
match parsed.scheme() {
"https" => {}
"http" if is_loopback_host(host) => {}
scheme => anyhow::bail!(
"refusing non-HTTPS revue URL ({scheme}://{host}); HTTP is allowed only for loopback hosts"
),
}
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()?;
Ok(Self {
client,
base_url: base_url.trim_end_matches('/').to_string(),
token,
permits: Arc::new(Semaphore::new(MAX_INFLIGHT_TRIGGERS)),
})
}

/// Dispatch a non-blocking advisory review request to `revue` (`POST /api/trigger`).
/// Returns `true` if accepted for dispatch, `false` if dropped due to backpressure.
pub fn trigger_advisory_review(&self, repo: &str, pr_number: u64, reason: &str) -> bool {
let Ok(permit) = self.permits.clone().try_acquire_owned() else {
warn!(repo, pr_number, "dropping revue trigger: too many in-flight requests");
return false;
};
let client = self.client.clone();
let url = format!("{}/api/trigger", self.base_url);
let token = self.token.clone();
let repo = repo.to_string();
let reason = reason.to_string();

tokio::spawn(async move {
let _permit = permit;
let mut req = client.post(&url).json(&serde_json::json!({
"repo": repo,
"pr": pr_number,
"reason": reason,
}));
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
match req.send().await.and_then(|r| r.error_for_status()) {
Ok(_) => info!(repo, pr_number, reason, "triggered advisory revue review"),
Err(err) => warn!(error = %err, repo, pr_number, reason, "failed to trigger revue"),
}
});
true
}
}
92 changes: 87 additions & 5 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::actuator::ntfy::NtfyClient;
use crate::actuator::revue::RevueClient;
use crate::budget::BudgetSnapshot;
use crate::config::Mode;
use crate::coverage::{self, CoverageSummary};
use crate::db::{Db, FindingRow, QueueRow, SpendRow};
use crate::ingest::webhook::{handle_webhook_event, verify_signature};
use crate::synthetic::split_full_repo_batches;
use axum::body::Bytes;
use axum::extract::{Path, Query, Request, State};
use axum::http::{HeaderMap, StatusCode, header};
Expand All @@ -25,6 +27,7 @@ pub struct AppState {
pub trust_authentik_header: bool,
pub webhook_secret: Option<String>,
pub ntfy: Option<NtfyClient>,
pub revue: Option<RevueClient>,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -84,6 +87,18 @@ pub struct PatchSettingsRequest {
pub mode: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct RevueCoverageFile {
pub path: String,
pub blob_sha: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct RevueCoverageReport {
pub commit_sha: String,
pub paths: Vec<RevueCoverageFile>,
}

pub fn build_router(state: AppState, web_dir: Option<PathBuf>) -> Router {
let protected = Router::new()
.route("/api/v1/budget", get(get_fleet_budget))
Expand All @@ -92,6 +107,10 @@ pub fn build_router(state: AppState, web_dir: Option<PathBuf>) -> Router {
.route("/api/v1/reviews", post(post_review_request))
.route("/api/v1/queue", get(get_queue))
.route("/api/v1/coverage/{owner}/{repo}", get(get_coverage))
.route(
"/api/v1/coverage/{owner}/{repo}/revue",
post(post_revue_coverage),
)
.route("/api/v1/findings", get(get_findings))
.route("/api/v1/findings/{id}", patch(patch_finding))
.route("/api/v1/settings", get(get_settings).patch(patch_settings))
Expand Down Expand Up @@ -186,8 +205,14 @@ async fn post_webhook(
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown");

let outcome = handle_webhook_event(&state.db, state.ntfy.as_ref(), event, &body)
.await
let outcome = handle_webhook_event(
&state.db,
state.ntfy.as_ref(),
state.revue.as_ref(),
event,
&body,
)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Expand Down Expand Up @@ -366,9 +391,47 @@ async fn post_review_request(
State(state): State<AppState>,
Json(req): Json<CreateReviewRequest>,
) -> Result<(StatusCode, Json<QueueRow>), (StatusCode, String)> {
let (kind, paths_json) = if req.full.unwrap_or(false) {
("full", None)
} else if let Some(paths) = req.paths {
if req.full.unwrap_or(false) {
let cov_files = state
.db
.list_file_coverage(&req.repo)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
let file_cap = state
.db
.list_repos()
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
.into_iter()
.find(|r| format!("{}/{}", r.owner, r.name) == req.repo)
.map(|r| usize::try_from(r.file_cap.max(1)).unwrap_or(50))
.unwrap_or(50);

let batches = split_full_repo_batches(&cov_files, file_cap);
if batches.is_empty() {
let row = state
.db
.enqueue_review(&req.repo, "full", None, None)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
return Ok((StatusCode::CREATED, Json(row)));
}
let batches_json: Vec<String> = batches
.into_iter()
.map(|b| {
let paths: Vec<String> = b.files.into_iter().map(|f| f.path).collect();
serde_json::to_string(&paths).unwrap_or_default()
})
.collect();
let row = state
.db
.enqueue_review_batches(&req.repo, "full", &batches_json)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
return Ok((StatusCode::CREATED, Json(row)));
}

let (kind, paths_json) = if let Some(paths) = req.paths {
("proactive", Some(serde_json::to_string(&paths).unwrap_or_default()))
} else {
("on-demand", None)
Expand Down Expand Up @@ -406,6 +469,25 @@ async fn get_coverage(
Ok(Json(coverage::summarize(&full, &files, Timestamp::now())))
}

async fn post_revue_coverage(
State(state): State<AppState>,
Path((owner, repo)): Path<(String, String)>,
Json(report): Json<RevueCoverageReport>,
) -> Result<Json<CoverageSummary>, (StatusCode, String)> {
let full = format!("{owner}/{repo}");
let reported: Vec<(String, Option<String>)> = report
.paths
.into_iter()
.map(|p| (p.path, p.blob_sha))
.collect();
let updated = state
.db
.apply_revue_coverage(&full, &report.commit_sha, &reported)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(Json(coverage::summarize(&full, &updated, Timestamp::now())))
}

async fn get_findings(
State(state): State<AppState>,
Query(q): Query<FindingsQuery>,
Expand Down
4 changes: 4 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ pub struct Config {
pub github_api_base: String,
pub ntfy_url: Option<String>,
pub ntfy_token: Option<String>,
pub revue_url: Option<String>,
pub revue_token: Option<String>,
}

impl Default for Config {
Expand All @@ -66,6 +68,8 @@ impl Default for Config {
github_api_base: "https://api.github.com".to_string(),
ntfy_url: None,
ntfy_token: None,
revue_url: None,
revue_token: None,
}
}
}
Expand Down
97 changes: 97 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub fn now_rfc3339() -> String {
pub struct Db {
pub pool: SqlitePool,
ledger_lock: Arc<Mutex<()>>,
coverage_lock: Arc<Mutex<()>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
Expand Down Expand Up @@ -134,6 +135,7 @@ impl Db {
Ok(Self {
pool,
ledger_lock: Arc::new(Mutex::new(())),
coverage_lock: Arc::new(Mutex::new(())),
})
}

Expand Down Expand Up @@ -408,6 +410,43 @@ impl Db {
Ok(row)
}

/// Atomically enqueue multiple batch rows (e.g. full-repo area batches) in one transaction.
pub async fn enqueue_review_batches(
&self,
repo: &str,
kind: &str,
batches_json: &[String],
) -> Result<QueueRow> {
let now = now_rfc3339();
let mut tx = self.pool.begin().await?;
let mut first_id: Option<i64> = None;
for paths_json in batches_json {
let id = sqlx::query_scalar::<_, i64>(
"INSERT INTO queue (repo, kind, pr_number, paths_json, state, created_at, updated_at)
VALUES (?1, ?2, NULL, ?3, 'waiting', ?4, ?4) RETURNING id",
)
.bind(repo)
.bind(kind)
.bind(paths_json)
.bind(&now)
.fetch_one(&mut *tx)
.await?;
if first_id.is_none() {
first_id = Some(id);
}
}
let first_id = first_id.context("batches_json must be non-empty")?;
let row = sqlx::query_as::<_, QueueRow>(
"SELECT id, repo, kind, pr_number, paths_json, priority, state, not_before, created_at, updated_at
FROM queue WHERE id = ?1",
)
.bind(first_id)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
Ok(row)
}

pub async fn list_queue(&self, repo: Option<&str>) -> Result<Vec<QueueRow>> {
let rows = match repo {
Some(r) => {
Expand Down Expand Up @@ -766,6 +805,7 @@ impl Db {
upserts: &[FileCoverageState],
new_cursor: Option<&str>,
) -> Result<()> {
let _guard = self.coverage_lock.lock().await;
let mut tx = self.pool.begin().await?;
for path in deleted_paths {
sqlx::query("DELETE FROM file_coverage WHERE repo = ?1 AND path = ?2")
Expand Down Expand Up @@ -813,6 +853,63 @@ impl Db {
Ok(())
}

/// Serialised read-modify-write for Revue coverage reports: only touches reported paths and
/// preserves newer unreviewed changes if the report is for a stale commit/blob.
pub async fn apply_revue_coverage(
&self,
repo: &str,
commit_sha: &str,
reported: &[(String, Option<String>)],
) -> Result<Vec<FileCoverageState>> {
let _guard = self.coverage_lock.lock().await;
let mut tx = self.pool.begin().await?;
for (path, blob_sha) in reported {
if crate::coverage::is_excluded_path(path) {
continue;
}
let existing: Option<(Option<String>, Option<String>, i64)> = sqlx::query_as(
"SELECT reviewed_blob, reviewed_commit, unreviewed_lines
FROM file_coverage WHERE repo = ?1 AND path = ?2",
)
.bind(repo)
.bind(path)
.fetch_optional(&mut *tx)
.await?;

// If an existing row already has a different reviewed_commit and newer unreviewed
// lines, and the incoming report's blob does not match, avoid clearing newer changes.
if let Some((ref cur_blob, Some(ref cur_commit), unrev)) = existing
&& cur_commit != commit_sha
&& unrev > 0
&& blob_sha.is_some()
&& cur_blob.as_deref() != blob_sha.as_deref()
{
continue;
}

sqlx::query(
"INSERT INTO file_coverage (repo, path, reviewed_blob, reviewed_commit, by, unreviewed_lines, unreviewed_since, excluded)
VALUES (?1, ?2, ?3, ?4, 'revue', 0, NULL, 0)
ON CONFLICT(repo, path) DO UPDATE SET
reviewed_blob = COALESCE(excluded.reviewed_blob, file_coverage.reviewed_blob),
reviewed_commit = excluded.reviewed_commit,
by = 'revue',
unreviewed_lines = 0,
unreviewed_since = NULL,
excluded = 0",
)
.bind(repo)
.bind(path)
.bind(blob_sha)
.bind(commit_sha)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
drop(_guard);
self.list_file_coverage(repo).await
}

/// Insert or update a finding deduplicated by `(repo, fingerprint)`, preserving existing status.
/// Returns `(finding_id, is_new)`.
pub async fn upsert_finding(
Expand Down
Loading