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
2 changes: 2 additions & 0 deletions migrations/0003_refill_samples.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Persist dated refill window samples so the 7-day rolling maximum survives save/load.
ALTER TABLE budget_state ADD COLUMN refill_samples_json TEXT NOT NULL DEFAULT '[]';
178 changes: 128 additions & 50 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use jiff::{SignedDuration, Timestamp};
use serde::{Deserialize, Serialize};
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
use sqlx::{FromRow, SqlitePool};
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
Expand Down Expand Up @@ -42,6 +43,8 @@ pub struct BudgetStateRow {
pub pool: String,
pub limit_per_hour: i64,
pub refill_minutes: i64,
#[serde(default)]
pub refill_samples_json: String,
pub remaining: i64,
pub next_free_at: Option<String>,
pub confidence: String,
Expand Down Expand Up @@ -168,13 +171,11 @@ impl Db {
.await?;

let full_name = format!("{owner}/{name}");
sqlx::query(
"INSERT OR IGNORE INTO budget_state (repo, updated_at) VALUES (?1, ?2)",
)
.bind(&full_name)
.bind(&now)
.execute(&self.pool)
.await?;
sqlx::query("INSERT OR IGNORE INTO budget_state (repo, updated_at) VALUES (?1, ?2)")
.bind(&full_name)
.bind(&now)
.execute(&self.pool)
.await?;

Ok(())
}
Expand Down Expand Up @@ -283,33 +284,57 @@ impl Db {

pub async fn load_budget_ledger(&self, repo: &str) -> Result<BudgetLedger> {
let state = sqlx::query_as::<_, BudgetStateRow>(
"SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
"SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
FROM budget_state WHERE repo = ?1",
)
.bind(repo)
.fetch_optional(&self.pool)
.await?;

let spends_rows = sqlx::query_as::<_, SpendRow>(
"SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at
FROM spends WHERE repo = ?1 ORDER BY at DESC LIMIT 50",
)
.bind(repo)
.fetch_all(&self.pool)
.await?;

let mut ledger = BudgetLedger::default();
let mut state_updated_at: Option<Timestamp> = None;
if let Some(s) = state {
ledger.limit = u32::try_from(s.limit_per_hour.max(1)).unwrap_or(1);
ledger.refill_minutes = u32::try_from(s.refill_minutes.max(60)).unwrap_or(60);
ledger.refill_samples =
serde_json::from_str(&s.refill_samples_json).unwrap_or_default();
ledger.next_free_at = s.next_free_at.as_deref().and_then(|v| v.parse().ok());
ledger.fleet_cooldown_until = s
.fleet_cooldown_until
.as_deref()
.and_then(|v| v.parse().ok());
ledger.confidence = Confidence::parse(&s.confidence);
ledger.last_observed_at = s.updated_at.parse().ok();
state_updated_at = s.updated_at.parse().ok();
ledger.last_observed_at = state_updated_at;
}

// Load all spends within the active refill/lookback window (plus any provisional rows),
// with no row cap so repos with limit > 50 never undercount active spends.
let spends_rows = if let Some(updated_at) = state_updated_at {
let anchor = updated_at.min(Timestamp::now());
// Add 1 minute margin so RFC3339 fractional-second ordering never drops a boundary row.
let lookback_mins = i64::from(ledger.refill_minutes.max(180)) + 1;
let cutoff = (anchor - SignedDuration::from_mins(lookback_mins)).to_string();
sqlx::query_as::<_, SpendRow>(
"SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at
FROM spends
WHERE repo = ?1 AND (at >= ?2 OR state = 'provisional')
ORDER BY at DESC",
)
.bind(repo)
.bind(&cutoff)
.fetch_all(&self.pool)
.await?
} else {
sqlx::query_as::<_, SpendRow>(
"SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at
FROM spends WHERE repo = ?1 ORDER BY at DESC",
)
.bind(repo)
.fetch_all(&self.pool)
.await?
};

for sr in spends_rows {
if let Ok(at) = sr.at.parse::<Timestamp>() {
ledger.spends.push(SpendRecord {
Expand All @@ -329,8 +354,8 @@ impl Db {
Ok(ledger)
}

/// Serialise load-modify-save of a repo's budget ledger so concurrent webhook deliveries
/// cannot clobber each other's throttle deadlines.
/// Serialise load-modify-save of a repo's budget ledger so concurrent webhook and poll
/// updates cannot clobber each other's throttle deadlines.
pub async fn update_budget_ledger<F>(
&self,
repo: &str,
Expand All @@ -343,19 +368,37 @@ impl Db {
let _guard = self.ledger_lock.lock().await;
let mut ledger = self.load_budget_ledger(repo).await?;
mutate(&mut ledger);
self.save_budget_ledger(repo, &ledger, now).await?;
self.save_budget_ledger_unlocked(repo, &ledger, now).await?;
Ok(ledger)
}

pub async fn save_budget_ledger(&self, repo: &str, ledger: &BudgetLedger, now: Timestamp) -> Result<()> {
pub async fn save_budget_ledger(
&self,
repo: &str,
ledger: &BudgetLedger,
now: Timestamp,
) -> Result<()> {
let _guard = self.ledger_lock.lock().await;
self.save_budget_ledger_unlocked(repo, ledger, now).await
}

async fn save_budget_ledger_unlocked(
&self,
repo: &str,
ledger: &BudgetLedger,
now: Timestamp,
) -> Result<()> {
let snap = ledger.snapshot(now);
let now_str = now.to_string();
let refill_samples_json = serde_json::to_string(&ledger.refill_samples)?;
let mut tx = self.pool.begin().await?;
sqlx::query(
"INSERT INTO budget_state (repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at)
VALUES (?1, 'pooled', ?2, ?3, ?4, ?5, ?6, ?7, ?8)
"INSERT INTO budget_state (repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at)
VALUES (?1, 'pooled', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(repo) DO UPDATE SET
limit_per_hour = excluded.limit_per_hour,
refill_minutes = excluded.refill_minutes,
refill_samples_json = excluded.refill_samples_json,
remaining = excluded.remaining,
next_free_at = excluded.next_free_at,
confidence = excluded.confidence,
Expand All @@ -365,30 +408,34 @@ impl Db {
.bind(repo)
.bind(i64::from(snap.limit))
.bind(i64::from(snap.refill_minutes))
.bind(&refill_samples_json)
.bind(i64::from(snap.remaining))
.bind(snap.next_free_at.map(|t| t.to_string()))
.bind(snap.confidence.as_str())
.bind(snap.fleet_cooldown_until.map(|t| t.to_string()))
.bind(&now_str)
.execute(&self.pool)
.execute(&mut *tx)
.await?;

let mut active_provisional_at: HashSet<String> = HashSet::new();
for sp in &ledger.spends {
let at_str = sp.at.to_string();
let exists: Option<(i64, String)> = sqlx::query_as(
"SELECT id, state FROM spends WHERE repo = ?1 AND at = ?2 LIMIT 1",
)
.bind(repo)
.bind(&at_str)
.fetch_optional(&self.pool)
.await?;
if sp.state == SpendState::Provisional {
active_provisional_at.insert(at_str.clone());
}
let exists: Option<(i64, String)> =
sqlx::query_as("SELECT id, state FROM spends WHERE repo = ?1 AND at = ?2 LIMIT 1")
.bind(repo)
.bind(&at_str)
.fetch_optional(&mut *tx)
.await?;

match exists {
Some((id, cur_state)) if cur_state != sp.state.as_str() => {
sqlx::query("UPDATE spends SET state = ?1 WHERE id = ?2")
.bind(sp.state.as_str())
.bind(id)
.execute(&self.pool)
.execute(&mut *tx)
.await?;
}
None => {
Expand All @@ -404,12 +451,30 @@ impl Db {
.bind(sp.check_run_id.and_then(|v| i64::try_from(v).ok()))
.bind(sp.state.as_str())
.bind(&now_str)
.execute(&self.pool)
.execute(&mut *tx)
.await?;
}
_ => {}
}
}

// Remove provisional spends dropped from the ledger (e.g. rate-limited check runs)
// while keeping all confirmed spend history intact.
let stored_provisional: Vec<(i64, String)> =
sqlx::query_as("SELECT id, at FROM spends WHERE repo = ?1 AND state = 'provisional'")
.bind(repo)
.fetch_all(&mut *tx)
.await?;
for (id, at_str) in stored_provisional {
if !active_provisional_at.contains(&at_str) {
sqlx::query("DELETE FROM spends WHERE id = ?1")
.bind(id)
.execute(&mut *tx)
.await?;
}
}

tx.commit().await?;
Ok(())
}

Expand All @@ -427,7 +492,7 @@ impl Db {

pub async fn list_budget_states(&self) -> Result<Vec<BudgetStateRow>> {
let rows = sqlx::query_as::<_, BudgetStateRow>(
"SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
"SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
FROM budget_state ORDER BY repo",
)
.fetch_all(&self.pool)
Expand All @@ -437,7 +502,7 @@ impl Db {

pub async fn get_budget_state(&self, repo: &str) -> Result<Option<BudgetStateRow>> {
let row = sqlx::query_as::<_, BudgetStateRow>(
"SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
"SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at
FROM budget_state WHERE repo = ?1",
)
.bind(repo)
Expand Down Expand Up @@ -636,13 +701,15 @@ impl Db {
) -> Result<()> {
let now = now_rfc3339();
if let Some(nb) = not_before {
sqlx::query("UPDATE queue SET state = ?1, not_before = ?2, updated_at = ?3 WHERE id = ?4")
.bind(state)
.bind(nb)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?;
sqlx::query(
"UPDATE queue SET state = ?1, not_before = ?2, updated_at = ?3 WHERE id = ?4",
)
.bind(state)
.bind(nb)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?;
} else {
sqlx::query("UPDATE queue SET state = ?1, updated_at = ?2 WHERE id = ?3")
.bind(state)
Expand Down Expand Up @@ -720,21 +787,31 @@ impl Db {
Ok(rows)
}

pub async fn update_finding_status(&self, id: i64, new_status: &str, actor: &str) -> Result<bool> {
pub async fn update_finding_status(
&self,
id: i64,
new_status: &str,
actor: &str,
) -> Result<bool> {
let mut tx = self.pool.begin().await?;
let current: Option<String> =
sqlx::query_scalar("SELECT status FROM findings WHERE id = ?1")
.bind(id)
.fetch_optional(&self.pool)
.fetch_optional(&mut *tx)
.await?;
let Some(from_status) = current else {
return Ok(false);
};
let now = now_rfc3339();
sqlx::query("UPDATE findings SET status = ?1 WHERE id = ?2")
let res = sqlx::query("UPDATE findings SET status = ?1 WHERE id = ?2 AND status = ?3")
.bind(new_status)
.bind(id)
.execute(&self.pool)
.bind(&from_status)
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
anyhow::bail!("concurrent status update conflict for finding {id}");
}
sqlx::query(
"INSERT INTO finding_events (finding_id, at, from_status, to_status, actor)
VALUES (?1, ?2, ?3, ?4, ?5)",
Expand All @@ -744,8 +821,9 @@ impl Db {
.bind(&from_status)
.bind(new_status)
.bind(actor)
.execute(&self.pool)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(true)
}

Expand Down Expand Up @@ -986,12 +1064,12 @@ impl Db {
.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.
// lines, and the incoming report's blob is absent or 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()
&& (blob_sha.is_none() || cur_blob.as_deref() != blob_sha.as_deref())
{
continue;
}
Expand Down
Loading